13 Commits
Author SHA1 Message Date
lumither c466ba48a9 feat(Makefile) Makefile fix&cleanup 2025-11-03 13:49:56 -05:00
lumither 330dd7c2a6 feat(Makefile) add cr support 2025-11-03 13:21:13 -05:00
lumither 1966e0059c feat(action) add release build 2025-11-03 01:54:28 -05:00
lumither 3f5f23a4e8 feat(action) canary container build
build canary nocturne image / build (push) Has been cancelled
2025-11-03 01:15:46 -05:00
lumither 7205faddbe feat(blog) change foreground color in dark mode 2025-10-21 21:50:41 -04:00
lumither f1d43e6799 fix(deploy) add db auto-restart 2025-10-18 17:30:42 -04:00
lumither 3a4af1ae8d feat(migration) add migration 2025-10-13 14:36:21 -04:00
lumither 02e7166fcb feat(frontend) new tag filter, new landing page 2025-10-13 02:59:21 -04:00
lumither 314f5780fd fix(blog::api) fix pagination for GET posts 2025-10-11 11:51:06 -04:00
lumither b1a55c363f feat(backend::api) add post tag filter 2025-10-09 23:26:08 -04:00
lumither f3cc387013 draft(daemon) module init 2025-10-08 12:48:43 -04:00
lumither 2a56263382 draft(gateway) module init 2025-10-08 12:43:47 -04:00
lumither cd39abbd45 ref(frontend) several minor updates 2025-10-08 12:42:54 -04:00
51 changed files with 872 additions and 163 deletions

No files matched your search

+5 -1
View File
@@ -16,4 +16,8 @@ WORK_DIR=/nocturne
# frontend settings # frontend settings
API_LOCAL_URL=http://backend:3001 API_LOCAL_URL=http://backend:3001
API_REMOTE_URL=https://lumither.com/api API_REMOTE_URL=https://lumither.com/api
# deployment
USE_CR=true
CHANNEL=release
+64
View File
@@ -0,0 +1,64 @@
name: build canary nocturne image
on:
push:
branches:
- master
env:
REGISTRY: cr.lmt.moe
TAG: canary
PROJECT: nocturne
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v4
- name: setup builder
uses: docker/setup-buildx-action@v3
- name: registry login
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
- name: build containers
run: |
make build
- name: tag and push
run: |
PROJECT_NAME=$(basename "$PWD")
ALL_IMAGES=$(docker compose -f prod.compose.yaml config --services 2>/dev/null)
PULLED_IMAGES=$(docker compose -f prod.compose.yaml config 2>/dev/null \
| awk '/image:/ {print $2}' \
| sort -u \
| sed 's/:.*//' \
)
TO_PUSH=$(comm -23 \
<(echo "$ALL_IMAGES" | sort) \
<(echo "$PULLED_IMAGES") \
)
FMT_STRING=$(echo "$TO_PUSH" | xargs printf '%s, ' | sed 's/, $//')
echo "services to push: $FMT_STRING"
for SERVICE in $TO_PUSH; do
LOCAL_TAG="${PROJECT_NAME}-${SERVICE}:latest"
REMOTE_TAG="${REGISTRY}/${PROJECT}/${SERVICE}:${TAG}"
if docker image inspect "$LOCAL_TAG" >/dev/null 2>&1; then
echo "Pushing $REMOTE_TAG"
docker tag "$LOCAL_TAG" "$REMOTE_TAG"
docker push "$REMOTE_TAG"
else
echo "warn: image $LOCAL_TAG not found, skipping $SERVICE"
fi
done
+64
View File
@@ -0,0 +1,64 @@
name: build release nocturne image
on:
push:
branches:
- release
env:
REGISTRY: cr.lmt.moe
TAG: release
PROJECT: nocturne
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v4
- name: setup builder
uses: docker/setup-buildx-action@v3
- name: registry login
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
- name: build containers
run: |
make build
- name: tag and push
run: |
PROJECT_NAME=$(basename "$PWD")
ALL_IMAGES=$(docker compose -f prod.compose.yaml config --services 2>/dev/null)
PULLED_IMAGES=$(docker compose -f prod.compose.yaml config 2>/dev/null \
| awk '/image:/ {print $2}' \
| sort -u \
| sed 's/:.*//' \
)
TO_PUSH=$(comm -23 \
<(echo "$ALL_IMAGES" | sort) \
<(echo "$PULLED_IMAGES") \
)
FMT_STRING=$(echo "$TO_PUSH" | xargs printf '%s, ' | sed 's/, $//')
echo "services to push: $FMT_STRING"
for SERVICE in $TO_PUSH; do
LOCAL_TAG="${PROJECT_NAME}-${SERVICE}:latest"
REMOTE_TAG="${REGISTRY}/${PROJECT}/${SERVICE}:${TAG}"
if docker image inspect "$LOCAL_TAG" >/dev/null 2>&1; then
echo "Pushing $REMOTE_TAG"
docker tag "$LOCAL_TAG" "$REMOTE_TAG"
docker push "$REMOTE_TAG"
else
echo "warn: image $LOCAL_TAG not found, skipping $SERVICE"
fi
done
+38 -3
View File
@@ -3,7 +3,42 @@ ifeq ($(ARCH), arm64)
ARCH := aarch64 ARCH := aarch64
endif endif
.PHONY: up ifneq (,$(wildcard ./.env))
clean: include ./.env
echo "todo" export
endif
ifneq (,$(wildcard ./.env.local))
include ./.env.local
export
endif
USE_CR ?= false
CHANNEL ?= release
ifeq ($(USE_CR), true)
COMPOSE_FILE := prod.cr.compose.yaml
else
COMPOSE_FILE := prod.compose.yaml
endif
DOCKER_ENV := ARCH=$(ARCH) TAG=$(CHANNEL)
DOCKER_COMPOSE := $(DOCKER_ENV) docker compose -f $(COMPOSE_FILE)
.PHONY: all
all:up
.PHONY: build
build:
$(DOCKER_COMPOSE) pull
$(DOCKER_COMPOSE) build
.PHONY: up
up:
$(DOCKER_COMPOSE) up -d
.PHONY: down
down:
$(DOCKER_COMPOSE) down
.PHONY: clean
clean:
$(DOCKER_COMPOSE) down --rmi all --volumes
+1
View File
@@ -8,6 +8,7 @@ macros = { path = "../macros" }
markdown = { path = "../markdown" } markdown = { path = "../markdown" }
axum = { version = "0.8.1", features = ["macros"] } axum = { version = "0.8.1", features = ["macros"] }
axum-extra = { version = "0.10.3", features = ["query"] }
tracing = { version = "0.1.41", features = ["log"] } tracing = { version = "0.1.41", features = ["log"] }
git2 = "0.20.0" git2 = "0.20.0"
chrono = { version = "0.4.39", features = ["serde"] } chrono = { version = "0.4.39", features = ["serde"] }
+14 -13
View File
@@ -1,16 +1,17 @@
use chrono::Utc; // use chrono::Utc;
use git2::Repository; // use git2::Repository;
fn main() { fn main() {
let repo = Repository::open("../..").expect("failed to open repository"); // let repo = Repository::open("../..").expect("failed to open repository");
let commit = repo // let commit = repo
.head() // .head()
.expect("failed to get HEAD") // .expect("failed to get HEAD")
.peel_to_commit() // .peel_to_commit()
.expect("failed to get HEAD commit"); // .expect("failed to get HEAD commit");
let hash = commit.id().to_string(); // let hash = commit.id().to_string();
let utc_timestamp = Utc::now().date_naive().format("%Y%m%d").to_string(); // let utc_timestamp = Utc::now().date_naive().format("%Y%m%d").to_string();
let pkg_version = env!("CARGO_PKG_VERSION"); // let pkg_version = env!("CARGO_PKG_VERSION");
let build_id = format!("{}:{}@{}", pkg_version, &hash[..8], utc_timestamp); // let build_id = format!("{}:{}@{}", pkg_version, &hash[..8], utc_timestamp);
println!("cargo:rustc-env=BUILD_ID={}", build_id); // println!("cargo:rustc-env=BUILD_ID={}", build_id);
println!("cargo:rustc-env=BUILD_ID=undefined");
} }
@@ -0,0 +1,20 @@
WITH filtered_posts AS
(SELECT p.id, p.date_created
FROM posts p
WHERE $1::text[] IS NULL
OR (
CASE
WHEN $4 THEN (SELECT COUNT(DISTINCT t.name)
FROM post_tag pt
JOIN tags t ON pt.tag = t.id
WHERE pt.post = p.id
AND t.name = ANY ($1::text[])) = cardinality($1)
ELSE EXISTS (SELECT 1
FROM post_tag pt
JOIN tags t ON pt.tag = t.id
WHERE pt.post = p.id
AND t.name = ANY ($1::text[]))
END
))
SELECT COUNT(*) AS total_count
FROM filtered_posts;
@@ -4,17 +4,65 @@ use crate::{
utils::axum_response::{err_resp, succ_resp}, utils::axum_response::{err_resp, succ_resp},
}; };
use axum::{ use std::collections::HashSet;
extract::{Query, State},
http::StatusCode, use axum::{extract::State, http::StatusCode, response::IntoResponse};
response::IntoResponse, use axum_extra::extract::Query;
};
use chrono::NaiveDate; use chrono::NaiveDate;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::json; use serde_json::json;
use sqlx::{FromRow, PgPool, query_as}; use sqlx::{query_as, FromRow, PgPool};
use uuid::Uuid; use uuid::Uuid;
fn tags_deserializer<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialize_each = |input: String| -> Result<Vec<String>, D::Error> {
Ok(input.split(',').map(|s| s.to_string()).collect())
};
#[derive(Deserialize)]
#[serde(untagged)]
enum Cardinality {
One(String),
Many(Vec<String>),
}
let cardinality: Option<Cardinality> = Deserialize::deserialize(deserializer)?;
let mut tags = HashSet::new();
match cardinality {
Some(Cardinality::One(s)) => {
for item in deserialize_each(s)? {
let item = item.trim().to_string();
if !item.is_empty() {
tags.insert(item);
}
}
let ret = tags.into_iter().collect::<Vec<_>>();
Ok(if ret.is_empty() { None } else { Some(ret) })
}
Some(Cardinality::Many(v)) => {
for items in v
.into_iter()
.map(deserialize_each)
.collect::<Result<Vec<_>, _>>()?
{
for item in items {
let item = item.trim().to_string();
if !item.is_empty() {
tags.insert(item);
}
}
}
let ret = tags.into_iter().collect::<Vec<_>>();
Ok(if ret.is_empty() { None } else { Some(ret) })
}
None => Ok(None),
}
}
#[derive(FromRow, Serialize)] #[derive(FromRow, Serialize)]
struct PostBriefModel { struct PostBriefModel {
id: Uuid, id: Uuid,
@@ -29,9 +77,15 @@ struct PostBriefModel {
} }
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
pub struct Pagination { pub struct SearchParams {
page: Option<u32>, page: Option<u32>,
page_size: Option<u32>, page_size: Option<u32>,
#[serde(default, deserialize_with = "tags_deserializer")]
tags: Option<Vec<String>>,
#[serde(default)]
match_all: bool,
} }
#[derive(Serialize)] #[derive(Serialize)]
@@ -52,15 +106,25 @@ struct UuidRow {
id: Uuid, id: Uuid,
} }
const I32_PLACEHOLDER: i32 = 0;
const COUNT_TAG_FILTERED_POSTS: &str = include_str!("count_tag_filtered_posts.sql");
const SELECT_POST_WITH_TAG_FILTER_PAGINATED: &str =
include_str!("select_post_with_tag_filter_paginated.sql");
const GET_POST_WITH_BRIEF_MODEL: &str = include_str!("get_post_with_brief_model.sql"); const GET_POST_WITH_BRIEF_MODEL: &str = include_str!("get_post_with_brief_model.sql");
pub async fn handler( pub async fn handler(
State(db): State<PgPool>, State(db): State<PgPool>,
Query(pagination): Query<Pagination>, Query(search_params): Query<SearchParams>,
) -> impl IntoResponse { ) -> impl IntoResponse {
let page = pagination.page.unwrap_or(1); let page = search_params.page.unwrap_or(1);
let page_size = pagination.page_size.unwrap_or(PAGE_SIZE); let page_size = search_params.page_size.unwrap_or(PAGE_SIZE);
let page_count = match sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM posts")
let page_count = match sqlx::query_scalar::<_, i64>(COUNT_TAG_FILTERED_POSTS)
.bind(&search_params.tags)
.bind(I32_PLACEHOLDER) // not used, but help sqlx/psql hit cache
.bind(I32_PLACEHOLDER)
.bind(search_params.match_all)
.fetch_one(&db) .fetch_one(&db)
.await .await
{ {
@@ -84,13 +148,13 @@ pub async fn handler(
let offset = page_size * (page - 1); let offset = page_size * (page - 1);
let ids = match query_as::<_, UuidRow>( let ids = match query_as::<_, UuidRow>(SELECT_POST_WITH_TAG_FILTER_PAGINATED)
"SELECT id FROM posts ORDER BY date_created DESC LIMIT $1 OFFSET $2", .bind(search_params.tags)
) .bind(page_size as i32)
.bind(page_size as i32) .bind(offset as i32)
.bind(offset as i32) .bind(search_params.match_all)
.fetch_all(&db) .fetch_all(&db)
.await .await
{ {
Ok(res) => res.into_iter().map(|item| item.id).collect::<Vec<_>>(), Ok(res) => res.into_iter().map(|item| item.id).collect::<Vec<_>>(),
Err(e) => return err_resp_log!(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()), Err(e) => return err_resp_log!(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
@@ -0,0 +1,22 @@
WITH filtered_posts AS
(SELECT p.id, p.date_created
FROM posts p
WHERE $1::text[] IS NULL
OR (
CASE
WHEN $4 THEN (SELECT COUNT(DISTINCT t.name)
FROM post_tag pt
JOIN tags t ON pt.tag = t.id
WHERE pt.post = p.id
AND t.name = ANY ($1::text[])) = cardinality($1)
ELSE EXISTS (SELECT 1
FROM post_tag pt
JOIN tags t ON pt.tag = t.id
WHERE pt.post = p.id
AND t.name = ANY ($1::text[]))
END
))
SELECT id
FROM filtered_posts
ORDER BY date_created DESC
LIMIT $2 OFFSET $3;
+2 -2
View File
@@ -5,6 +5,6 @@ RUN ["cargo", "build", "-r"]
FROM gcr.io/distroless/cc AS production FROM gcr.io/distroless/cc AS production
ARG ARCH ARG ARCH
COPY --from=builder /app/target/release/api_server ./api_server COPY --from=builder /app/target/release/server ./server
COPY --from=builder /usr/lib/${ARCH}-linux-gnu/libz.so.1 /usr/lib/${ARCH}-linux-gnu/ COPY --from=builder /usr/lib/${ARCH}-linux-gnu/libz.so.1 /usr/lib/${ARCH}-linux-gnu/
ENTRYPOINT ["./api_server"] ENTRYPOINT ["./server"]
+3
View File
@@ -0,0 +1,3 @@
target/
Cargo.lock
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "daemon"
version = "0.1.0"
edition = "2024"
[dependencies]
clap = { version = "4.5.47", features = ["derive"] }
containerd-client = "0.8.0"
tokio = { version = "1.45.1", features = ["macros", "rt-multi-thread"] }
+13
View File
@@ -0,0 +1,13 @@
.PHONY: rebuild
rebuild:
cargo clean
cargo build
.PHONY: rebuild-release
rebuild-release:
cargo clean
cargo build -r
.PHONY: run
run:
sudo ./target/debug/daemon
+1
View File
@@ -0,0 +1 @@
mod pull;
View File
Whitespace-only changes.
+8
View File
@@ -0,0 +1,8 @@
{
"images": [
{
"id": "",
"image": ""
}
]
}
View File
Whitespace-only changes.
+89
View File
@@ -0,0 +1,89 @@
mod actions;
mod config;
use clap::Parser;
use containerd_client::tonic::Request;
use containerd_client::{
connect,
services::v1::{transfer_client::TransferClient, TransferOptions, TransferRequest},
to_any,
types::transfer::OciRegistry,
types::transfer::{ImageStore, UnpackConfiguration},
types::Platform,
with_namespace,
};
use std::env::consts;
#[derive(Parser, Debug)]
struct Args {
/// containerd namespace
#[arg(short, long, default_value = "nocturne")]
namespace: String,
/// containerd socket
#[arg(short, long, default_value = "/run/containerd/containerd.sock")]
socket: String,
}
const IMAGE: &str = "docker.io/library/alpine:latest";
#[tokio::main]
async fn main() {
let args = Args::parse();
let arch = match consts::ARCH {
"x86_64" => "amd64",
"aarch64" => "arm64",
_ => consts::ARCH,
};
dbg!(&args);
let channel = connect(&args.socket).await.expect("failed to bind socket");
let mut client = TransferClient::new(channel.clone());
let registry = OciRegistry {
reference: IMAGE.to_string(),
resolver: Default::default(),
};
let platform = Platform {
os: "linux".to_string(),
architecture: arch.to_string(),
variant: "".to_string(),
os_version: "".to_string(),
};
let destination = ImageStore {
name: IMAGE.to_string(),
platforms: vec![platform.clone()],
unpacks: vec![UnpackConfiguration {
platform: Some(platform),
..Default::default()
}],
..Default::default()
};
let anys = to_any(&registry);
let anyd = to_any(&destination);
println!(
"Pulling image for linux/{} from source: {:?}",
arch, registry
);
let request = TransferRequest {
source: Some(anys),
destination: Some(anyd),
options: Some(TransferOptions {
..Default::default()
}),
};
// let request = Request::new(request);
let req = with_namespace!(request, args.namespace);
client
.transfer(req)
.await
.expect("unable to transfer image");
}
+2 -2
View File
@@ -27,10 +27,10 @@ services:
- ./blog_posts_git:/app/blog_posts_git:ro - ./blog_posts_git:/app/blog_posts_git:ro
env_file: env_file:
- ./container/dev/.env - ./container/dev/.env
postgres: postgres:
image: postgres:16.3 image: postgres:16.3
ports: ports:
- 5432:5432 - "5432:5432"
env_file: env_file:
- ./container/dev/.env - ./container/dev/.env
+8
View File
@@ -0,0 +1,8 @@
.PHONY:all
all: standalone
.PHONY: standalone
standalone:
npm run build
cp -r public .next/standalone/ && cp -r .next/static .next/standalone/.next/
+32 -11
View File
@@ -4,6 +4,8 @@ import { Chip } from '@nextui-org/react';
import Image from 'next/image'; import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import { MdCalendarMonth, MdNorthEast } from 'react-icons/md'; import { MdCalendarMonth, MdNorthEast } from 'react-icons/md';
import { HighlightSelector } from '@/app/(pages)/blog/post/components/AnimationPostList';
import TagChip from '@/app/(pages)/blog/TagChip';
interface Post { interface Post {
id: string, id: string,
@@ -19,15 +21,20 @@ interface Post {
type Props = { type Props = {
post: Post post: Post
highlightSelector: HighlightSelector,
} }
function BlogPostCard({ post }: Props) { function BlogPostCard({ post, highlightSelector }: Props) {
const highlightTags = highlightSelector?.tags;
return ( return (
<div className={ `w-full` }> <div className={ `w-full` }>
<Card as={ Link } href={ `/blog/post/${ post.id }` } <Card
className={ `group` } as={ Link } href={ `/blog/post/${ post.identifier }` }
isPressable className={ `group w-full dark:bg-[#353540]` }
isHoverable isPressable
isHoverable
> >
{ post.header_img && <div className={ `w-full overflow h-80 relative` }> { post.header_img && <div className={ `w-full overflow h-80 relative` }>
@@ -63,12 +70,26 @@ function BlogPostCard({ post }: Props) {
<div className={ `flex flex-row flex-wrap justify-between w-full` }> <div className={ `flex flex-row flex-wrap justify-between w-full` }>
<div> <div>
<ul className={ `flex flex-row flex-wrap` }> <ul className={ `flex flex-row flex-wrap` }>
{ {/*highlight*/
post.tags.map((tag: string, key: any) => ( post.tags
<li key={ key } className={ `mx-1 mb-1` }> .filter((tag) => highlightTags?.includes(tag))
<Chip>{ tag }</Chip> .sort()
</li> .map((tag: string, key: any) => (
)) <li key={ key } className={ `mx-1 mb-1` }>
<TagChip tagName={ tag } isHighlighted={ true } />
</li>
))
}
{/*normal */
post.tags
.filter((tag) => !highlightTags?.includes(tag))
.sort()
.map((tag: string, key: any) => (
<li key={ key } className={ `mx-1 mb-1` }>
<TagChip tagName={ tag } isHighlighted={ false } />
</li>
))
} }
</ul> </ul>
</div> </div>
+7 -2
View File
@@ -8,7 +8,9 @@ import { useScreenSizeTrigger } from '@/app/(pages)/public/screenSizeTrigger';
const Pagination = ({ total }: { const Pagination = ({ total }: {
total: number, total: number,
}) => { }) => {
const parsePage = Number(useSearchParams().get('page')); const searchParams = useSearchParams();
const parsePage = Number(searchParams.get('page'));
const currPage = parsePage > 0 ? parsePage : 1; const currPage = parsePage > 0 ? parsePage : 1;
const router = useRouter(); const router = useRouter();
@@ -27,7 +29,10 @@ const Pagination = ({ total }: {
color={ 'default' } color={ 'default' }
variant={ 'light' } variant={ 'light' }
onChange={ (page) => { onChange={ (page) => {
router.push(`?page=${ page }`, { scroll: false }); const params = new URLSearchParams(searchParams.toString());
params.set('page', page.toString());
const queryString = params.toString();
router.push(`?${ queryString }`, { scroll: false });
} } } }
/> />
</div> </div>
+10 -24
View File
@@ -1,33 +1,19 @@
'use server';
import React from 'react'; import React from 'react';
import BlogPostCard from '@/app/(pages)/blog/BlogPostCard'; import { Post } from '@/src/api/blog/post';
import AnimationPostList, { HighlightSelector } from '@/app/(pages)/blog/post/components/AnimationPostList';
import * as motion from 'motion/react-client'; interface Props {
import { fetchPostList } from '@/src/api/blog/post'; posts: Post[],
tags: string[] | undefined
}
const PostList = async ({ page }: { page: number }) => { const PostList = async ({ posts, tags }: Props) => {
try { try {
const postListResponse = await fetchPostList(page);
const posts = postListResponse.data.posts;
return ( return (
// blog list
<div className={ 'w-full' }> <div className={ 'w-full' }>
<ul className={ 'flex flex-col items-center w-full space-y-7' }> <AnimationPostList posts={ posts } highlight={ {
{ posts.map((post, key: number) => ( tags: tags
<li key={ key } className={ 'w-full' }> } } />
<motion.div
initial={ { y: 20, opacity: 0 } }
animate={ { y: 0, opacity: 1 } }
transition={ { ease: 'easeInOut', duration: 0.5, delay: key * .2 + .25 } }
>
<BlogPostCard post={ post } />
</motion.div>
</li>)
) }
</ul>
</div> </div>
); );
} catch (e: any) { } catch (e: any) {
+52
View File
@@ -0,0 +1,52 @@
'use client';
import React from 'react';
import { Chip } from '@nextui-org/react';
import { useRouter, useSearchParams } from 'next/navigation';
import { cn } from '@/src/utils';
interface TagChipProps {
tagName: string,
isHighlighted: boolean
}
const TagChip = ({ tagName, isHighlighted }: TagChipProps) => {
const router = useRouter();
const searchParams = useSearchParams();
const toggleTag = (e: React.MouseEvent<HTMLDivElement>) => {
e.stopPropagation();
e.preventDefault();
const params = new URLSearchParams(searchParams.toString());
const tags = params.getAll('tags');
if (tags.includes(tagName)) {
const newTags = tags.filter(t => t !== tagName);
params.delete('tags');
newTags.forEach(t => params.append('tags', t));
} else {
params.append('tags', tagName);
}
const queryString = params.toString();
router.push(`?${ queryString }`, { scroll: false });
};
return (
<div
onClick={ toggleTag }
className="cursor-pointer relative"
>
<Chip
className={ cn(
'hover:border-amber-400 hover:dark:border-amber-700 transition-all ',
!isHighlighted && 'dark:border-amber-50/25'
) }
variant={ 'bordered' }
color={ isHighlighted ? 'warning' : 'default' }
>{ tagName }</Chip>
</div>
);
};
export default TagChip;
+11
View File
@@ -0,0 +1,11 @@
import React from 'react';
const ToolBar = () => {
return (
<div className={ 'w-full' }>
</div>
);
};
export default ToolBar;
+30 -7
View File
@@ -1,6 +1,7 @@
import PostList from '@/app/(pages)/blog/PostList'; import PostList from '@/app/(pages)/blog/PostList';
import Pagination from '@/app/(pages)/blog/Pagination'; import Pagination from '@/app/(pages)/blog/Pagination';
import { fetchPostListPagination } from '@/src/api/blog/post'; import { fetchPostList } from '@/src/api/blog/post';
import ToolBar from '@/app/(pages)/blog/ToolBar';
async function Blog({ async function Blog({
@@ -9,18 +10,40 @@ async function Blog({
searchParams: Promise<{ [_: string]: string | string[] | undefined }> searchParams: Promise<{ [_: string]: string | string[] | undefined }>
}) { }) {
const parsePage = Number((await searchParams)?.page); const sp = await searchParams;
const parsePage = Number(sp?.page);
const currPage = parsePage > 0 ? parsePage : 1; const currPage = parsePage > 0 ? parsePage : 1;
const matchAll = Boolean(sp?.match_all);
const ensureList = (input: string | string[] | undefined): string[] | undefined => {
if (!input) {
return undefined;
}
if (typeof input === 'string') {
return [ input ];
} else {
return input;
}
};
const tags = ensureList(sp?.tags);
try { try {
const pagination = await fetchPostListPagination(); const postListResponse = await fetchPostList({
const pageCount = pagination.data.page_count; page: currPage,
match_all: matchAll,
tag_filter: tags
});
const pagination = postListResponse.data.pagination;
const posts = postListResponse.data.posts;
return ( return (
<div className={ 'w-full min-w-full space-y-4' }> <div className={ 'w-full min-w-full space-y-4' }>
<PostList page={ currPage } /> <ToolBar />
<Pagination total={ pageCount } /> <PostList posts={ posts } tags={ tags } />
<Pagination total={ pagination.page_count } />
</div> </div>
); );
} catch (e: any) { } catch (e: any) {
@@ -28,7 +51,7 @@ async function Blog({
<div className={ `flex h-full min-h-dvh w-full justify-center items-center` }> <div className={ `flex h-full min-h-dvh w-full justify-center items-center` }>
<div className={ `flex-row` }> <div className={ `flex-row` }>
<p className={ `text-xl font-bold` }> <p className={ `text-xl font-bold` }>
{ 'Unexpected Error [loading pagination]:' } { 'Unexpected Error [loading blog posts]:' }
</p> </p>
<p className={ `font-bold` }> <p className={ `font-bold` }>
{ e.message } { e.message }
@@ -12,7 +12,7 @@ const ButtonGoBack = () => {
<Button <Button
startContent={ <IoArrowBackOutline /> } startContent={ <IoArrowBackOutline /> }
variant={ 'light' } variant={ 'light' }
onClick={ () => router.back() } onPress={ () => router.back() }
> >
{ 'Back' } { 'Back' }
</Button> </Button>
@@ -33,7 +33,7 @@ const Footer = (props: Props) => {
return ( return (
<div className={ `w-full` }> <div className={ `w-full` }>
<div className={ 'flex transition bg-zinc-300/80 dark:bg-gray-600/25' }> <div className={ 'flex transition bg-zinc-300/80 dark:bg-[#1c1c22]/50' }>
<div className={ `p-8 w-full overflow-hidden` }> <div className={ `p-8 w-full overflow-hidden` }>
<div className={ 'relative' }> <div className={ 'relative' }>
<FaCreativeCommons <FaCreativeCommons
@@ -2,6 +2,7 @@ import React from 'react';
import Image from 'next/image'; import Image from 'next/image';
import { Chip } from '@nextui-org/react'; import { Chip } from '@nextui-org/react';
import { MdCalendarMonth } from 'react-icons/md'; import { MdCalendarMonth } from 'react-icons/md';
import TagChip from '@/app/(pages)/blog/post/[id]/TagChip';
type Props = { type Props = {
title: string; title: string;
@@ -50,7 +51,7 @@ const Headers = (post: Props) => {
{ {
post.tags.map((tag: string, key: any) => ( post.tags.map((tag: string, key: any) => (
<li key={ key } className={ `mx-1 mb-1` }> <li key={ key } className={ `mx-1 mb-1` }>
<Chip>{ tag }</Chip> <TagChip tag={ tag } />
</li> </li>
)) ))
} }
@@ -12,12 +12,12 @@ const MinifyPostCard = (props: Props) => {
const { post, desc } = props; const { post, desc } = props;
const img_url = post['header_img'] as string; const img_url = post['header_img'] as string;
return ( return (
<div className={ 'w-full transition hover:brightness-75' }> <div className={ 'w-full transition hover:brightness-90' }>
<Card isFooterBlurred <Card isFooterBlurred
className="w-full h-[300px] shadow-none border-0 rounded-none overflow-hidden" className="w-full h-[300px] shadow-none border-0 rounded-none overflow-hidden dark:bg-[#353540]"
as={ Link } as={ Link }
isPressable isPressable
href={ `/blog/post/${ post['id'] }` } href={ `/blog/post/${ post['identifier'] }` }
> >
<CardHeader className="absolute z-10 top-1 flex-col items-start"> <CardHeader className="absolute z-10 top-1 flex-col items-start">
<p className={ `text-tiny uppercase font-bold ${ img_url ? 'text-white/60' : 'text-black/60 dark:text-white/60' }` }>{ desc }</p> <p className={ `text-tiny uppercase font-bold ${ img_url ? 'text-white/60' : 'text-black/60 dark:text-white/60' }` }>{ desc }</p>
@@ -16,7 +16,7 @@ async function PostCard(props: Props) {
return ( return (
<div> <div>
<Card className={ `max-w-full relative` }> <Card className={ `max-w-full relative dark:bg-[#34343e]` }>
{/* card headers */ } {/* card headers */ }
<Headers title={ post.title } <Headers title={ post.title }
@@ -0,0 +1,20 @@
'use client';
import React from 'react';
import { Chip } from '@nextui-org/react';
import { useRouter } from 'next/navigation';
const TagChip = ({ tag }: { tag: string }) => {
const router = useRouter();
return (
<div onClick={ () => router.push(`/blog?tags=${ tag }`) }>
<Chip
className={ 'hover:border-amber-400 hover:dark:border-amber-700 transition-all dark:bg-[#353540] dark:border-amber-50/25' }
variant={ 'faded' }
>{ tag }</Chip>
</div>
);
};
export default TagChip;
@@ -0,0 +1,40 @@
'use client';
import React from 'react';
import BlogPostCard from '@/app/(pages)/blog/BlogPostCard';
import * as motion from 'motion/react-client';
import { AnimatePresence } from 'motion/react';
import { Post } from '@/src/api/blog/post';
export interface HighlightSelector {
tags?: string[];
}
interface Props {
posts: Post[];
highlight: HighlightSelector;
}
const PostList = ({ posts, highlight }: Props) => {
return (
<div className={ 'w-full' }>
<ul className={ 'flex flex-col items-center w-full space-y-7' }>
<AnimatePresence mode={ 'wait' }>
{ posts.map((post, key: number) => (
<motion.li
initial={ { y: 20, opacity: 0 } }
animate={ { y: 0, opacity: 1 } }
transition={ { ease: 'easeOut', duration: 0.5, delay: key * .1 + .1 } }
key={ key }
className={ 'w-full' }>
<BlogPostCard post={ post } highlightSelector={ highlight } />
</motion.li>)
) }
</AnimatePresence>
</ul>
</div>
);
};
export default PostList;
+1 -1
View File
@@ -14,7 +14,7 @@ function Layout({
<motion.div <motion.div
initial={ { opacity: 0 } } initial={ { opacity: 0 } }
animate={ { opacity: 1 } } animate={ { opacity: 1 } }
transition={ { ease: 'easeInOut', duration: 0.3, delay: 0.5 } } transition={ { ease: 'easeInOut', duration: 0.3, delay: 0.1 } }
className={ `justify-center flex flex-row w-full max-w-full` }> className={ `justify-center flex flex-row w-full max-w-full` }>
<Navbar /> <Navbar />
<div className={ `flex flex-col flex-1 max-w-[1024px] min-w-0` }> <div className={ `flex flex-col flex-1 max-w-[1024px] min-w-0` }>
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
const screenSize = new Map<string, number>( const screenSize = new Map<string, number>(
[ [
[ 'xs', 480 ],
[ 'sm', 640 ], [ 'sm', 640 ],
[ 'md', 768 ], [ 'md', 768 ],
[ 'lg', 1024 ], [ 'lg', 1024 ],
+5 -3
View File
@@ -1,4 +1,4 @@
@import "lxgw-wenkai-webfont/style.css"; @import "lxgw-wenkai-webfont/lxgwwenkai-light.css";
@tailwind base; @tailwind base;
@tailwind components; @tailwind components;
@@ -6,8 +6,10 @@
body { body {
font-family: "LXGW WenKai", sans-serif; font-family: "LXGW WenKai", sans-serif;
/*font-family: "Arial", "monospace", sans-serif;*/
} }
pre, code { pre, code {
font-family: "LXGW WenKai Mono", sans-serif; /*font-family: "monospace", sans-serif;*/
} font-family: "monospace", sans-serif;
}
-3
View File
@@ -21,9 +21,6 @@ export default function RootLayout({
<html lang="en" suppressHydrationWarning> <html lang="en" suppressHydrationWarning>
<body className={ `transition duration-300 dark:bg-[#282830] min-h-screen` }> <body className={ `transition duration-300 dark:bg-[#282830] min-h-screen` }>
<NextThemesProvider attribute="class" defaultTheme="system"> <NextThemesProvider attribute="class" defaultTheme="system">
<div className={ 'fixed top-0 w-full h-15 bg-yellow-600 z-50' }>
<p className={ 'font-bold text-2xl text-center' }>*System Under Construction*</p>
</div>
{ children } { children }
</NextThemesProvider> </NextThemesProvider>
</body> </body>
+61 -39
View File
@@ -5,57 +5,79 @@ import { useScreenSizeTrigger } from '@/app/(pages)/public/screenSizeTrigger';
import { Button } from '@nextui-org/react'; import { Button } from '@nextui-org/react';
import { entries } from '@/app/entries'; import { entries } from '@/app/entries';
import Link from 'next/link'; import Link from 'next/link';
import * as motion from 'motion/react-client';
import { cn } from '@/src/utils';
export default function Home() { export default function Home() {
const isMobile = useScreenSizeTrigger('sm'); const isSm = useScreenSizeTrigger('sm');
const isXs = useScreenSizeTrigger('xs');
return ( return (
<div> <div className={ 'h-dvh w-full overflow-hidden relative' }>
<div className={ `min-h-dvh h-min content-center` }> <motion.div
<p className={ 'text-center text-4xl' }>Atelier Lumiaethor</p> initial={ { opacity: 0 } }
</div> animate={ { opacity: 1 } }
transition={ { ease: 'easeInOut', duration: 0.3, delay: 0.0 } }
<div
// className={ 'absolute bottom-0 w-full h-60 bg-yellow-500 p-12' }
className={ 'absolute bottom-0 w-full h-60 p-12' }
> >
<div <div className={ `min-h-dvh h-min content-center z-20 p-10` }>
className={ 'bg-blue-500 h-full w-full rounded-3xl backdrop-blur align-middle grid grid-cols-2 content-center' }> <p className={ 'text-center text-4xl' }>Atelier Lumiaethor</p>
<p className={ 'text-center text-gray-700 font-bold dark:text-gray-400' }>In pursuit of absolute
simplicity and ultimate
sophistication</p>
</div>
<div className={ 'w-full flex justify-between' }> <div
<div className={ 'p-16' }> className={ 'absolute left-1/2 -translate-x-1/2 bottom-0 w-full h-60 p-12 max-w-[1536px] justify-center' }
test >
<div
className={ 'h-full w-full rounded-3xl backdrop-blur align-middle grid grid-cols-1 sm:grid-cols-2 content-center' }>
{ !isSm &&
<div className={ 'w-full grid content-center' }>
<div
className={ 'p-2 h-fit brightness-50 lg:brightness-75 lg:p-8 xl:p-16 transition-all' }>
<p>
© 2024-{ new Date().getFullYear() } <Link href={ `/about` }>Lumither Tao</Link>
</p>
<p>Powered by Next.js and Rust, built with passion and love</p>
<p>LMTCloud ecosystem</p>
</div>
</div>
}
<div className={ 'h-full content-center p-4' }>
<ul className={ `grid grid-cols-3 sm:grid-cols-2 justify-items-center sm:justify-items-start w-full` }>
{
entries.map((meta, key) => (
<li key={ key } className={ cn(isXs && 'w-fit', !isXs && 'w-full') }>
<Button
as={ Link }
variant={ `light` }
color={ `default` }
fullWidth
isIconOnly={ isXs }
className={ cn(
'flex justify-center',
isXs && 'w-fit',
!isXs && 'sm:justify-start'
) }
aria-label={ `navbar: ${ meta.display_name }` }
href={ meta.href }
>
{ meta.icon }
{ !isXs && <p className={ `font-bold` }>{ meta.display_name }</p> }
</Button>
</li>
))
}
</ul>
</div> </div>
<div className={ 'w-0.5 h-full bg-neutral-400' }></div>
</div>
<div className={ 'h-full content-center p-4 pr-3' }>
<ul className={ `grid grid-cols-2 w-full` }>
{
entries.map((meta, key) => (
<li key={ key }>
<Button
as={ Link }
variant={ `light` }
color={ `default` }
fullWidth
isIconOnly={ isMobile }
className={ 'flex lg:justify-start w-fit lg:w-full' }
aria-label={ `navbar: ${ meta.display_name }` }
href={ meta.href }
>
{ meta.icon }
<p className={ `font-bold hidden sm:block` }>{ meta.display_name }</p>
</Button>
</li>
))
}
</ul>
</div> </div>
</div> </div>
</div> </motion.div>
</div> </div>
); );
} }
@@ -4,7 +4,7 @@ const ConstructionPlaceHolder = () => {
return ( return (
<div className={ `flex h-full w-full justify-center items-center` }> <div className={ `flex h-full w-full justify-center items-center` }>
<p className={ `text-2xl font-bold` }> <p className={ `text-2xl font-bold` }>
正在施工中... * Under Construction *
</p> </p>
</div> </div>
); );
+2
View File
@@ -1,3 +1,5 @@
'use client';
import React from 'react'; import React from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { IoLogoGithub } from 'react-icons/io5'; import { IoLogoGithub } from 'react-icons/io5';
+1 -1
View File
@@ -8,7 +8,7 @@ const nextConfig = {
}, },
{ {
protocol: 'https', protocol: 'https',
hostname: 'pic.re' hostname: 'cdn.jsdelivr.net'
} }
] ]
}, },
+5 -2
View File
@@ -11,8 +11,9 @@
"dependencies": { "dependencies": {
"@nextui-org/react": "^2.4.6", "@nextui-org/react": "^2.4.6",
"@types/react-syntax-highlighter": "^15.5.13", "@types/react-syntax-highlighter": "^15.5.13",
"clsx": "^2.1.1",
"lxgw-wenkai-webfont": "^1.7.0", "lxgw-wenkai-webfont": "^1.7.0",
"motion": "^12.3.1", "motion": "^12.23.12",
"next": "^15.3.2", "next": "^15.3.2",
"next-themes": "^0.3.0", "next-themes": "^0.3.0",
"react": "^18.3.1", "react": "^18.3.1",
@@ -26,7 +27,9 @@
"remark-frontmatter": "^5.0.0", "remark-frontmatter": "^5.0.0",
"remark-gfm": "^4.0.0", "remark-gfm": "^4.0.0",
"remark-toc": "^9.0.0", "remark-toc": "^9.0.0",
"sharp": "^0.33.4" "sharp": "^0.33.4",
"tailwind-merge": "^3.3.1",
"ts-pattern": "^5.8.0"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/typography": "^0.5.14", "@tailwindcss/typography": "^0.5.14",
+33 -14
View File
@@ -1,20 +1,22 @@
import { fetchNocturneJson } from '@/src/api/endpoint'; import { fetchNocturneJson } from '@/src/api/endpoint';
const DEFAULT_PAGE_SIZE = 6; const DEFAULT_PAGE_SIZE = 8;
export interface Post {
id: string,
identifier: string,
title: string,
subtitle: string,
tags: string[]
category: string,
date_created: Date,
date_updated: Date | null,
header_img: string | null
}
export interface PostListResponse { export interface PostListResponse {
data: { data: {
posts: { posts: Post[],
id: string,
identifier: string,
title: string,
subtitle: string,
tags: string[]
category: string,
date_created: Date,
date_updated: Date | null,
header_img: string | null
}[],
pagination: { pagination: {
page: number, page: number,
page_count: number, page_count: number,
@@ -24,9 +26,26 @@ export interface PostListResponse {
status: string status: string
} }
interface FetchPostListParams {
page: number;
page_size?: number;
tag_filter?: string[];
match_all?: boolean;
}
export async function fetchPostList(page: number, page_size: number = DEFAULT_PAGE_SIZE): Promise<PostListResponse> { export async function fetchPostList({
const url = `/blog/posts?page=${ page }&page_size=${ page_size }`; page,
page_size = DEFAULT_PAGE_SIZE,
tag_filter = [],
match_all = false
}: FetchPostListParams
): Promise<PostListResponse> {
const pagination_string = `page=${ page }&page_size=${ page_size }`;
const tag_filter_string = tag_filter.length != 0
? `&tags=${ tag_filter.join(',') }&match_all=${ match_all }`
: '';
const url = `/blog/posts?${ pagination_string }${ tag_filter_string }`;
return await fetchNocturneJson(url); return await fetchNocturneJson(url);
} }
+1 -1
View File
@@ -1,4 +1,4 @@
export const SITE_CONFIG = { export const SITE_CONFIG = {
name: 'Atelier Lumiaethor', name: 'Atelier Lumiaethor',
desc: '' desc: 'In pursuit of absolute simplicity and ultimate sophistication'
}; };
+6
View File
@@ -0,0 +1,6 @@
import { ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "gateway" name = "gateway"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2024"
[dependencies] [dependencies]
+1 -3
View File
@@ -1,3 +1 @@
fn main() { fn main() {}
println!("Hello, world!");
}
File renamed without changes.
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
set -e
PGPASSFILE="/root/.pgpass"
echo "postgres:5432:${POSTGRES_DB}:${POSTGRES_USER}:${POSTGRES_PASSWORD}" > "$PGPASSFILE"
chmod 600 "$PGPASSFILE"
echo "waiting for postgres"
until pg_isready -h postgres -U "$POSTGRES_USER" -d "$POSTGRES_DB"; do
echo "retrying, sleep 2s"
sleep 2
done
echo "db ready, running migrations"
for file in /migrations/*.sql; do
echo "applying $file"
psql -h postgres -U "$POSTGRES_USER" -d "$POSTGRES_DB" -f "$file"
done
echo "migration complete"
+26 -4
View File
@@ -7,14 +7,14 @@ services:
dockerfile: ../container/release/frontend.containerfile dockerfile: ../container/release/frontend.containerfile
restart: always restart: always
ports: ports:
- "3000:3000" - "0.0.0.0:3000:3000"
env_file: env_file:
- ./.env - ./.env
backend: backend:
depends_on: depends_on:
- postgres - migrate
build: build:
context: ./backend context: ./backend
dockerfile: ../container/release/backend.containerfile dockerfile: ../container/release/backend.containerfile
@@ -22,17 +22,39 @@ services:
ARCH: ${ARCH} ARCH: ${ARCH}
restart: always restart: always
ports: ports:
- "3001:3001" - "0.0.0.0:3001:3001"
env_file: env_file:
- ./.env - ./.env
- ./.env.local - ./.env.local
dns: dns:
- 1.1.1.1 - 1.1.1.1
migrate:
image: postgres:17
depends_on:
postgres:
condition: service_healthy
env_file:
- ./.env
- ./.env.local
volumes:
- ./migration/ddl:/migrations:ro
- ./migration/migration.sh:/migration.sh:ro
entrypoint: [ "/bin/sh", "/migration.sh" ]
postgres: postgres:
image: postgres:16.3 image: postgres:17
ports: ports:
- "5432:5432" - "5432:5432"
env_file: env_file:
- ./.env - ./.env
- ./.env.local - ./.env.local
healthcheck:
test: [ "CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB" ]
interval: 5s
timeout: 3s
retries: 10
start_period: 5s
restart: always
+54
View File
@@ -0,0 +1,54 @@
services:
frontend:
depends_on:
- backend
image: cr.lmt.moe/nocturne/frontend:${TAG}
restart: always
ports:
- "0.0.0.0:3000:3000"
env_file:
- ./.env
backend:
depends_on:
- migrate
image: cr.lmt.moe/nocturne/backend:${TAG}
restart: always
ports:
- "0.0.0.0:3001:3001"
env_file:
- ./.env
- ./.env.local
dns:
- 1.1.1.1
migrate:
image: postgres:17
depends_on:
postgres:
condition: service_healthy
env_file:
- ./.env
- ./.env.local
volumes:
- ./migration/ddl:/migrations:ro
- ./migration/migration.sh:/migration.sh:ro
entrypoint: [ "/bin/sh", "/migration.sh" ]
postgres:
image: postgres:17
ports:
- "5432:5432"
env_file:
- ./.env
- ./.env.local
healthcheck:
test: [ "CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB" ]
interval: 5s
timeout: 3s
retries: 10
start_period: 5s
restart: always