Skip to content

Commit

Permalink
[Feat] add language support (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
mistricky authored Sep 2, 2024
1 parent 2feced0 commit efd39a8
Show file tree
Hide file tree
Showing 16 changed files with 123 additions and 49 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
**/target
**/dist
database.json
output.css

# Deps
node_modules
Expand Down
43 changes: 41 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/src/dao/post.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
database::models::{prelude::Tags, tags},
utils::{helpers::parse_load_many_result, vector_convert::convert_vecs},
utils::vector_convert::convert_vecs,
};
use sea_orm::{
sea_query::OnConflict, ColumnTrait, DatabaseConnection, DeleteResult, EntityTrait,
Expand Down
1 change: 1 addition & 0 deletions api/src/dao/post_tags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ pub async fn upsert_post_tags<T: ConnectionTrait>(db: &T, tags: &Vec<String>, po
})
.collect::<Vec<ActiveModel>>(),
)
.on_empty_do_nothing()
.on_conflict(
OnConflict::columns([Column::TagId, Column::PostId])
.do_nothing()
Expand Down
45 changes: 20 additions & 25 deletions api/src/database/initialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,33 +50,28 @@ async fn upsert_posts(db: &DatabaseConnection, dir_entries: &Vec<DirEntry>) -> a
let front_matter = get_post_front_matter(&content);
let content = get_post_content(&content);
let tags = front_matter.tags;

match get_post_by_path(db, &stringify_dir_path).await? {
Some(post) => {
if post.updated_at == updated_at {
continue;
}

upsert_tags(db, tags, post.id).await;
}
None => {
let post = upsert_post(
db,
ActiveModel {
path: Set(stringify_dir_path),
content: Set(markdown::parse::parse_markdown(&content)),
title: Set(front_matter.title),
spoiler: Set(Some(front_matter.spoiler)),
created_at: Set(created_at),
updated_at: Set(updated_at),
..Default::default()
},
)
.await?;

upsert_tags(db, tags, post.last_insert_id).await;
let post_active_model = ActiveModel {
path: Set(stringify_dir_path.clone()),
content: Set(markdown::parse::parse_markdown(&content)),
title: Set(front_matter.title),
spoiler: Set(Some(front_matter.spoiler)),
created_at: Set(created_at),
updated_at: Set(updated_at.clone()),
..Default::default()
};

if let Some(post) = get_post_by_path(db, &stringify_dir_path).await? {
if post.updated_at == updated_at {
continue;
}
}

upsert_tags(
db,
tags,
upsert_post(db, post_active_model).await?.last_insert_id,
)
.await;
}

Ok(())
Expand Down
2 changes: 2 additions & 0 deletions app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ reqwest = { version = "0.12.5", features = ["json", "socks"] }
wasm-bindgen = "0.2.92"
wasm-bindgen-macro = "0.2.92"
site_config = { path = "../site_config" }
chrono = "0.4.38"
cached = "0.53.1"

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
api = {path = "../api"}
Expand Down
35 changes: 17 additions & 18 deletions app/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,26 @@ impl HTTP {
}
}

// #[cfg(debug_assertions)]
// #[cfg(not(target_arch = "wasm32"))]
// fn get_port() -> usize {
// site_config::get_site_config().server.dev_port
// }

// #[cfg(not(debug_assertions))]
// fn get_port() -> usize {
// site_config::get_site_config().server.prod_port
// }

// #[cfg(not(target_arch = "wasm32"))]
#[cfg(debug_assertions)]
#[cfg(not(target_arch = "wasm32"))]
fn get_port() -> usize {
site_config::get_site_config().server.dev_port
}

#[cfg(not(debug_assertions))]
fn get_port() -> usize {
site_config::get_site_config().server.prod_port
}

#[cfg(not(target_arch = "wasm32"))]
pub fn get_base_url(prefix: &'static str) -> String {
// format!("http://localhost:{}{prefix}", Self::get_port())
format!("http://localhost:8000{prefix}")
format!("http://localhost:{}{prefix}", Self::get_port())
}

// #[cfg(target_arch = "wasm32")]
// pub fn get_base_url(prefix: &'static str) -> String {
// format!("{}{prefix}", web_sys::window().unwrap().origin())
// }
#[cfg(target_arch = "wasm32")]
pub fn get_base_url(prefix: &'static str) -> String {
format!("{}{prefix}", web_sys::window().unwrap().origin())
}

fn with_base_url(&self, path: &str) -> String {
format!("{}{path}", self.base_url)
Expand Down
1 change: 1 addition & 0 deletions app/src/i18n.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod translate;
3 changes: 3 additions & 0 deletions app/src/i18n/en.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"Hello": "World"
}
25 changes: 25 additions & 0 deletions app/src/i18n/translate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use cached::proc_macro::cached;
use serde_json::Value;

const EN: &'static str = include_str!("en.json");
const ZH: &'static str = include_str!("zh.json");

#[cached]
fn get_parsed_config() -> Value {
let site_config = site_config::get_site_config();
let language = site_config.root.language.as_str();
let language_source = match language {
"zh" => ZH,
"en" => EN,
_ => panic!("Unsupported language"),
};

serde_json::from_str(language_source).expect("Wrong format of language json")
}

pub fn t(key: &str) -> String {
let config = get_parsed_config();
let value = config.get(key).expect("Key not found");

value.as_str().expect("Value is not a string").to_string()
}
3 changes: 3 additions & 0 deletions app/src/i18n/zh.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"Hello": "你好"
}
1 change: 1 addition & 0 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod components;
mod http;
mod i18n;
mod icons;
mod pages;
pub mod portal;
Expand Down
4 changes: 2 additions & 2 deletions app/src/pages/post.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::http::HTTP;
use log::info;
use crate::i18n::translate::t;
use shared::post::PostDetail;
use yew::functional::use_prepared_state;
use yew::prelude::*;
Expand Down Expand Up @@ -31,7 +31,7 @@ fn Content(props: &PostProps) -> HtmlResult {
.unwrap();

Ok(html! {
<div>
<div class="prose">
{parse_str_to_element(&parepared_post_detail.content)}
</div>
})
Expand Down
1 change: 0 additions & 1 deletion app/src/pages/posts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::rc::Rc;

use crate::components::{load_more::LoadMore, post_item::PostItem};
use crate::http::HTTP;
use log::info;
use shared::post::{PaginationPostsRes, Post};
use yew::{platform::spawn_local, prelude::*};

Expand Down
1 change: 1 addition & 0 deletions shared/src/site_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub struct NavConfig {

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Clone)]
pub struct RootConfig {
pub language: String,
pub posts_folder_name: String,
pub dynamic_pages_folder_name: String,
}
Expand Down
4 changes: 4 additions & 0 deletions site.config.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
[root]
posts_folder_name = "posts"

# The default language of the site
# en | zh
language = "en"

# dynamic_pages_folder_name is really useful in most cases,
# you can put markdown files under the root/dynamic_pages_folder_name folder,
# if zzhack found markdown file in root/dynamic_pages_folder_name,
Expand Down

0 comments on commit efd39a8

Please sign in to comment.