diff --git a/.agents/skills/gleam-conventions/SKILL.md b/.agents/skills/gleam-conventions/SKILL.md new file mode 100644 index 0000000..685cd67 --- /dev/null +++ b/.agents/skills/gleam-conventions/SKILL.md @@ -0,0 +1,59 @@ +--- +name: gleam-conventions +description: ALWAYS use this skill BEFORE writing or modifying ANY Gleam code (.gleam files), even for simple Hello World programs. Enforces idiomatic Gleam coding guidelines from the official Gleam conventions (conventions, patterns, and anti-patterns). This skill is MANDATORY for all Gleam development. +license: MIT +metadata: + author: veeso + version: "1.0.0" + tags: + - gleam + - conventions + - linting +--- + +# Gleam Development + +This skill automatically enforces Gleam coding standards and best practices when creating or modifying Gleam code. + +## Instructions + +**CRITICAL**: This skill MUST be invoked for ANY Gleam code operation, including: + +- Creating new .gleam files (even simple examples like Hello World) +- Modifying existing .gleam files (any change, no matter how small) +- Reviewing Gleam code +- Refactoring Gleam code + +**Process**: + +1. Read the [conventions-patterns-anti-patterns.djot](./conventions-patterns-anti-patterns.djot) file to understand all compliance requirements +2. Before writing/modifying ANY Gleam code, ensure edits are conformant to the guidelines +3. Apply the rules according to their tier (see below) +4. Comments must ALWAYS be written in American English, unless the user explicitly requests a different language. + +**No exceptions**: Even for trivial code like "Hello World", guidelines must be followed. + +## How to interpret the djot file + +The file uses [djot](https://djot.net/) markup format. It is structured into three top-level sections, each representing a tier of rules: + +### Conventions (Mandatory) + +Rules under the `## Conventions` heading are **mandatory** and must be adhered to always. These are non-negotiable requirements for all Gleam code. + +### Patterns (Recommended) + +Rules under the `## Patterns` heading are **recommended** approaches. Apply them whenever you think they would benefit the code. They represent idiomatic solutions to common problems. + +### Anti-patterns (Avoid) + +Rules under the `## Anti-patterns` heading describe practices that should be **avoided**. Never introduce these patterns into code. + +### Reading the format + +- Each rule is a `###` subsection within its tier +- Code examples use `` ```gleam `` fenced blocks with `// Good` and `// Bad` comments to show correct vs incorrect usage +- Prose paragraphs explain the rationale and nuances of each rule +- Some rules reference external talks or resources for deeper understanding + +--- diff --git a/.agents/skills/gleam-conventions/conventions-patterns-anti-patterns.djot b/.agents/skills/gleam-conventions/conventions-patterns-anti-patterns.djot new file mode 100644 index 0000000..93165dc --- /dev/null +++ b/.agents/skills/gleam-conventions/conventions-patterns-anti-patterns.djot @@ -0,0 +1,856 @@ +--- +title = "Conventions, patterns, and anti-patterns" +meta_title = "Conventions, patterns, and anti-patterns | Gleam programming language" +subtitle = "Writing good code in Gleam" +description = "Tips and guidance for writing good code in Gleam" +preview_image = "patterns" +--- + +This document outlines conventions, patterns, and anti-patterns for Gleam code. +Conventions and anti-patterns are rules that should be adhered to always, while +patterns are to applied whenever the programmer thinks it would benefit their +code. + +## Conventions + +Gleam enforces `snake_case` for variables, constants, and functions, and +`PascalCase` for types and variants. + +### Avoid unqualified importing of functions and constants + +Always used the qualified syntax for functions and constants defined in other +modules. + +```gleam +// Good +import gleam/list +import gleam/string + +pub fn reverse(input: String) -> String { + input + |> string.to_graphemes + |> list.reverse + |> string.concat +} + +// Bad +import gleam/list.{reverse} +import gleam/string.{to_graphemes, concat} + +pub fn reverse(input: String) -> String { + input + |> to_graphemes + |> reverse + |> concat +} +``` + +Types and record constructors may be used with the unqualified syntax, +providing you think it does not make the code more difficult to read. + +### Annotate all module functions + +All module functions should have annotations for their argument types and for +their return type. + +```gleam +// Good +fn calculate_total(amounts: List(Int), service_charge: Int) -> Int { + int.sum(amounts) * service_charge +} + +// Bad +fn calculate_total(amounts, service_charge) { + int.sum(amounts) * service_charge +} + +// Bad: missing return annotation +fn calculate_total(amounts: List(Int), service_charge: Int) { + int.sum(amounts) * service_charge +} +``` + +### Use result for fallible functions + +All functions that can succeed or fail may return a result in Gleam. + +Some languages use both the result and the option type for fallible functions, +but Gleam does not. Using results always makes code consistent and removes the +boilerplate that would otherwise be required to convert between result and +option. If there is no extra information to return for failure then the result +error type can be `Nil`. + +Panics are not used for fallible functions, especially within libraries. +Panicking may be appropriate at the top level of application code, handling the +result returned by fallible functions. + +```gleam +// Good +pub fn first(list: List(a)) -> Result(a, Nil) { + case list { + [item, ..] -> Ok(item) + _ -> Error(Nil) + } +} + +// Bad: returns an option +pub fn first(list: List(a)) -> option.Option(a) { + case list { + [item, ..] -> option.Some(item) + _ -> option.None + } +} + +// Bad: panics on failure +pub fn first(list: List(a)) -> a { + case list { + [item, ..] -> item + _ -> panic as "cannot get first of empty list" + } +} +``` + +### Use singular for module names + +Module names are singular, not plural. + +```gleam +// Good +import app/user + +// Bad +import app/users +``` + +This applies to all segments, not just the final one. + +```gleam +// Good +import app/payment/invoice + +// Bad +import app/payments/invoice +``` + +### Treat acronyms as single words + +Acronyms are always written as if they were a single word. + +```gleam +// Good +let json: Json = build_json() + +// Bad +let j_s_o_n: JSON = build_j_s_o_n() +``` + +It may be tempting to ignore this convention and use the name `JSON`, but this +will result in the BEAM code generated from the Gleam code using the name +`j_s_o_n`. + +### Conventional conversion function naming + +When naming a function that converts from one type to another, use the convention `x_to_y`. + +```gleam +// Good +pub fn json_to_string(data: Json) -> String + +// Bad +pub fn json_into_string(data: Json) -> String +pub fn json_as_string(data: Json) -> String +pub fn string_of_json(data: Json) -> String +``` + +If the module name matches the type name then do not repeat the name of the +type at the start of the function. + +```gleam +// In src/my_app/identifier.gleam + +// Good +pub fn to_string(id: Identifier) -> String + +// Bad +pub fn identifier_to_string(id: Identifier) -> String +``` + +Functions are used with a module qualifier, so the name of the module clarifies +what the input value is: + +```gleam +import my_app/identifier.{type Identifier} + +pub fn run(id: Identifier) -> String { + identifier.to_string(id) +} +``` + +If there is a name for the encoding, format, or variant used in the conversion +function, then use that in the name of the function. + +```gleam +// Good +pub fn date_to_rfc3339(date: Date) -> String + +// Bad +pub fn date_to_string(date: Date) -> String +``` + +If there is a more descriptive name for the conversion operation then use that +instead. + +```gleam +// Good +pub fn round(data: Float) -> Int + +// Bad +pub fn float_to_int(data: Float) -> Int +``` + +### Conventional fallible function naming + +Functions that return results should be given a name that is appropriate for +the domain and the operation they perform. + +```gleam +// Good +pub fn parse_json(input: String) -> Result(Json, ParseError) +pub fn enqueue(job: BackgroundJob) -> Result(Nil, EnqueueError) +``` + +If the function is a special result-handling version of an existing function +that returns-early when there is an error, then the `try_` prefix can be used, +so long as there is not a more appropriate domain-specific name. Names based on +design patterns or abstract concepts should be avoided. + +```gleam +pub fn map(list: List(a), f: fn(a) -> b) -> List(b) + +// Good +pub fn try_map( + list: List(a), + f: fn(a) -> Result(b, e), +) -> Result(List(b), e) + +// Bad +pub fn monadic_bind( + list: List(a), + f: fn(a) -> Result(b, e), +) -> Result(List(b), e) +``` + +### Use the core libraries + +The Gleam core team maintain several packages that are to be used as a shared +foundation for other Gleam libraries and applications. + +- [`gleam_stdlib`](https://hexdocs.pm/gleam_stdlib) +- [`gleam_time`](https://hexdocs.pm/gleam_time) +- [`gleam_json`](https://hexdocs.pm/gleam_json) +- [`gleam_http`](https://hexdocs.pm/gleam_http) +- [`gleam_erlang`](https://hexdocs.pm/gleam_erlang) +- [`gleam_otp`](https://hexdocs.pm/gleam_otp) +- [`gleam_javascript`](https://hexdocs.pm/gleam_javascript) + +This shared foundation makes it easier for related Gleam packages to work +together, and helps avoid common problems that the design of the packages +guard against. + +Do not replicate functionality provided by these packages. e.g. Do not create a +new time type instead of using `gleam_time`'s `Timestamp`. + +### Keep development tool config in `gleam.toml` + +The `gleam` command line program provides most the functionality that we need +for Gleam development, but there may still be occasions where additional +tooling is desired. For example, a security scanner, or a licence compliance +checker. + +If these tools are to be configured via a file, that file should be +`gleam.toml`, with configuration going under the `tools.$TOOL_NAME` key prefix. + +```toml +name = "thingy" +version = "1.0.0" + +[dependencies] +gleam_stdlib = "<= 1.0.0 and < 2.0.0" + +[tools.lustre.dev] +host = "0.0.0.0" + +[tools.lustre.build] +minify = true +outdir = "../server/priv/static" +``` + +Do not use dedicated configuration files such as `my-tool.toml`, or +`config/my-tool.yaml`. + +Dynamic configuration can be read from environment variables or provided as +command line arguments. + +### Use the correct source code directory + +Gleam's build tool offers 3 directories for source code, `src`, `dev`, `test`. +Each directory has a different purpose. + +`src` is for code to be included in application or library itself. Code in this +directory can import modules from `dependencies` and `src/`, but not +`dev_dependencies`, `dev/`, or `test/`. + +`test` is for code that tests the package, such as automated unit and +integration tests. Code in this directory can import modules from any +dependencies and any directory. + +`dev` is for any additional code used in development, such as code generators +and helper scripts. Code in this directory can import modules from any +dependencies and any directory. + +## Patterns + +### Design descriptive errors + +When creating an error type, design the variants to describe what the error was +in terms of your business domain. Each variant should hold additional +information about the error instance, to aid debugging or with creation of +helpful error messages. + +If the error was caused by a lower-level error, e.g. being unable to load +application data due to failing to read a file, then that lower error can be +one of the fields of the higher error. + +```gleam +// Good +pub type NoteBookError { + NoteAlreadyExists(path: String) + NoteCouldNotBeCreated(path: String, reason: simplifile.FileError) + NoteCouldNotBeRead(path: String, reason: simplifile.FileError) + NoteInvalidFrontmatter(path: String, reason: tom.ParseError) +} + +// Bad: Not enough detail +pub type NotesError { + NoteAlreadyExists + NoteCouldNotBeCreated + NoteCouldNotBeRead + NoteInvalidFrontmatter +} + +// Bad: Designed around dependencies, not business domain +pub type NotesError { + FileError(path: String, reason: simplifile.FileError) + TomlError(path: String, reason: tom.ParseError) +} +``` + +### Comment liberally + +Comments are a very effective way to make code easier to understand. This is +especially valuable for projects with more than one programmer, or projects +that are expected read and edited over longer periods of time. + +Comments can explain both _what_ the code does as well as _why_ the code does +what it does. Often the reader could determine _what_ without the aid of the +comment, but that may not be the case for unfamiliar readers or if the code is +later determined to have a bug, so what it does and what the writer intended it +to do do not match. + +```gleam +pub fn classify_file_content(content: String) -> FileOrigin { + let likely_generated = + // In newer versions of squirrel this is always at the beginning of the + // file and it would be enough to check for this comment to establish if + // a file is generated or not... + string.contains( + content, + "> 🐿️ This module was generated automatically using", + ) + // ...but in older versions that module comment is not present! So we + // need to check if there's any function generated by squirrel. + || string.contains( + content, + "> 🐿️ This function was generated automatically using", + ) + + case likely_generated { + True -> LikelyGenerated + False -> NotGenerated + } +} +``` + +Adding comments does not mean the code itself can be written in an unclear way, +and having well written code doesn't mean that comments are not a valuable +addition. + +### Make invalid states impossible + +Gleam's type system and custom types enable Gleam programmers to precisely +model their domain in their code. Types definitions that sufficiently encode +the business rules can make it impossible to construct invalid data, removing +many types of bugs, and turning the type definitions into documentation for the +business logic. + +For example, say we are making a website, and the visitors to that website can +be logged in users, or they can be guests. All logged in users have an email +address and a database id. This could be represented like so: + +```gleam +pub type Visitor { + Visitor(id: Option(Int), email: Option(String)) +} +``` + +If the visitor is logged in, then both the optional fields would be set. If the +visitor is a guest, then both would be unset. + +```gleam +let logged_in_user = Visitor(id: Some(123), email: Some("hi@example.com")) +let guest = Visitor(id: None, email: None) +``` + +However, this data structure can be constructed with just an email, or just an +id, both states being invalid according to our business rules! + +```gleam +let invalid = Visitor(id: Some(123), email: None) +``` + +A better design would ensure that both the id and the email are present at the +same time, making the invalid states impossible. + +```gleam +pub type Visitor { + LoggedInUser(id: Int, email: String) + Guest +} +``` + +Richard Feldman has an excellent talk on this pattern which can be viewed +[on youtube](https://www.youtube.com/watch?v=IcgmSRJHu_8). + +### Replace bools with custom types + +The bool type can be useful for representing data with 2 possible states, +however, there are some drawbacks to this: + +- `Bool`, `True`, and `False` have no meaning without context, making it easier + to misunderstand what values represent. +- The bool type will be used for many unrelated pieces of data, so it is + possible to mistake one bool value for another without a type error to + prevent the mistake. +- If a third state is required in future then bool can no longer be used, and a + larger refactoring will be needed. It may be tempting to use a second bool, + but that results in 4 states, and a third bool results in 8 states. + Combinations of bools can be especially unclear. + +```gleam +pub type SchoolPerson { + SchoolPerson(name: String, is_student: Bool) +} +``` + +Consider defining and using descriptive custom types instead, as they avoid +these issues. + +```gleam +pub type SchoolPerson { + SchoolPerson(name: String, role: Role) +} + +pub type Role { + Student + Teacher +} +``` + +### The sans-io pattern + +The sans-io pattern is a way of designing API clients, SDKs, and similar +packages so that they do not depend on any particular HTTP client. Instead it +gives responsibility to the library user for sending HTTP requests, etc. +With this pattern the user has full control over HTTP sending, so they can use +it on any target, inside any structure or framework, they can add rate limiting +or retries, or anything else they might need. + +To implement the pattern structure your code so that each API action has a pair +of functions: One that constructs a HTTP request, and another that takes a HTTP +response and returns the resulting data. + +```gleam +import gleam/http/request.{type Request} +import gleam/http/response.{type Response} + +/// Construct a request for the create-user endpoint. +pub fn create_user_request(name: String) -> Request(String) { + request.new() + |> request.set_method(Post) + |> request.set_host("example.com") + |> request.set_body(json.to_string(json.object([#("name", name)]))) + |> request.prepend_header("accept", "application/json") + |> request.prepend_header("content-type", "application/json") +} + +/// Parse a response from the create-user endpoint. +pub fn create_user_response(response: Response(String)) -> Result(User, ApiError) { + case response.status { + 201 -> Ok(User(name: response.body)) + 409 -> Error(UserNameAlreadyInUse) + 429 -> Error(RateLimitWasHit) + code -> Error(GotUnexpectedResponse(code, response.body)) + } +} +``` + +This is not the same as taking a HTTP-sending function as an argument. That +design means that only HTTP clients that conform to that type can be used, +which is very limiting. Most notably, it would mean that the library cannot be +used on both the Erlang and the JavaScript targets, as one will be using a +promise type, while the other will not. + +### The builder pattern + +The builder pattern is a flexible way to create records with multiple optional +fields, often used for configuration. + +```gleam +// Usage +button.new(text: "Continue") +|> button.colour("green") +|> button.large +|> button.to_html +``` + +Any required fields can be taken as arguments by the function that starts the +builder pipeline, the remaining fields being set to default values. + +```gleam +pub type Button { + Button(text: String, colour: String, classes: Set(String)) +} + +pub fn new(text text: String) -> Button { + Button(text:, colour: "pink", classes: set.new()) +} +``` + +In this example the `Button` type is not opaque, so the record can be +constructed and manipulated directly. Other times you may wish to make it +opaque and force the builder functions to be used, which could be for +validation or data integrity reasons. + +Builder functions take the builder value as an argument and return a new +version of it with one or more fields changed. + +```gleam +pub fn colour(button: Button, value: String) -> Button { + Button(..button, colour: value) +} +``` + +Builder functions do not need to only set a field to a value taken as an +argument, they can perform any logic to construct the data. Often it is helpful +to have convenience functions for common uses, and possibly have the users of +the code construct the builder record directly if they need full control. + +```gleam +pub fn large(button: Button) -> Button { + let classes = button.classes |> set.delete("small") |> set.insert("large") + Button(..button, classes:) +} +``` + +## Anti-patterns + +### Abbreviations + +Using shortened names can save a few keystrokes when typing, but they greatly +hinder code reading and understanding. Abbreviations are ambiguous, so the +reader has to guess what they are short for, and often they will get it wrong. +This is especially likely if you are working with people with different +backgrounds or from different cultures. + +Always write names in full. + +```gleam +// Bad +let cap = 5 +let off = 0 +let cnt = proc_dat(ss) + +// Good +let capacity = 5 +let offset = 0 +let continuation = process_data(session) +``` + +### Fragmented modules + +Do not prematurely split up modules into multiple smaller modules, and do not +view large modules as a problem. Instead focus on the business domain and +making the best API for the users of the code. + +An API that is split over many modules is harder to understand and requires +more boilerplate to use than one well designed module, and it becomes more +challenging to hide internal implementation details when they have to be +exposed for other modules to use. + +Multiple modules also encourages the creation of a much larger number of +functions and types, with overlapping functionality between modules. The larger +the API the more difficult it is to understand and to work with. The best APIs +are small and focused. + +If you are having trouble with import cycles, or if multiple modules need to be +imported to perform a simple task with your code, then it may be a sign that +you have split up code that should be a single module. + +Evan Czaplicki's talk ["The life of a file"](https://www.youtube.com/watch?v=XpDsk374LDE) +has a wealth of information on this topic. + +```gleam +// Bad +import my_library/client +import my_library/config +import my_library/decode +import my_library/error +import my_library/parser +import my_library/types + +// Good +import my_library +``` + +This anti-pattern is especially common with AI-generated code. If you are using +AI in your coding pay extra attention to this rule. + +### Panicking in libraries + +Libraries must not panic, so they should not use `panic` or `let assert`. + +Panicking instead of returning a result takes control away from the users of +the library, preventing them from being able to handle errors. A library does +not know the context in which it is used, so it is impossible for the author of +a library to know if it acceptable to panic, so they never can. + +The one exception to this rule is for libraries _about_ OTP, the BEAM +application framework. OTP has non-local handling through supervision trees, so +there may be some circumstances in which it is appropriate to panic, providing +they have a suitably designed supervision tree. The library author would +benefit from having a strong understanding of OTP system to identify when this +is a good option. + +### Global namespace pollution + +Gleam has a global module namespace, a property inherited from the BEAM +ecosystem. If two packages each define a module with the same name then a +project adding both packages as dependencies will fail to compile. + +To avoid this problem packages should define their own namespace by placing +their modules within a uniquely named directory. This name should match the +name of the package. For example, the package `lustre` places its modules in +`src/lustre/`. + +```sh +# Good +src/ +├── my_package.gleam +└── my_package/ + ├── distribution.gleam + └── inventory.gleam + +# Bad +src/ +├── distribution.gleam +├── inventory.gleam +└── my_package.gleam +``` + +### Namespace trespassing + +Other packages should not place their modules within a top-level directory that +belongs to a different package. Trespassing in someone else's module +namespace can result in compilation errors due to module collisions, and +confusing code where it is unclear where modules come from. + +For example, I must not place my modules within `src/lustre/`, even if I am +making a package intended to be used with the `lustre` package. + +The maintainers of the `lustre` package may choose to reuse the `src/lustre/` +directory in other Lustre-related packages that they also own. + +### Grouping by design pattern + +When splitting your code into modules always design the boundaries in your +system around your business domain and what would be the best API for the users +of the code. This means never using design patterns or abstract code constructs +as the basis for boundaries within the project. + +```gleam +// Bad: kind grouping +import app/constants +import app/functions +import app/types +import app/utilities + +// Bad: category theory grouping +import app/functors +import app/monads +import app/monoids +import app/semigroups + +// Bad: design pattern grouping +import app/controllers/user_controller +import app/decorator/user_decorator +import app/model/user_mode +import app/services/user_service +import app/views/user_view + +// Good: business domain grouping +import app/stock +import app/billing +``` + +### Check-then-assert + +Check-then-assert is a pattern common in procedural languages where one +performs a check that a value is in some desired state, and then performs +some action afterwards with the knowledge that it is in the desired state. This +is an anti-pattern in functional languages like Gleam, and it should never be +done. + +Instead use pattern matching or functions such as `result.try` and `result.map` +to handle data that could be in some other state. These patterns take advantage +of the type system to ensure that there are no mistakes coming from a +disconnect between the checking and the using, and they can have performance +benefits too. + +```gleam +// Bad: check then assert +case result.is_ok(data) { + True -> { + let assert Ok(value) = data + process(value) + } + False -> data +} + +// Bad: check then assert with `use` +use <- bool.guard(when: result.is_error(data), return: data) +let assert Ok(value) = data +process(data) + +// Good: pattern matching +case data { + Ok(value) -> process(value) + Error(e) -> Error(e) +} + +// Good: combinators +data |> result.try(process) + +// Good: combinators with `use` +use value <- result.try(value) +process(value) +``` + +### Using dynamic with FFI + +When using code written in other languages there will be some arguments and +return values that cannot be represented with the Gleam type system. For +example, an Erlang function could take an int or a float as its argument. + +Never use the `gleam/dynamic` module's `Dynamic` type to represent these types. + +The dynamic type represents _any_ type of data, meaning it is valid to pass any +value at all to that function, which is not correct and will cause runtime +errors. Instead create a new type that represents exactly the expected type. + +```gleam +// Good +pub type Buffer + +pub fn byte_size(data: Buffer) -> Int + +// Bad +import gleam/dynamic.{type Dynamic} + +pub fn byte_size(data: Dynamic) -> Int +``` + +### Match all variants + +Gleam's exhaustiveness checking of case expressions ensures that when you +change your data model all your code is updated appropriately before it +compiled again. + +If the final pattern of a case expression is one that matches any value, then +this refactoring assistance is effectively disabled for new additions, and the +compiler will not be able to help you update your code. This makes it easy to +introduce bugs due to old logic no longer being correct, so avoid catch-all +patterns where possible. + +```gleam +// Bad: assumes all other variants are teachers +case role { + Student -> handle_student() + _ -> handle_teacher() +} + +// Good: cannot silently become incorrect +case role { + Student -> handle_student() + Teacher -> handle_teacher() +} +``` + +### Category theory overuse + +Avoid creation of complex category theory based abstractions. + +Gleam does not have the ergonomics to make these abstractions easy to work +with, nor the compiler and runtime optimisations required to erase the +significant runtime overhead they introduce. Complex abstractions typically +introduce a high cognitive overhead to the code, running contrary to Gleam's +simple, concrete, and approachable programming style. + +Solve specific problems with specific solutions. + +```gleam +// Bad: abstract style +pub fn sum( + data: a, + monoid: Monoid(a), + catamorphism: Catamorphism(a, b), +) -> b { + catamorphism.apply(data, monoid.empty, monoid.append) +} + +// Good: concrete style +pub fn total_cost(costs: List(Int)) -> Int { + int.sum(costs) +} +``` + +``` =html + +``` diff --git a/.claude/skills/gleam-conventions b/.claude/skills/gleam-conventions new file mode 120000 index 0000000..acb6e76 --- /dev/null +++ b/.claude/skills/gleam-conventions @@ -0,0 +1 @@ +../../.agents/skills/gleam-conventions \ No newline at end of file diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..f8deaa4 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,50 @@ +name: deploy + +on: + push: + branches: + - main + pull_request: + +permissions: + contents: read + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + + - uses: erlef/setup-beam@fc68ffb90438ef2936bbb3251622353b3dcb2f93 # v1.24.0 + with: + otp-version: "28" + gleam-version: "1.18.1" + rebar3-version: "3" + + - run: gleam deps download + - run: gleam run + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: "24" + + - run: npm install -g vercel # zizmor: ignore[adhoc-packages] legacy deployment retained while Vercel packaging is deferred + + - name: Deploy production + if: github.ref == 'refs/heads/main' && github.event_name == 'push' + run: vercel deploy ./dist --prod --token=${{ secrets.VERCEL_TOKEN }} + env: + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} + + - name: Deploy preview + if: github.event_name == 'pull_request' + run: | + url=$(vercel deploy ./dist --token=${{ secrets.VERCEL_TOKEN }}) + echo "Preview URL: $url" + echo "PREVIEW_URL=$url" >> "$GITHUB_ENV" + env: + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..6b02eee --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,30 @@ +name: test + +on: + push: + branches: + - master + - main + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + - uses: erlef/setup-beam@fc68ffb90438ef2936bbb3251622353b3dcb2f93 # v1.24.0 + with: + otp-version: "28" + gleam-version: "1.18.1" + rebar3-version: "3" + # elixir-version: "1" + - run: gleam deps download + - run: gleam test + - run: gleam format --check src test + - run: gleam run + - run: python3 -m unittest discover -s scripts -p 'test_*.py' diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..709fcdf --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +*.beam +*.ez +/build +erl_crash.dump + +dist/ +.vercel/ +.vercel +.env*.local + +.DS_Store +.env* diff --git a/AGENTS.md b/AGENTS.md new file mode 120000 index 0000000..681311e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1 @@ +CLAUDE.md \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..e9ff828 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,94 @@ +# 项目协作指南 + +这是 chunyan.dev 的简体中文 Rust 博客,使用 Gleam、Lustre 和 Blogatto +生成纯静态网站,部署到 Vercel。它是独立的中文版本,不是 +[blog.veeso.dev](https://blog.veeso.dev/) 的自动镜像;后者只作为写作风格参考。 + +## 常用命令 + +```sh +gleam deps download +gleam run +gleam test +gleam format +gleam format --check src test +just dev +python3 -m unittest discover -s scripts -p 'test_*.py' +``` + +`gleam run` 将网站构建到 `./dist`,`just dev` 在 3000 端口启动带实时重载的 +开发服务器。发布前需要同时运行 Gleam 测试、格式检查、构建和 Python 输出测试。 + +## 代码结构 + +- `src/blog.gleam` 是构建入口,负责安装 Tailwind、运行 Blogatto 并编译 CSS。 +- `src/blog/config.gleam` 配置 Markdown 目录、静态资源、页面、RSS、Atom、站点地图和 robots.txt。 +- `src/blog/site.gleam` 保存站点名称、作者显示名、规范域名、语言和订阅源信息。 +- `src/blog/pages/` 包含首页、文章列表、隐私政策和中文 404 页面。 +- `src/blog/template/` 包含页面外壳、顶栏、页脚和文章模板。 +- `src/blog/components/` 包含布局、文章卡片、日期、图标和 Markdown 渲染组件。 +- `blog/` 保存文章;静态资源在 `static/`,Tailwind 输入在 `assets/blog.css`。 + +## 内容、URL 和语言 + +文章使用 `blog//index.md` 和 YAML frontmatter。文章路由为 +`/blog//`,slug 使用稳定的 ASCII 字符串。站点只生成一个简体中文版本, +不要新增语言目录或翻译后缀。当前公开 URL 包括: + +- `/`:首页。 +- `/blog/`:全部文章。 +- `/blog/hello-world/`:欢迎文章。 +- `/privacy/`:隐私政策。 +- `/rss.xml` 和 `/atom.xml`:订阅源。 +- `/sitemap.xml` 和 `/robots.txt`:搜索发现文件。 + +所有规范 URL 都以 `https://blog.chunyan.dev` 为根,不要使用预览域名作为规范地址。 +历史路径只在部署重定向规则中保留,不能把不存在的旧文章批量重定向到首页。 + +## Rust 编辑范围和写作风格 + +文章面向中国大陆的 Rust 开发者,从入门者到专家。主题应具体围绕所有权、借用、 +生命周期、trait、异步 Rust、性能、Cargo、工具链、Rust 库或实际 Rust 项目经验。 +Gleam 只是网站的实现技术,不是博客文章的编辑主题。 + +写作使用自然的简体中文,直接说明问题,再介绍抽象概念。可以使用“我”和“你”, +保留实验、失败和限制,避免企业宣传、夸张权威、强行网络用语和把 Rust 翻译成 +“铁锈”。必要时可首次写成“所有权(ownership)”“借用检查器(borrow checker)” +或“异步 Rust(async Rust)”,crate 名称、命令和代码保持原样。 + +页面标题、description、图片 alt、导航、订阅源、错误页面和隐私政策都必须使用简体 +中文。中文与 Latin 文本混排时检查标点、换行和长 Rust 标识符。注释和 API 标识符 +可以保留英文,但面向读者的可见文字不能因此保留英文。 + +## 页面和元数据约定 + +- 每个页面只有一个 H1;首页的“最新文章”使用 H2,文章描述使用段落。 +- 首页标题是“春晏的 Rust 博客 | chunyan.dev”,文章标题使用“文章标题 | chunyan.dev”。 +- HTML 语言为 `zh-CN`,Open Graph locale 为 `zh_CN`,文章日期以 UTC+8 展示。 +- 文章日期保留原始时间戳,并同时输出带 ISO 时间的 `time` 元素和 JSON-LD。 +- JSON-LD 必须通过 JSON 序列化器生成,并转义脚本数据中的 `<`。 +- 图标使用内联 SVG;SVG 图形标记为装饰性内容,图标链接必须有中文 aria-label。 +- 文章采用 CC BY-NC-ND 4.0 许可协议,不能添加与它矛盾的“All rights reserved”文字。 + +代码高亮在构建时由 Blogatto 和 smalto 完成。浏览器端不依赖 Prism、Feather、Google +Fonts、jsDelivr 或分析脚本;深色模式可以使用 JavaScript,但页面正文、导航、日期、 +代码和订阅源必须在禁用 JavaScript 时仍然可用。 + +## 依赖和版本 + +项目使用 Blogatto 7.x、Lustre 5.x、Tailwind CSS 4.2.1、Gleam 1.18.1 和 +Erlang/OTP 28。新增直接依赖时要更新 `gleam.toml`,不要依赖传递导入;锁文件由 +Gleam 管理。修改 Gleam、Markdown 或 GitHub Actions 文件时,遵循对应的本地协作 +规范并运行完整检查。 + +## 部署 + +本次迁移不改变现有 Vercel 项目、凭据或部署方式。部署继续由 +`.github/workflows/deploy.yml` 负责;修改部署产物、项目链接、域名或 secrets 前,先 +确认目标是这个中文博客而不是旧项目。不要读取或提交 `.env.local`、token 或其他凭据。 + +## 安全和协作边界 + +不要修改 `../blog.veeso.dev/`,不要提交 `.superpowers/`、`.vercel/` 或本地环境文件。 +不要未经确认打开 GitHub issue;如果创建 Pull Request,默认使用 draft。保留已有的 +真实账户链接、邮箱、法律主体和 VAT 信息,不要用站点显示名机械替换它们。 diff --git a/Justfile b/Justfile new file mode 100644 index 0000000..c789b94 --- /dev/null +++ b/Justfile @@ -0,0 +1,6 @@ +# Lists all the available commands +default: + @just --list + +dev: + gleam run -m blog/dev diff --git a/README.md b/README.md index 9786279..b735459 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,76 @@ -# blog.chunyan.dev +# chunyan.dev -我的个人博客,使用 [Gleam](https://gleam.run/) 和 [Lustre](https://lustre.dev/) 构建,由 [Blogatto](https://github.com/veeso/blogatto) 驱动。 +你好,我是春晏。这是一个专门聊 Rust 的简体中文个人博客,记录实际开发中的 +经验、踩坑和技术思考。 -最初使用 Gatsby 构建,现已迁移为由 Gleam/OTP 生成的纯静态站点。 +网站使用 [Gleam](https://gleam.run/)、[Lustre](https://lustre.dev/) 和 +[Blogatto](https://github.com/veeso/blogatto) 构建,由 Gleam/OTP 生成纯静态站点, +托管在 [Vercel](https://vercel.com/)。 ## 技术栈 -| 技术 | 用途 | -| --------------------------------------------- | -------------------- | -| [Gleam](https://gleam.run/) | 编程语言(编译为 Erlang/OTP) | -| [Lustre](https://lustre.dev/) | UI 组件框架 | -| [Blogatto](https://github.com/veeso/blogatto) | 博客引擎 / 静态站点生成器 | -| [Tailwind CSS](https://tailwindcss.com/) | 样式 | -| [Vercel](https://vercel.com/) | 托管 | +| 技术 | 用途 | +| --------------------------------------------- | ------------------- | +| [Gleam](https://gleam.run/) | 编程语言,编译为 Erlang/OTP | +| [Lustre](https://lustre.dev/) | UI 组件框架 | +| [Blogatto](https://github.com/veeso/blogatto) | 静态站点生成器 | +| [Tailwind CSS](https://tailwindcss.com/) | 样式 | +| [Vercel](https://vercel.com/) | 静态站点托管 | ## 项目结构 -```txt +```text blog.chunyan.dev/ -├── src/blog/ # Gleam 源代码 -│ ├── blog.gleam # 入口与 Blogatto 配置 -│ ├── components/ # 可复用 UI 组件 -│ ├── pages/ # 首页与博客列表页 -│ └── template/ # 页面模板、顶栏、页脚 -├── blog/ # Markdown 文章(含 frontmatter) -├── assets/ # CSS 源文件(Tailwind 输入) -├── static/ # 静态文件(favicon、头像、OG 图片) -└── dist/ # 构建输出(构建后生成) +├── src/blog.gleam # 构建入口 +├── src/blog/config.gleam # Blogatto 配置 +├── src/blog/site.gleam # 共享站点身份 +├── src/blog/components/ # 可复用 UI 和 Markdown 组件 +├── src/blog/pages/ # 首页、文章列表、隐私政策和 404 +├── src/blog/template/ # 页面模板、顶栏和页脚 +├── blog/ # Markdown 文章和 frontmatter +├── assets/ # Tailwind CSS 输入 +├── static/ # favicon、头像和社交预览图 +└── dist/ # 构建输出 ``` ## 开发 ### 前置条件 -- [Gleam](https://gleam.run/) >= 1.14.0 -- [Erlang/OTP](https://www.erlang.org/) >= 28 -- [Docker](https://www.docker.com/)(用于本地预览) -- [just](https://github.com/casey/just)(可选的任务运行器) +- [Gleam](https://gleam.run/) 1.18.1 或更高版本。 +- [Erlang/OTP](https://www.erlang.org/) 28 或更高版本。 +- [just](https://github.com/casey/just)(可选的任务运行器)。 ### 命令 ```sh -gleam run # 将静态站点构建到 ./dist -gleam test # 运行测试 -gleam format # 格式化代码 -just dev # 启动开发服务器,端口 3000,支持热重载 +gleam deps download +gleam format --check src test +gleam test +gleam run +just dev +python3 -m unittest discover -s scripts -p 'test_*.py' ``` -## 部署 +`gleam run` 会把站点生成到 `./dist`。文章使用 +`blog//index.md`,并通过 `/blog//` 访问。网站只生成一个简体 +中文版本,Rust 语法、crate 名称和命令保持原样。 -站点通过 GitHub Actions 部署到 Vercel: +## 部署 -- **推送到 `main`**:生产环境部署 -- **拉取请求(Pull Request)**:预览环境部署 +本次内容迁移不改变现有的 Vercel 项目、凭据或部署方式。GitHub Actions 仍沿用 +`.github/workflows/deploy.yml` 中已有的构建和部署流程。重新设计部署产物或切换项目 +前,应先确认目标项目、域名和 secrets 属于这个中文博客,不要读取或提交 `.env.local`、 +token 或其他凭据。 ## 许可证 -- 代码:[MIT](https://opensource.org/licenses/MIT) -- 内容:[CC-BY-NC-ND-4.0](https://creativecommons.org/licenses/by-nc-nd/4.0/) +- 代码:[MIT](https://opensource.org/licenses/MIT)。 +- 文章和图片:[CC BY-NC-ND 4.0](https://creativecommons.org/licenses/by-nc-nd/4.0/)。 -## 资源 +## 参考资源 -- [A Blog in Gleam](https://gearsco.de/blog/blog-in-gleam/) -- [blogatto](https://github.com/veeso/blogatto):使用 Gleam 编写的博客引擎 -- [glailglind](https://hexdocs.pm/glailglind/):Gleam 的 Tailwind CSS 安装器 -- [webls](https://hexdocs.pm/webls/):网站的 Sitemap、robots 与 RSS 订阅源 +- [A Blog in Gleam](https://gearsco.de/blog/blog-in-gleam/)。 +- [Blogatto](https://github.com/veeso/blogatto):使用 Gleam 编写的博客引擎。 +- [glailglind](https://hexdocs.pm/glailglind/):Gleam 的 Tailwind CSS 安装器。 +- [webls](https://hexdocs.pm/webls/):网站地图、robots 和 RSS 工具。 diff --git a/assets/blog.css b/assets/blog.css new file mode 100644 index 0000000..298c524 --- /dev/null +++ b/assets/blog.css @@ -0,0 +1,73 @@ +@import "tailwindcss"; + +@custom-variant dark (&:where(.dark, .dark *)); +@custom-variant sm (@media (max-width: 640px)); + +@theme { + --breakpoint-sm: initial; + + --color-brand: #31363b; + --color-page: #f5f5f5; + + --font-size-xl: 1.5rem; + --font-size-2xl: 2rem; + --font-size-3xl: 3.5rem; + --font-size-4xl: 7rem; +} + +html { + scroll-behavior: smooth; +} + +body { + font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", + "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif; + line-height: 1.75; + margin: 0; + min-width: 100vw; + overflow-x: hidden !important; + padding: 0; +} + +p { + font-weight: 400; +} + +input, +textarea { + font-family: inherit; +} + +strong { + font-weight: 600; +} + +button { + box-sizing: border-box; + cursor: pointer; +} + +button, +input { + margin: 0; + font-family: inherit; + font-size: inherit; + line-height: inherit; +} + +article { + overflow-wrap: anywhere; +} + +pre, +code { + font-family: ui-monospace, "SFMono-Regular", Consolas, monospace; +} + +pre { + overflow-x: auto; +} + +.md-img { + max-height: 420px; +} diff --git a/blog/post-1/featured.jpeg b/blog/post-1/featured.jpeg new file mode 100644 index 0000000..3e9a281 Binary files /dev/null and b/blog/post-1/featured.jpeg differ diff --git a/blog/post-1/index.md b/blog/post-1/index.md new file mode 100644 index 0000000..e664aa3 --- /dev/null +++ b/blog/post-1/index.md @@ -0,0 +1,24 @@ +--- +date: "2026-09-17 08:00:00 +08:00" +slug: "hello-world" +title: "你好,我是春晏。这里聊 Rust。" +description: "一个专门聊 Rust 的中文博客,记录开发经验、踩过的坑,还有一些忍不住想说的看法。" +author: "春晏" +featured_image: featured.jpeg +category: "rust" +reading_time: '1' +--- + +你好,我是春晏,也就是 Christian Visintin。 + +我住在意大利,写代码,也做开源项目。之前一直在 +[blog.veeso.dev](https://blog.veeso.dev/) 写博客,现在想用中文聊聊 Rust, +于是有了 **chunyan.dev**。 + +这里专门写 Rust:实际项目里遇到的问题、踩过的坑、折腾出来的东西, +还有一些可能没必要、但我还是想说的看法。 + +Rust 很好用,但借用检查器也不会因为我喜欢它就对我客气。遇到问题, +我会把过程和解决办法一起写下来。 + +就这样,欢迎来坐坐。我们从下一篇开始写代码。 diff --git a/gleam.toml b/gleam.toml new file mode 100644 index 0000000..6abc933 --- /dev/null +++ b/gleam.toml @@ -0,0 +1,21 @@ +name = "blog" +version = "1.2.0" +links = [{ title = "Website", href = "https://blog.chunyan.dev" }] +repository = { type = "github", user = "veeso-dev", repo = "blog.chunyan.dev" } +description = "春晏的 Rust 中文博客,分享开发经验、踩坑记录和技术思考。" +licenses = ["MIT", "CC-BY-NC-ND-4.0"] + +[dependencies] +blogatto = ">= 7.0.0 and < 8.0.0" +glailglind = ">= 2.2.0 and < 3.0.0" +gleam_json = ">= 3.1.0 and < 4.0.0" +gleam_stdlib = ">= 0.44.0 and < 2.0.0" +gleam_time = ">= 1.7.0 and < 2.0.0" +lustre = ">= 5.6.0 and < 6.0.0" +marceau = ">= 1.3.0 and < 2.0.0" + +[dev_dependencies] +gleeunit = ">= 1.0.0 and < 2.0.0" + +[tailwind] +version = "4.2.1" diff --git a/manifest.toml b/manifest.toml new file mode 100644 index 0000000..1ffb33a --- /dev/null +++ b/manifest.toml @@ -0,0 +1,63 @@ +# Do not manually edit this file, it is managed by Gleam. +# +# This file locks the dependency versions used, to make your build +# deterministic and to prevent unexpected versions from being included +# in your application. +# +# You should check this file into your source control repository. + +packages = [ + { name = "blogatto", version = "7.0.0", build_tools = ["gleam"], requirements = ["filepath", "filespy", "frontmatter", "gleam_erlang", "gleam_http", "gleam_otp", "gleam_stdlib", "gleam_time", "gtempo", "houdini", "jot", "lustre", "marceau", "maud", "mist", "mork", "simplifile", "smalto", "smalto_lustre", "str", "tzif", "webls", "zones"], otp_app = "blogatto", source = "hex", outer_checksum = "9CB07BA7CD90D3D2027656D7655D274F3B69838308ECFD45F3F93243645A7180" }, + { name = "casefold", version = "2.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "casefold", source = "hex", outer_checksum = "6E1EBB01B945448EE43BE5618F122341F9D876442E65F28FD3948009C31CE3E5" }, + { name = "exception", version = "2.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "exception", source = "hex", outer_checksum = "329D269D5C2A314F7364BD2711372B6F2C58FA6F39981572E5CA68624D291F8C" }, + { name = "filepath", version = "1.1.2", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "filepath", source = "hex", outer_checksum = "B06A9AF0BF10E51401D64B98E4B627F1D2E48C154967DA7AF4D0914780A6D40A" }, + { name = "filespy", version = "0.7.0", build_tools = ["gleam"], requirements = ["fs", "gleam_erlang", "gleam_otp", "gleam_stdlib"], otp_app = "filespy", source = "hex", outer_checksum = "1136C7DB512B83DF544CDA4632A633412281B48489428391DB0356F66423D7C0" }, + { name = "frontmatter", version = "1.0.1", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "frontmatter", source = "hex", outer_checksum = "D7FF83A8D22A52867809681EE254A3F989169F92539299958879FE47737DAB7A" }, + { name = "fs", version = "11.4.1", build_tools = ["rebar3"], requirements = [], otp_app = "fs", source = "hex", outer_checksum = "DD00A61D89EAC01D16D3FC51D5B0EB5F0722EF8E3C1A3A547CD086957F3260A9" }, + { name = "glailglind", version = "2.3.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_http", "gleam_httpc", "gleam_stdlib", "shellout", "simplifile", "tom"], otp_app = "glailglind", source = "hex", outer_checksum = "734B8103529D9406B970C707D077CA6B45FD566295F0E72E209C23740734AC78" }, + { name = "gleam_community_ansi", version = "1.5.0", build_tools = ["gleam"], requirements = ["gleam_community_colour", "gleam_regexp", "gleam_stdlib"], otp_app = "gleam_community_ansi", source = "hex", outer_checksum = "B5AA433AF84313E23FDF90CCFF752B9380FE9FFCE02B2949D49B7AACCC77B16D" }, + { name = "gleam_community_colour", version = "2.0.4", build_tools = ["gleam"], requirements = ["gleam_json", "gleam_stdlib"], otp_app = "gleam_community_colour", source = "hex", outer_checksum = "6DB4665555D7D2B27F0EA32EF47E8BEBC4303821765F9C73D483F38EE24894F0" }, + { name = "gleam_crypto", version = "1.6.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_crypto", source = "hex", outer_checksum = "2DE9E4EF53CF6FEE049D4F765731F7178F7A11AEFAE00EEE63BF7536B354AD3F" }, + { name = "gleam_erlang", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_erlang", source = "hex", outer_checksum = "1124AD3AA21143E5AF0FC5CF3D9529F6DB8CA03E43A55711B60B6B7B3874375C" }, + { name = "gleam_http", version = "4.3.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_http", source = "hex", outer_checksum = "82EA6A717C842456188C190AFB372665EA56CE13D8559BF3B1DD9E40F619EE0C" }, + { name = "gleam_httpc", version = "5.0.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_http", "gleam_stdlib"], otp_app = "gleam_httpc", source = "hex", outer_checksum = "C545172618D07811494E97AAA4A0FB34DA6F6D0061FDC8041C2F8E3BE2B2E48F" }, + { name = "gleam_json", version = "3.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_json", source = "hex", outer_checksum = "44FDAA8847BE8FC48CA7A1C089706BD54BADCC4C45B237A992EDDF9F2CDB2836" }, + { name = "gleam_otp", version = "1.2.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], otp_app = "gleam_otp", source = "hex", outer_checksum = "BA6A294E295E428EC1562DC1C11EA7530DCB981E8359134BEABC8493B7B2258E" }, + { name = "gleam_regexp", version = "1.1.1", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_regexp", source = "hex", outer_checksum = "9C215C6CA84A5B35BB934A9B61A9A306EC743153BE2B0425A0D032E477B062A9" }, + { name = "gleam_stdlib", version = "1.0.3", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "1F543AFBA5D33DA493E6087F4E4C4F20D899411343512686C98A8ABB2963CF22" }, + { name = "gleam_time", version = "1.8.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_time", source = "hex", outer_checksum = "533D8723774D61AD4998324F5DD1DABDCDBFABAFB9E87CB5D03C6955448FC97D" }, + { name = "gleeunit", version = "1.11.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleeunit", source = "hex", outer_checksum = "EC31ABA74256AEA531EDF8169931D775BBB384FED0A8A1BDC4DD9354E3E21826" }, + { name = "glisten", version = "9.0.1", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_otp", "gleam_stdlib", "logging"], otp_app = "glisten", source = "hex", outer_checksum = "7795AA50830656F3A0316A6B26595F893C83272DA901B3405E31339CAA31A10B" }, + { name = "gramps", version = "6.0.1", build_tools = ["gleam"], requirements = ["gleam_crypto", "gleam_erlang", "gleam_http", "gleam_stdlib"], otp_app = "gramps", source = "hex", outer_checksum = "D55636072DEE173F6586A5679D3C02EC7A0DE3F8646B78C351B72908FF223DF7" }, + { name = "gtempo", version = "7.3.0", build_tools = ["gleam"], requirements = ["gleam_regexp", "gleam_stdlib", "gleam_time"], otp_app = "gtempo", source = "hex", outer_checksum = "12203C245560AA732751B5F5F6D73266BAAABE5A10C4C5F993CF91174A6C224F" }, + { name = "houdini", version = "1.2.1", build_tools = ["gleam"], requirements = [], otp_app = "houdini", source = "hex", outer_checksum = "6F8AC2F12974567FB744BEA66AC93CEB76AAEA19AD28564623F76CDA9BC26A85" }, + { name = "hpack_erl", version = "0.3.0", build_tools = ["rebar3"], requirements = [], otp_app = "hpack", source = "hex", outer_checksum = "D6137D7079169D8C485C6962DFE261AF5B9EF60FBC557344511C1E65E3D95FB0" }, + { name = "jot", version = "12.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib", "houdini", "splitter"], otp_app = "jot", source = "hex", outer_checksum = "B9FD4E9971257919F46BCA36D075F94D8FAACDF6E68C06AC3E37A0DA85D31A0D" }, + { name = "logging", version = "1.5.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "logging", source = "hex", outer_checksum = "BC5F18CE5DD9686100229FE5409BDC3DD5C46D5A7DF2F804AD2D8F0DD6C5060E" }, + { name = "lustre", version = "5.7.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_json", "gleam_otp", "gleam_stdlib", "houdini"], otp_app = "lustre", source = "hex", outer_checksum = "38C6FCBD7B7BACE994D5BF643202BB69B02576D44250B4C5DCE738387C0E8F87" }, + { name = "marceau", version = "1.3.0", build_tools = ["gleam"], requirements = [], otp_app = "marceau", source = "hex", outer_checksum = "2D1C27504BEF45005F5DFB18591F8610FB4BFA91744878210BDC464412EC44E9" }, + { name = "maud", version = "2.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib", "lustre", "mork"], otp_app = "maud", source = "hex", outer_checksum = "73CECA8B235B159E2EC24D487DA4CBBEF550D01AD79599AB9810C235496667B8" }, + { name = "mist", version = "6.0.3", build_tools = ["gleam"], requirements = ["exception", "gleam_erlang", "gleam_http", "gleam_otp", "gleam_stdlib", "glisten", "gramps", "hpack_erl", "logging"], otp_app = "mist", source = "hex", outer_checksum = "1B07F321D5FA0CB162D81496F2DE96AEB6EF8980F4F38230A4CC3F849497E020" }, + { name = "mork", version = "1.12.1", build_tools = ["gleam"], requirements = ["casefold", "gleam_regexp", "gleam_stdlib", "splitter"], otp_app = "mork", source = "hex", outer_checksum = "73CEB1DBF2C4E827D420970729EEE8931D324D23612869938F729DEFFEDBB820" }, + { name = "odysseus", version = "1.0.0", build_tools = ["gleam"], requirements = [], otp_app = "odysseus", source = "hex", outer_checksum = "6A97DA1075BDDEA8B60F47B1DFFAD49309FA27E73843F13A0AF32EA7087BA11C" }, + { name = "shellout", version = "1.8.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "shellout", source = "hex", outer_checksum = "C416356D45151F298108C9DB9CD1EDE0313F620B5EDBB5766CD7237659D87841" }, + { name = "simplifile", version = "2.4.0", build_tools = ["gleam"], requirements = ["filepath", "gleam_stdlib"], otp_app = "simplifile", source = "hex", outer_checksum = "7C18AFA4FED0B4CE1FA5B0B4BAC1FA1744427054EA993565F6F3F82E5453170D" }, + { name = "smalto", version = "3.0.0", build_tools = ["gleam"], requirements = ["gleam_community_ansi", "gleam_stdlib", "houdini"], otp_app = "smalto", source = "hex", outer_checksum = "13EA8935A9E60A770E326FB850F5A5B3612A62E0A6C62C3F850AD04C842E3769" }, + { name = "smalto_lustre", version = "3.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib", "lustre", "smalto"], otp_app = "smalto_lustre", source = "hex", outer_checksum = "63C5F2CE886D7CDFEAABAAC5A0E7B3EDBF69F9776A08AACA0360B0948745EF2A" }, + { name = "splitter", version = "1.2.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "splitter", source = "hex", outer_checksum = "3DFD6B6C49E61EDAF6F7B27A42054A17CFF6CA2135FF553D0CB61C234D281DD0" }, + { name = "str", version = "2.1.1", build_tools = ["gleam"], requirements = ["gleam_stdlib", "houdini", "odysseus"], otp_app = "str", source = "hex", outer_checksum = "641BBAE6BB781B9652EA0A47A8D06E536BF823397FD2BE4C5754B67E333C999E" }, + { name = "tom", version = "2.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib", "gleam_time"], otp_app = "tom", source = "hex", outer_checksum = "DCF04CB7AB35D58CFC598C66EA2E1816D160759802C89B2BA6238780D59BC256" }, + { name = "tzif", version = "1.1.2", build_tools = ["gleam"], requirements = ["filepath", "gleam_stdlib", "gleam_time", "simplifile"], otp_app = "tzif", source = "hex", outer_checksum = "04C8EBAFB7F6A6E61B8B0C16E06F96E7C7F76C31172EF07204CE9813B2E54AD2" }, + { name = "webls", version = "1.6.2", build_tools = ["gleam"], requirements = ["gleam_stdlib", "gleam_time", "gtempo"], otp_app = "webls", source = "hex", outer_checksum = "515CA019E3B09FF7605D44ABBCDCF8FF56EC528AA29017741E0184278E3423DD" }, + { name = "zones", version = "1.26020.0", build_tools = ["gleam"], requirements = ["tzif"], otp_app = "zones", source = "hex", outer_checksum = "C7C40CF11ADAF0A64329ACE429DF51F69222820489481F61DD2F3DA98680D680" }, +] + +[requirements] +blogatto = { version = ">= 7.0.0 and < 8.0.0" } +glailglind = { version = ">= 2.2.0 and < 3.0.0" } +gleam_json = { version = ">= 3.1.0 and < 4.0.0" } +gleam_stdlib = { version = ">= 0.44.0 and < 2.0.0" } +gleam_time = { version = ">= 1.7.0 and < 2.0.0" } +gleeunit = { version = ">= 1.0.0 and < 2.0.0" } +lustre = { version = ">= 5.6.0 and < 6.0.0" } +marceau = { version = ">= 1.3.0 and < 2.0.0" } diff --git a/scripts/add_reading_time.py b/scripts/add_reading_time.py new file mode 100644 index 0000000..c2e5ba8 --- /dev/null +++ b/scripts/add_reading_time.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Add reproducible mixed-language reading-time estimates to blog posts. + +The estimate counts CJK characters at 400 per minute and Latin words or code +tokens at 225 per minute. It is an editorial estimate, not a measured reading +speed claim. Markdown markup and link destinations are ignored, while inline +and fenced code content remains part of the estimate. +""" + +import math +import pathlib +import re +import sys + +CJK_CHARACTERS_PER_MINUTE = 400 +LATIN_TOKENS_PER_MINUTE = 225 +BLOG_DIR = pathlib.Path(__file__).resolve().parent.parent / "blog" +FRONTMATTER_RE = re.compile(r"^---\n(.*?\n)---\n", re.DOTALL) +CJK_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]") +MARKDOWN_LINK_RE = re.compile( + r"!?\[([^\]]*)\]\((?:[^()]|\([^)]*\))*\)", +) +HTML_TAG_RE = re.compile(r"<[^>]+>") +FENCED_CODE_RE = re.compile( + r"(?ms)^\s{0,3}(?P`{3,}|~{3,})[^\n]*\n" + r"(?P.*?)(?:^\s{0,3}(?P=fence)[ \t]*$|\Z)", +) +INLINE_CODE_RE = re.compile(r"(?s)`+(?P.+?)`+") +LATIN_TOKEN_RE = re.compile( + r"[A-Za-z]+(?:[0-9][A-Za-z0-9_-]*|[_-][A-Za-z0-9]+)*|[0-9]+", +) + + +def _plain_markdown(body: str) -> str: + """Remove Markdown syntax while retaining prose and code content.""" + + code_fragments = [] + + def protect_code(match: re.Match[str]) -> str: + code_fragments.append(match.group("code")) + return f"\x00CODE{len(code_fragments) - 1}\x00" + + text = FENCED_CODE_RE.sub(protect_code, body) + text = INLINE_CODE_RE.sub(protect_code, text) + text = MARKDOWN_LINK_RE.sub(r"\1", text) + text = HTML_TAG_RE.sub(" ", text) + + for index, code in enumerate(code_fragments): + text = text.replace(f"\x00CODE{index}\x00", code) + return text + + +def calculate_reading_time(body: str) -> int: + """Return a minimum-one-minute mixed CJK and Latin reading estimate.""" + + text = _plain_markdown(body) + cjk_count = len(CJK_RE.findall(text)) + latin_text = CJK_RE.sub(" ", text) + latin_count = len(LATIN_TOKEN_RE.findall(latin_text)) + minutes = ( + cjk_count / CJK_CHARACTERS_PER_MINUTE + + latin_count / LATIN_TOKENS_PER_MINUTE + ) + return max(1, math.ceil(minutes)) + + +def process_file(path: pathlib.Path) -> None: + """Update one Markdown file while preserving its body and other fields.""" + + text = path.read_text(encoding="utf-8") + + match = FRONTMATTER_RE.match(text) + if not match: + print(f" SKIP (no frontmatter): {path}") + return + + frontmatter = match.group(1) + body = text[match.end() :] + minutes = calculate_reading_time(body) + + frontmatter = re.sub(r"^reading_time:.*\n", "", frontmatter, flags=re.MULTILINE) + new_frontmatter = frontmatter.rstrip("\n") + f"\nreading_time: '{minutes}'\n" + new_text = f"---\n{new_frontmatter}---\n{body}" + + path.write_text(new_text, encoding="utf-8") + print(f" {path.name}: {minutes} min") + + +def main() -> None: + """Update Markdown files in this repository's blog directory.""" + + if not BLOG_DIR.is_dir(): + print(f"Blog directory not found: {BLOG_DIR}", file=sys.stderr) + sys.exit(1) + + for post_dir in sorted(BLOG_DIR.iterdir()): + if not post_dir.is_dir(): + continue + print(post_dir.name) + for md_file in sorted(post_dir.glob("*.md")): + process_file(md_file) + + +if __name__ == "__main__": + main() diff --git a/scripts/test_reading_time.py b/scripts/test_reading_time.py new file mode 100644 index 0000000..94442a4 --- /dev/null +++ b/scripts/test_reading_time.py @@ -0,0 +1,78 @@ +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from add_reading_time import calculate_reading_time, process_file + + +class ReadingTimeTests(unittest.TestCase): + def test_empty_text_is_one_minute(self): + self.assertEqual(calculate_reading_time(""), 1) + + def test_chinese_without_spaces(self): + self.assertEqual(calculate_reading_time("中" * 800), 2) + + def test_latin_words(self): + text = " ".join(["Rust"] * 450) + self.assertEqual(calculate_reading_time(text), 2) + + def test_mixed_prose(self): + text = "中" * 400 + " " + " ".join(["Rust"] * 225) + self.assertEqual(calculate_reading_time(text), 2) + + def test_rounding(self): + self.assertEqual(calculate_reading_time("中" * 401), 2) + + def test_markup_and_link_destinations_are_ignored(self): + text = "**Rust** [文档](https://example.com/very-long-destination)" + self.assertEqual(calculate_reading_time(text), 1) + + def test_inline_and_fenced_code_are_counted(self): + inline = "`borrow_checker`" + fenced = "```rust\n" + " ".join(["Rust"] * 225) + "\n```" + self.assertEqual(calculate_reading_time(inline), 1) + self.assertEqual(calculate_reading_time(fenced), 1) + + def test_markup_like_code_content_is_preserved(self): + code = " ".join(["[Rust](https://example.com)"] * 225) + self.assertEqual(calculate_reading_time(f"`{code}`"), 4) + + def test_second_pass_is_idempotent_and_preserves_content(self): + body = "\n一段中文,包含 `borrow_checker` 和一个链接。\n" + source = ( + "---\n" + 'date: "2026-09-17 08:00:00 +08:00"\n' + 'title: "测试文章"\n' + 'description: "测试描述"\n' + 'author: "春晏"\n' + 'category: "rust"\n' + 'reading_time: "99"\n' + 'custom: "保持不变"\n' + "---\n" + + body + ) + + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "index.md" + path.write_text(source, encoding="utf-8") + + process_file(path) + first_pass = path.read_text(encoding="utf-8") + process_file(path) + second_pass = path.read_text(encoding="utf-8") + + self.assertEqual(first_pass, second_pass) + self.assertTrue(second_pass.endswith(body)) + self.assertIn('date: "2026-09-17 08:00:00 +08:00"', second_pass) + self.assertIn('title: "测试文章"', second_pass) + self.assertIn('description: "测试描述"', second_pass) + self.assertIn('author: "春晏"', second_pass) + self.assertIn('category: "rust"', second_pass) + self.assertIn('custom: "保持不变"', second_pass) + self.assertIn("reading_time: '1'", second_pass) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test_site_output.py b/scripts/test_site_output.py new file mode 100644 index 0000000..0b0f240 --- /dev/null +++ b/scripts/test_site_output.py @@ -0,0 +1,244 @@ +import json +import unittest +from html.parser import HTMLParser +from pathlib import Path +import xml.etree.ElementTree as ElementTree + + +REPOSITORY_ROOT = Path(__file__).resolve().parent.parent +DIST = REPOSITORY_ROOT / "dist" +ORIGIN = "https://blog.chunyan.dev" +ATOM_NAMESPACE = "{http://www.w3.org/2005/Atom}" +SITEMAP_NAMESPACE = "{http://www.sitemaps.org/schemas/sitemap/0.9}" + + +class DocumentParser(HTMLParser): + def __init__(self): + super().__init__(convert_charrefs=True) + self.title = "" + self.lang = "" + self.meta = {} + self.links = [] + self.anchors = [] + self.images = [] + self.times = [] + self.headings = [] + self._text_target = None + self._script_data = [] + self.json_ld = [] + + def handle_starttag(self, tag, attrs): + values = dict(attrs) + if tag == "html": + self.lang = values.get("lang", "") + elif tag == "title": + self._text_target = "title" + elif tag == "meta": + key = values.get("name") or values.get("property") + if key: + self.meta[key] = values.get("content", "") + elif tag == "link": + self.links.append(values) + elif tag == "a": + self.anchors.append(values) + elif tag == "img": + self.images.append(values) + elif tag == "time": + self.times.append(values) + elif tag in {"h1", "h2", "h3"}: + self._text_target = tag + elif tag == "script": + self._script_data = [] + if values.get("type") == "application/ld+json": + self._text_target = "json-ld" + + def handle_endtag(self, tag): + if tag == "script" and self._text_target == "json-ld": + self.json_ld.append("".join(self._script_data)) + self._text_target = None + elif tag == "title" and self._text_target == "title": + self._text_target = None + elif tag in {"h1", "h2", "h3"} and self._text_target == tag: + self._text_target = None + + def handle_data(self, data): + if self._text_target == "title": + self.title += data + elif self._text_target in {"h1", "h2", "h3"}: + self.headings.append((self._text_target, data.strip())) + elif self._text_target == "json-ld": + self._script_data.append(data) + + +def parse_page(relative_path: str) -> DocumentParser: + parser = DocumentParser() + parser.feed((DIST / relative_path).read_text(encoding="utf-8")) + return parser + + +class SiteOutputTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + if not DIST.is_dir(): + raise AssertionError("dist is missing; run gleam run before output tests") + cls.pages = { + "index.html": "/", + "blog/index.html": "/blog/", + "blog/hello-world/index.html": "/blog/hello-world/", + "privacy/index.html": "/privacy/", + "404/index.html": "/404/", + } + + def test_html_documents_have_chinese_metadata_and_canonical_urls(self): + expected_types = { + "blog/hello-world/index.html": "article", + } + for relative_path, route in self.pages.items(): + with self.subTest(relative_path=relative_path): + document = parse_page(relative_path) + self.assertEqual(document.lang, "zh-CN") + self.assertTrue(document.title) + self.assertTrue(document.meta.get("description")) + self.assertRegex(document.title, r"[\u3400-\u9fff]") + self.assertRegex(document.meta["description"], r"[\u3400-\u9fff]") + self.assertEqual( + document.meta["og:type"], + expected_types.get(relative_path, "website"), + ) + self.assertRegex(document.meta["og:image:alt"], r"[\u3400-\u9fff]") + canonical = [ + link["href"] + for link in document.links + if link.get("rel") == "canonical" + ] + self.assertEqual(canonical, [ORIGIN + route]) + feed_links = { + (link.get("type"), link.get("href")) + for link in document.links + if link.get("rel") == "alternate" + } + self.assertEqual( + feed_links, + { + ("application/rss+xml", "/rss.xml"), + ("application/atom+xml", "/atom.xml"), + }, + ) + self.assertEqual(len([heading for heading in document.headings if heading[0] == "h1"]), 1) + + def test_homepage_and_article_structured_data(self): + website = json.loads(parse_page("index.html").json_ld[0]) + self.assertEqual(website["@type"], "WebSite") + self.assertEqual(website["inLanguage"], "zh-CN") + self.assertEqual(website["author"]["name"], "春晏") + + article = json.loads(parse_page("blog/hello-world/index.html").json_ld[0]) + self.assertEqual(article["@type"], "BlogPosting") + self.assertEqual(article["inLanguage"], "zh-CN") + self.assertEqual(article["author"]["name"], "春晏") + self.assertRegex(article["datePublished"], r"^2026-09-17T\d{2}:\d{2}:\d{2}Z$") + self.assertNotIn("", parse_page("blog/hello-world/index.html").json_ld[0]) + + def test_feeds_are_chinese_and_use_canonical_links(self): + rss = ElementTree.parse(DIST / "rss.xml").getroot() + channel = rss.find("channel") + self.assertIsNotNone(channel) + self.assertEqual(channel.findtext("language"), "zh-CN") + self.assertEqual(channel.findtext("title"), "chunyan.dev · 春晏的 Rust 博客") + item = channel.find("item") + self.assertIsNotNone(item) + self.assertEqual(item.findtext("link"), ORIGIN + "/blog/hello-world/") + self.assertEqual(item.findtext("guid"), ORIGIN + "/blog/hello-world/") + self.assertEqual(item.findtext("author"), "christian.visintin@veeso.dev") + rss_text = (DIST / "rss.xml").read_text(encoding="utf-8") + self.assertNotIn("/rss/en.xml", rss_text) + self.assertNotIn("/atom/en.xml", rss_text) + + atom = ElementTree.parse(DIST / "atom.xml").getroot() + self.assertEqual(atom.tag, ATOM_NAMESPACE + "feed") + self.assertEqual(atom.findtext(ATOM_NAMESPACE + "title"), "chunyan.dev · 春晏的 Rust 博客") + self_link = atom.find(ATOM_NAMESPACE + "link") + self.assertEqual(self_link.attrib["href"], ORIGIN + "/atom.xml") + self.assertEqual(self_link.attrib["rel"], "self") + self.assertEqual(self_link.attrib["type"], "application/atom+xml") + self.assertEqual(self_link.attrib["hreflang"], "zh-CN") + entry = atom.find(ATOM_NAMESPACE + "entry") + self.assertEqual(entry.findtext(ATOM_NAMESPACE + "author/" + ATOM_NAMESPACE + "name"), "春晏") + self.assertEqual( + entry.findtext(ATOM_NAMESPACE + "author/" + ATOM_NAMESPACE + "email"), + "christian.visintin@veeso.dev", + ) + self.assertEqual( + entry.find(ATOM_NAMESPACE + "link").attrib["href"], + ORIGIN + "/blog/hello-world/", + ) + + def test_sitemap_robots_and_404(self): + sitemap = ElementTree.parse(DIST / "sitemap.xml").getroot() + locations = { + node.text + for node in sitemap.findall(SITEMAP_NAMESPACE + "url/" + SITEMAP_NAMESPACE + "loc") + } + self.assertIn(ORIGIN + "/", locations) + self.assertEqual( + locations, + { + ORIGIN + "/", + ORIGIN + "/blog/", + ORIGIN + "/privacy/", + ORIGIN + "/blog/hello-world/", + }, + ) + self.assertNotIn("/en/", "\n".join(locations)) + + robots = (DIST / "robots.txt").read_text(encoding="utf-8") + self.assertIn("User-agent: *", robots) + self.assertIn(f"Sitemap: {ORIGIN}/sitemap.xml", robots) + + not_found = parse_page("404/index.html") + self.assertEqual(not_found.meta["robots"], "noindex, nofollow") + self.assertEqual(not_found.headings, [("h1", "页面不存在")]) + + def test_all_local_links_and_assets_exist(self): + for relative_path in self.pages: + with self.subTest(relative_path=relative_path): + document = parse_page(relative_path) + urls = [ + link.get("href", "") for link in document.links + ] + [ + anchor.get("href", "") for anchor in document.anchors + ] + [ + image.get("src", "") for image in document.images + ] + for url in urls: + if not url.startswith("/"): + continue + local_path = url.split("?", 1)[0].split("#", 1)[0] + target = DIST / local_path.lstrip("/") + if local_path.endswith("/"): + target /= "index.html" + self.assertTrue(target.is_file(), f"missing local asset: {url}") + + def test_no_external_runtime_assets_or_legacy_text(self): + generated = "\n".join( + (DIST / relative_path).read_text(encoding="utf-8") + for relative_path in self.pages + ) + for forbidden in ( + "fonts.googleapis.com", + "fonts.gstatic.com", + "cdn.jsdelivr.net", + "umami", + "data-feather", + "feather.replace", + "/en/", + "rss/en.xml", + "atom/en.xml", + ): + self.assertNotIn(forbidden, generated) + + self.assertNotRegex(generated, r"]+src=") + + +if __name__ == "__main__": + unittest.main() diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 0000000..2cf45d9 --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,11 @@ +{ + "version": 1, + "skills": { + "gleam-conventions": { + "source": "veeso/agents-code-conventions", + "sourceType": "github", + "skillPath": "gleam-conventions/gleam-conventions/SKILL.md", + "computedHash": "0e86230f0bfab37f935542a752c590c7f343249ee91bc6c9195bf45335078d50" + } + } +} diff --git a/src/blog.gleam b/src/blog.gleam new file mode 100644 index 0000000..78e9e95 --- /dev/null +++ b/src/blog.gleam @@ -0,0 +1,30 @@ +//// Main entry point: configures blogatto and builds the static site. + +import blog/config +import blogatto +import blogatto/error as blogatto_error +import gleam/io +import tailwind + +/// Build the blog: install Tailwind, configure blogatto, and generate output. +pub fn main() { + case tailwind.install() { + Ok(_) -> io.println("Tailwindcss installed successfully!") + Error(e) -> panic as { "Failed to install Tailwind: " <> e } + } + + let cfg = config.config() + + case blogatto.build(cfg) { + Ok(_) -> io.println("Blog built successfully!") + Error(e) -> + panic as { "Failed to build blog: " <> blogatto_error.describe_error(e) } + } + + case tailwind.run(["--input=assets/blog.css", "--output=dist/blog.css"]) { + Ok(out) -> io.println("Tailwindcss built successfully: " <> out) + Error(e) -> panic as { "Failed to run Tailwind: " <> e } + } + + io.println("Blog built successfully!") +} diff --git a/src/blog/components.gleam b/src/blog/components.gleam new file mode 100644 index 0000000..d4966af --- /dev/null +++ b/src/blog/components.gleam @@ -0,0 +1,11 @@ +//// Shared utility functions for building HTML attributes. + +import gleam/list +import lustre/attribute + +/// A utility which converts a list of strings into a `class` attribute. +pub fn classes(classes: List(String)) -> attribute.Attribute(msg) { + classes + |> list.map(fn(class) { #(class, True) }) + |> attribute.classes +} diff --git a/src/blog/components/container.gleam b/src/blog/components/container.gleam new file mode 100644 index 0000000..6c7ee1f --- /dev/null +++ b/src/blog/components/container.gleam @@ -0,0 +1,48 @@ +//// Flexbox layout container components (row, column, responsive row). + +import blog/components +import gleam/list +import lustre/element.{type Element} +import lustre/element/html + +/// A flex row +pub fn row( + classes: List(String), + children: List(Element(msg)), +) -> Element(msg) { + let classes = list.append(["flex", "flex-row"], classes) + html.div( + [ + components.classes(classes), + ], + children, + ) +} + +/// A flex column +pub fn col( + classes: List(String), + children: List(Element(msg)), +) -> Element(msg) { + let classes = list.append(["flex", "flex-col"], classes) + html.div( + [ + components.classes(classes), + ], + children, + ) +} + +/// A flex row that becomes a column on smaller screens +pub fn responsive_row( + classes: List(String), + children: List(Element(msg)), +) -> Element(msg) { + let classes = list.append(["flex", "flex-row", "sm:flex-col"], classes) + html.div( + [ + components.classes(classes), + ], + children, + ) +} diff --git a/src/blog/components/heading.gleam b/src/blog/components/heading.gleam new file mode 100644 index 0000000..29974ec --- /dev/null +++ b/src/blog/components/heading.gleam @@ -0,0 +1,129 @@ +//// Styled heading components (h1 through h5) with consistent typography. + +import blog/components +import gleam/dict.{type Dict} +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/html + +/// Render an h1 heading with optional anchor id. +pub fn h1( + _attributes: Dict(String, String), + id: String, + children: List(Element(msg)), +) -> Element(msg) { + html.h1( + [ + h_id(id), + components.classes([ + "py-4", + "text-2xl", + "text-brand", + "dark:text-white", + "tracking-wide", + "font-normal", + "mt-0", + "mb-2", + ]), + ], + children, + ) +} + +/// Render an h2 heading with optional anchor id. +pub fn h2( + _attributes: Dict(String, String), + id: String, + children: List(Element(msg)), +) -> Element(msg) { + html.h2( + [ + h_id(id), + components.classes([ + "py-3", + "text-xl", + "text-brand", + "dark:text-white", + "tracking-wide", + "font-normal", + "mt-0", + "mb-2", + ]), + ], + children, + ) +} + +/// Render an h3 heading with optional anchor id. +pub fn h3( + _attributes: Dict(String, String), + id: String, + children: List(Element(msg)), +) -> Element(msg) { + html.h3( + [ + h_id(id), + components.classes([ + "py-2", + "text-lg", + "text-brand", + "dark:text-white", + "font-normal", + "mt-0", + "mb-2", + ]), + ], + children, + ) +} + +/// Render an h4 heading with optional anchor id. +pub fn h4( + _attributes: Dict(String, String), + id: String, + children: List(Element(msg)), +) -> Element(msg) { + html.h4( + [ + h_id(id), + components.classes([ + "text-base", + "text-brand", + "dark:text-white", + "font-normal", + "mt-0", + "mb-2", + ]), + ], + children, + ) +} + +/// Render an h5 heading with optional anchor id. +pub fn h5( + _attributes: Dict(String, String), + id: String, + children: List(Element(msg)), +) -> Element(msg) { + html.h5( + [ + h_id(id), + components.classes([ + "text-base", + "text-brand", + "dark:text-white", + "font-normal", + "mt-0", + "mb-2", + ]), + ], + children, + ) +} + +fn h_id(id: String) -> attribute.Attribute(msg) { + case id { + "" -> attribute.none() + id -> attribute.id(id) + } +} diff --git a/src/blog/components/md_components.gleam b/src/blog/components/md_components.gleam new file mode 100644 index 0000000..ee157b0 --- /dev/null +++ b/src/blog/components/md_components.gleam @@ -0,0 +1,361 @@ +//// Custom markdown rendering components for blogatto's markdown pipeline. + +import blog/components +import blog/components/container +import blog/components/heading +import blog/components/svg +import blogatto/config/post.{type Alignment, Center, Left, Right} +import gleam/dict.{type Dict} +import gleam/int +import gleam/option.{type Option} +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/html + +/// Markdown components for markdown rendering. +pub fn components() -> post.Components(msg) { + post.Components( + ..post.default_components(), + a: a, + blockquote: blockquote, + code: code, + h1: heading.h1, + h2: heading.h2, + h3: heading.h3, + h4: heading.h4, + h5: heading.h5, + hr: hr, + img: img, + li: li, + ol: ol, + p: p, + pre: pre, + table: table, + tbody: tbody, + td: td, + th: th, + thead: thead, + tr: tr, + ul: ul, + ) +} + +fn a( + _attributes: Dict(String, String), + href: String, + title: Option(String), + children: List(Element(msg)), +) -> Element(msg) { + html.a( + [ + attribute.href(href), + title_attr(title), + attribute.target("_blank"), + components.classes([ + "font-medium", "text-brand", "dark:text-gray-200", "underline", + "hover:no-underline", + ]), + ], + children, + ) +} + +fn blockquote( + _attributes: Dict(String, String), + children: List(Element(msg)), +) -> Element(msg) { + html.blockquote( + [ + components.classes([ + "border-l-4", + "border-brand", + "dark:border-gray-400", + "bg-gray-50", + "dark:bg-zinc-800", + "italic", + "pl-4", + "py-2", + "pr-4", + "my-4", + "text-gray-700", + "dark:text-gray-200", + ]), + ], + children, + ) +} + +fn code( + _attributes: Dict(String, String), + _language: Option(String), + children: List(Element(msg)), +) -> Element(msg) { + html.code( + [ + components.classes([ + "bg-[#fafafa]", + "dark:bg-[#1e1e1e]", + "text-[#383a42]", + "dark:text-[#d4d4d4]", + "px-1.5", + "py-0.5", + "rounded", + "text-sm", + "font-mono", + ]), + ], + children, + ) +} + +fn img( + _attributes: Dict(String, String), + src: String, + alt: String, + title: Option(String), +) -> Element(msg) { + html.div( + [ + components.classes([ + "flex", + "justify-center", + "items-center", + "py-4", + "md-img-container", + ]), + ], + [ + html.img([ + attribute.src(src), + attribute.alt(alt), + title_attr(title), + components.classes(["md-img"]), + ]), + ], + ) +} + +fn li(children: List(Element(msg))) -> Element(msg) { + html.li( + [ + components.classes([ + "text-lg", + "py-2", + "text-gray-700", + "dark:text-gray-100", + ]), + ], + children, + ) +} + +fn hr() -> Element(msg) { + html.hr([ + components.classes(["my-8", "border-gray-300", "dark:border-gray-600"]), + ]) +} + +fn ol(start: Option(Int), children: List(Element(msg))) -> Element(msg) { + let start = + start + |> option.map(int.to_string) + |> option.map(attribute.attribute("start", _)) + |> option.unwrap(or: attribute.none()) + + html.ol( + [ + start, + components.classes(["px-8", "list-decimal", "sm:px-0"]), + ], + children, + ) +} + +fn p( + _attributes: Dict(String, String), + children: List(Element(msg)), +) -> Element(msg) { + html.p( + [ + components.classes([ + "w-full", + "mb-4", + "text-justify", + "text-lg", + "text-gray-700", + "dark:text-gray-100", + ]), + ], + children, + ) +} + +fn pre( + _attributes: Dict(String, String), + children: List(Element(msg)), +) -> Element(msg) { + container.row( + [ + "w-full", + "relative", + "bg-[#fafafa]", + "dark:bg-[#1e1e1e]", + "rounded", + "text-[#383a42]", + "dark:text-[#d4d4d4]", + ], + [ + html.div([components.classes(["overflow-auto", "flex-1"])], [ + html.pre( + [ + components.classes([ + "overflow-auto", + "w-fit", + "mb-4", + "p-5", + "font-mono", + "text-sm", + ]), + ], + children, + ), + ]), + pre_copy_button(), + ], + ) +} + +fn pre_copy_button() -> Element(msg) { + html.div([components.classes(["absolute", "top-2", "right-2"])], [ + html.button( + [ + components.classes([ + "bg-inherit", + "rounded", + "p-1", + "hover:bg-gray-200", + "active:bg-gray-300", + ]), + attribute.attribute( + "onclick", + "navigator.clipboard.writeText(this.closest('.flex').querySelector('pre').textContent)", + ), + ], + [ + svg.feather_icon("copy"), + ], + ), + ]) +} + +fn table(children: List(Element(msg))) -> Element(msg) { + html.div([components.classes(["w-full", "overflow-x-auto", "my-6"])], [ + html.table( + [ + components.classes([ + "w-full", + "border-collapse", + "text-left", + "text-gray-700", + "dark:text-gray-200", + "border", + "border-gray-300", + "dark:border-gray-600", + ]), + ], + children, + ), + ]) +} + +fn thead(children: List(Element(msg))) -> Element(msg) { + html.thead( + [ + components.classes([ + "bg-gray-100", + "dark:bg-zinc-800", + "border-b", + "border-gray-300", + "dark:border-gray-600", + ]), + ], + children, + ) +} + +fn tbody(children: List(Element(msg))) -> Element(msg) { + html.tbody([], children) +} + +fn tr(children: List(Element(msg))) -> Element(msg) { + html.tr( + [ + components.classes([ + "border-b", + "border-gray-200", + "dark:border-gray-700", + "even:bg-gray-50", + "dark:even:bg-zinc-900", + ]), + ], + children, + ) +} + +fn th(alignment: Alignment, children: List(Element(msg))) -> Element(msg) { + html.th( + [ + components.classes([ + "px-4", + "py-2", + "font-semibold", + "text-gray-900", + "dark:text-gray-100", + "border", + "border-gray-300", + "dark:border-gray-600", + alignment_class(alignment), + ]), + ], + children, + ) +} + +fn td(alignment: Alignment, children: List(Element(msg))) -> Element(msg) { + html.td( + [ + components.classes([ + "px-4", + "py-2", + "border", + "border-gray-300", + "dark:border-gray-600", + alignment_class(alignment), + ]), + ], + children, + ) +} + +fn alignment_class(alignment: Alignment) -> String { + case alignment { + Left -> "text-left" + Center -> "text-center" + Right -> "text-right" + } +} + +fn ul(children: List(Element(msg))) -> Element(msg) { + html.ul( + [ + components.classes(["px-8", "list-disc", "sm:px-0"]), + ], + children, + ) +} + +fn title_attr(title: Option(String)) -> attribute.Attribute(msg) { + title + |> option.map(attribute.title) + |> option.unwrap(or: attribute.none()) +} diff --git a/src/blog/components/post_meta.gleam b/src/blog/components/post_meta.gleam new file mode 100644 index 0000000..10c44ff --- /dev/null +++ b/src/blog/components/post_meta.gleam @@ -0,0 +1,48 @@ +//// Shared post metadata components used by post previews and blog templates. + +import blogatto/post +import gleam/dict +import gleam/int +import gleam/result +import gleam/time/calendar +import gleam/time/duration +import gleam/time/timestamp +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/html + +/// Render a post's date in UTC+8 with a machine-readable timestamp. +pub fn formatted_date(date: timestamp.Timestamp) -> Element(msg) { + let #(calendar_date, _time) = timestamp.to_calendar(date, duration.hours(8)) + let formatted_date = + int.to_string(calendar_date.year) + <> "年" + <> int.to_string(calendar.month_to_int(calendar_date.month)) + <> "月" + <> int.to_string(calendar_date.day) + <> "日" + let machine_date = timestamp.to_rfc3339(date, duration.seconds(0)) + + html.time([attribute.attribute("datetime", machine_date)], [ + element.text(formatted_date), + ]) +} + +/// Render a post's estimated reading time in Chinese. +pub fn reading_time(post: post.Post(msg)) -> Element(msg) { + let minutes = + post.extras + |> dict.get("reading_time") + |> result.try(int.parse) + |> result.map(clamp_minutes) + |> result.unwrap(or: 1) + + element.text("约 " <> int.to_string(minutes) <> " 分钟阅读") +} + +fn clamp_minutes(minutes: Int) -> Int { + case minutes > 0 { + True -> minutes + False -> 1 + } +} diff --git a/src/blog/components/post_preview.gleam b/src/blog/components/post_preview.gleam new file mode 100644 index 0000000..74daa1e --- /dev/null +++ b/src/blog/components/post_preview.gleam @@ -0,0 +1,121 @@ +//// Post preview card component for blog listing pages. + +import blog/components +import blog/components/heading +import blog/components/post_meta +import blogatto/post +import gleam/dict +import gleam/option +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/html + +/// Render a post preview card. +pub fn post_preview(post: post.Post(msg)) -> Element(msg) { + html.div( + [components.classes(["p-2", "border-b", "border-gray-200", "h-full"])], + [ + image_preview(post), + heading.h2(dict.new(), "", [ + html.a( + [ + attribute.href(post_uri(post)), + components.classes([ + "text-brand", + "dark:text-gray-200", + "hover:underline", + ]), + ], + [element.text(post.title)], + ), + ]), + html.p( + [ + components.classes([ + "w-full", + "mb-3", + "text-justify", + "text-lg", + "text-gray-500", + "dark:text-gray-200", + ]), + ], + [element.text(post.description)], + ), + html.p( + [ + components.classes([ + "w-full", + "mb-3", + "text-justify", + "text-lg", + "text-gray-500", + "dark:text-gray-200", + ]), + ], + [ + element.text(post.excerpt), + ], + ), + html.p( + [ + components.classes([ + "w-full", + "mb-3", + "text-justify", + "text-gray-400", + "dark:text-gray-400", + ]), + ], + [ + element.text("发布于 "), + post_meta.formatted_date(post.date), + element.text(" · "), + post_meta.reading_time(post), + ], + ), + ], + ) +} + +fn image_preview(post: post.Post(msg)) -> Element(msg) { + case post.featured_image { + option.None -> element.none() + option.Some(featured_image) -> { + let featured_image = case featured_image { + "http" <> _ -> featured_image + path -> "/blog/" <> post.slug <> "/" <> path + } + + html.div( + [ + components.classes([ + "py-2", + "transition-discrete", + "hover:scale-105", + "cursor-pointer", + ]), + ], + [ + html.a( + [ + attribute.href(post_uri(post)), + ], + [ + html.img([ + attribute.src(featured_image), + attribute.alt("文章配图:" <> post.description), + attribute.loading("eager"), + ]), + ], + ), + ], + ) + } + } +} + +/// relative url to post +fn post_uri(post: post.Post(msg)) -> String { + "/blog/" <> post.slug <> "/" +} diff --git a/src/blog/components/svg.gleam b/src/blog/components/svg.gleam new file mode 100644 index 0000000..d8e63eb --- /dev/null +++ b/src/blog/components/svg.gleam @@ -0,0 +1,282 @@ +//// SVG icon components for social media and feather icons. + +import blog/components +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/svg + +/// Mastodon social media icon. +pub fn mastodon(size: Int) -> Element(msg) { + svg.svg( + [ + attribute.attribute("viewBox", "0 0 74 79"), + attribute.width(size), + attribute.height(size), + attribute.class("inline"), + attribute.attribute("fill", "currentColor"), + attribute.attribute("aria-hidden", "true"), + theme_classes(), + ], + [ + svg.path([ + attribute.attribute( + "d", + "M73.7014 17.4323C72.5616 9.05152 65.1774 2.4469 56.424 1.1671C54.9472 0.950843 49.3518 0.163818 36.3901 0.163818H36.2933C23.3281 0.163818 20.5465 0.950843 19.0697 1.1671C10.56 2.41145 2.78877 8.34604 0.903306 16.826C-0.00357854 21.0022 -0.100361 25.6322 0.068112 29.8793C0.308275 35.9699 0.354874 42.0498 0.91406 48.1156C1.30064 52.1448 1.97502 56.1419 2.93215 60.0769C4.72441 67.3445 11.9795 73.3925 19.0876 75.86C26.6979 78.4332 34.8821 78.8603 42.724 77.0937C43.5866 76.8952 44.4398 76.6647 45.2833 76.4024C47.1867 75.8033 49.4199 75.1332 51.0616 73.9562C51.0841 73.9397 51.1026 73.9184 51.1156 73.8938C51.1286 73.8693 51.1359 73.8421 51.1368 73.8144V67.9366C51.1364 67.9107 51.1302 67.8852 51.1186 67.862C51.1069 67.8388 51.0902 67.8184 51.0695 67.8025C51.0489 67.7865 51.0249 67.7753 50.9994 67.7696C50.9738 67.764 50.9473 67.7641 50.9218 67.7699C45.8976 68.9569 40.7491 69.5519 35.5836 69.5425C26.694 69.5425 24.3031 65.3699 23.6184 63.6327C23.0681 62.1314 22.7186 60.5654 22.5789 58.9744C22.5775 58.9477 22.5825 58.921 22.5934 58.8965C22.6043 58.8721 22.621 58.8505 22.6419 58.8336C22.6629 58.8167 22.6876 58.8049 22.714 58.7992C22.7404 58.7934 22.7678 58.794 22.794 58.8007C27.7345 59.9796 32.799 60.5746 37.8813 60.5733C39.1036 60.5733 40.3223 60.5733 41.5447 60.5414C46.6562 60.3996 52.0437 60.1408 57.0728 59.1694C57.1983 59.1446 57.3237 59.1233 57.4313 59.0914C65.3638 57.5847 72.9128 52.8555 73.6799 40.8799C73.7086 40.4084 73.7803 35.9415 73.7803 35.4523C73.7839 33.7896 74.3216 23.6576 73.7014 17.4323ZM61.4925 47.3144H53.1514V27.107C53.1514 22.8528 51.3591 20.6832 47.7136 20.6832C43.7061 20.6832 41.6988 23.2499 41.6988 28.3194V39.3803H33.4078V28.3194C33.4078 23.2499 31.3969 20.6832 27.3894 20.6832C23.7654 20.6832 21.9552 22.8528 21.9516 27.107V47.3144H13.6176V26.4937C13.6176 22.2395 14.7157 18.8598 16.9118 16.3545C19.1772 13.8552 22.1488 12.5719 25.8373 12.5719C30.1064 12.5719 33.3325 14.1955 35.4832 17.4394L37.5587 20.8853L39.6377 17.4394C41.7884 14.1955 45.0145 12.5719 49.2765 12.5719C52.9614 12.5719 55.9329 13.8552 58.2055 16.3545C60.4017 18.8574 61.4997 22.2371 61.4997 26.4937L61.4925 47.3144Z", + ), + ]), + ], + ) +} + +/// X (formerly Twitter) social media icon. +pub fn x(size: Int) -> Element(msg) { + svg.svg( + [ + attribute.attribute("viewBox", "0 0 24 24"), + attribute.width(size), + attribute.height(size), + attribute.attribute("fill", "none"), + attribute.attribute("stroke", "currentColor"), + attribute.attribute("stroke-width", "2"), + attribute.attribute("stroke-linecap", "round"), + attribute.attribute("stroke-linejoin", "round"), + attribute.class("inline"), + attribute.attribute("aria-hidden", "true"), + theme_classes(), + ], + [ + svg.polygon([ + attribute.attribute("points", "21.3,21.1 9.9,2.9 2.7,2.9 14.1,21.1"), + ]), + svg.line([ + attribute.attribute("x1", "2.7"), + attribute.attribute("y1", "21.1"), + attribute.attribute("x2", "9.9"), + attribute.attribute("y2", "14.5"), + ]), + svg.line([ + attribute.attribute("x1", "14.1"), + attribute.attribute("y1", "9.5"), + attribute.attribute("x2", "21.3"), + attribute.attribute("y2", "2.9"), + ]), + ], + ) +} + +/// Telegram social media icon. +pub fn telegram(size: Int) -> Element(msg) { + svg.svg( + [ + attribute.attribute("viewBox", "0 0 32 32"), + attribute.width(size), + attribute.height(size), + attribute.attribute("fill", "currentColor"), + attribute.class("inline"), + attribute.attribute("aria-hidden", "true"), + theme_classes(), + ], + [ + svg.path([ + attribute.attribute( + "d", + "M22.122 10.04h.022c.209 0 .403.065.562.177l-.003-.002a.632.632 0 0 1 .213.403v.003a2.553 2.553 0 0 1 .024.598v-.009c-.225 2.369-1.201 8.114-1.697 10.766-.21 1.123-.623 1.499-1.023 1.535-.869.081-1.529-.574-2.371-1.126-1.318-.865-2.063-1.403-3.342-2.246-1.479-.973-.52-1.51.322-2.384.221-.23 4.052-3.715 4.127-4.031a.308.308 0 0 0-.07-.265.34.34 0 0 0-.185-.053.364.364 0 0 0-.128.024l.002-.001q-.198.045-6.316 4.174a2.805 2.805 0 0 1-1.619.599h-.006a10.542 10.542 0 0 1-2.401-.573l.074.024c-.938-.306-1.683-.467-1.619-.985q.051-.404 1.114-.827 6.548-2.853 8.733-3.761a22.627 22.627 0 0 1 5.429-2.01l.157-.031zM15.93 1.025C7.628 1.045.905 7.78.905 16.085c0 8.317 6.742 15.06 15.06 15.06s15.06-6.742 15.06-15.06c0-8.305-6.723-15.04-15.023-15.06H15.93z", + ), + ]), + ], + ) +} + +/// WhatsApp social media icon. +pub fn whatsapp(size: Int) -> Element(msg) { + svg.svg( + [ + attribute.attribute("viewBox", "0 0 30.667 30.667"), + attribute.width(size), + attribute.height(size), + attribute.attribute("fill", "currentColor"), + attribute.class("inline"), + attribute.attribute("aria-hidden", "true"), + theme_classes(), + ], + [ + svg.path([ + attribute.attribute( + "d", + "M30.667 14.939c0 8.25-6.74 14.938-15.056 14.938a15.1 15.1 0 01-7.276-1.857L0 30.667l2.717-8.017a14.787 14.787 0 01-2.159-7.712C.559 6.688 7.297 0 15.613 0c8.315.002 15.054 6.689 15.054 14.939zM15.61 2.382c-6.979 0-12.656 5.634-12.656 12.56 0 2.748.896 5.292 2.411 7.362l-1.58 4.663 4.862-1.545c2 1.312 4.393 2.076 6.963 2.076 6.979 0 12.658-5.633 12.658-12.559C28.27 8.016 22.59 2.382 15.61 2.382zm7.604 15.998c-.094-.151-.34-.243-.708-.427-.367-.184-2.184-1.069-2.521-1.189-.34-.123-.586-.185-.832.182-.243.367-.951 1.191-1.168 1.437-.215.245-.43.276-.799.095-.369-.186-1.559-.57-2.969-1.817-1.097-.972-1.838-2.169-2.052-2.536-.217-.366-.022-.564.161-.746.165-.165.369-.428.554-.643.185-.213.246-.364.369-.609.121-.245.06-.458-.031-.643-.092-.184-.829-1.984-1.138-2.717-.307-.732-.614-.611-.83-.611-.215 0-.461-.03-.707-.03s-.646.089-.983.456-1.291 1.252-1.291 3.054c0 1.804 1.321 3.543 1.506 3.787.186.243 2.554 4.062 6.305 5.528 3.753 1.465 3.753.976 4.429.914.678-.062 2.184-.885 2.49-1.739.308-.858.308-1.593.215-1.746z", + ), + ]), + ], + ) +} + +/// Render an inline icon for the named Feather icon used by the site. +pub fn feather_icon(name: String) -> Element(msg) { + svg.svg(feather_attributes(), [feather_shape(name)]) +} + +fn feather_attributes() -> List(attribute.Attribute(msg)) { + [ + attribute.attribute("viewBox", "0 0 24 24"), + attribute.width(20), + attribute.height(20), + attribute.attribute("fill", "none"), + attribute.attribute("stroke", "currentColor"), + attribute.attribute("stroke-width", "2"), + attribute.attribute("stroke-linecap", "round"), + attribute.attribute("stroke-linejoin", "round"), + attribute.class("inline"), + attribute.attribute("aria-hidden", "true"), + theme_classes(), + ] +} + +fn feather_shape(name: String) -> Element(msg) { + case name { + "sun" -> + svg.g([], [ + svg.circle([ + attribute.attribute("cx", "12"), + attribute.attribute("cy", "12"), + attribute.attribute("r", "5"), + ]), + svg.line([ + attribute.attribute("x1", "12"), + attribute.attribute("y1", "1"), + attribute.attribute("x2", "12"), + attribute.attribute("y2", "3"), + ]), + svg.line([ + attribute.attribute("x1", "12"), + attribute.attribute("y1", "21"), + attribute.attribute("x2", "12"), + attribute.attribute("y2", "23"), + ]), + svg.line([ + attribute.attribute("x1", "4.22"), + attribute.attribute("y1", "4.22"), + attribute.attribute("x2", "5.64"), + attribute.attribute("y2", "5.64"), + ]), + svg.line([ + attribute.attribute("x1", "18.36"), + attribute.attribute("y1", "18.36"), + attribute.attribute("x2", "19.78"), + attribute.attribute("y2", "19.78"), + ]), + svg.line([ + attribute.attribute("x1", "1"), + attribute.attribute("y1", "12"), + attribute.attribute("x2", "3"), + attribute.attribute("y2", "12"), + ]), + svg.line([ + attribute.attribute("x1", "21"), + attribute.attribute("y1", "12"), + attribute.attribute("x2", "23"), + attribute.attribute("y2", "12"), + ]), + svg.line([ + attribute.attribute("x1", "4.22"), + attribute.attribute("y1", "19.78"), + attribute.attribute("x2", "5.64"), + attribute.attribute("y2", "18.36"), + ]), + svg.line([ + attribute.attribute("x1", "18.36"), + attribute.attribute("y1", "5.64"), + attribute.attribute("x2", "19.78"), + attribute.attribute("y2", "4.22"), + ]), + ]) + "moon" -> + svg.path([ + attribute.attribute( + "d", + "M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z", + ), + ]) + "github" -> + svg.path([ + attribute.attribute( + "d", + "M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22", + ), + ]) + "linkedin" -> + svg.g([], [ + svg.rect([ + attribute.attribute("x", "2"), + attribute.attribute("y", "2"), + attribute.attribute("width", "20"), + attribute.attribute("height", "20"), + attribute.attribute("rx", "2"), + attribute.attribute("ry", "2"), + ]), + svg.line([ + attribute.attribute("x1", "8"), + attribute.attribute("y1", "11"), + attribute.attribute("x2", "8"), + attribute.attribute("y2", "16"), + ]), + svg.line([ + attribute.attribute("x1", "8"), + attribute.attribute("y1", "8"), + attribute.attribute("x2", "8.01"), + attribute.attribute("y2", "8"), + ]), + svg.line([ + attribute.attribute("x1", "12"), + attribute.attribute("y1", "16"), + attribute.attribute("x2", "12"), + attribute.attribute("y2", "11"), + ]), + svg.path([ + attribute.attribute("d", "M16 16v-3a2 2 0 0 0-4 0"), + ]), + ]) + "rss" -> + svg.g([], [ + svg.path([ + attribute.attribute("d", "M4 11a9 9 0 0 1 9 9"), + ]), + svg.path([ + attribute.attribute("d", "M4 4a16 16 0 0 1 16 16"), + ]), + svg.circle([ + attribute.attribute("cx", "5"), + attribute.attribute("cy", "19"), + attribute.attribute("r", "1"), + ]), + ]) + "facebook" -> + svg.path([ + attribute.attribute( + "d", + "M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z", + ), + ]) + "copy" -> + svg.g([], [ + svg.rect([ + attribute.attribute("x", "9"), + attribute.attribute("y", "9"), + attribute.attribute("width", "13"), + attribute.attribute("height", "13"), + attribute.attribute("rx", "2"), + attribute.attribute("ry", "2"), + ]), + svg.path([ + attribute.attribute( + "d", + "M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1", + ), + ]), + ]) + _ -> element.none() + } +} + +fn theme_classes() -> attribute.Attribute(msg) { + components.classes(["text-brand", "dark:text-white"]) +} diff --git a/src/blog/components/syntax_highlighting.gleam b/src/blog/components/syntax_highlighting.gleam new file mode 100644 index 0000000..45a0c6e --- /dev/null +++ b/src/blog/components/syntax_highlighting.gleam @@ -0,0 +1,158 @@ +//// Syntax highlighting components for blogatto (smalto). +//// Uses Prism One Light for light theme and VS Code Dark Plus for dark theme, +//// with Tailwind CSS arbitrary color classes and the dark: variant. + +import blogatto/config/post/code +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/html + +/// Returns the syntax highlighting configuration for the blog. +pub fn config() -> code.SyntaxHighlightingConfig(msg) { + code.default() + |> code.keyword(keyword) + |> code.string(string) + |> code.number(number) + |> code.comment(comment) + |> code.function(function) + |> code.operator(operator) + |> code.punctuation(punctuation) + |> code.type_(type_) + |> code.module(module) + |> code.variable(variable) + |> code.constant(constant) + |> code.builtin(builtin) + |> code.tag(tag) + |> code.attribute(attribute) + |> code.selector(selector) + |> code.property(property) + |> code.regex(regex) + |> code.custom(custom) +} + +// --- One Light (light) / VS Code Dark Plus (dark) token renderers --- + +fn keyword(value: String) -> Element(msg) { + // One Light: #a626a4 (purple) | Dark Plus: #569cd6 (blue) + themed_span("text-[#a626a4]", "dark:text-[#569cd6]", value) +} + +fn string(value: String) -> Element(msg) { + // One Light: #50a14f (green) | Dark Plus: #ce9178 (salmon) + themed_span("text-[#50a14f]", "dark:text-[#ce9178]", value) +} + +fn number(value: String) -> Element(msg) { + // One Light: #986801 (brown) | Dark Plus: #b5cea8 (light green) + themed_span("text-[#986801]", "dark:text-[#b5cea8]", value) +} + +fn comment(value: String) -> Element(msg) { + // One Light: #a0a1a7 (gray) | Dark Plus: #6a9955 (green) + html.span( + [ + attribute.class("text-[#a0a1a7] dark:text-[#6a9955] italic"), + ], + [element.text(value)], + ) +} + +fn function(value: String) -> Element(msg) { + // One Light: #4078f2 (blue) | Dark Plus: #dcdcaa (yellow) + themed_span("text-[#4078f2]", "dark:text-[#dcdcaa]", value) +} + +fn operator(value: String) -> Element(msg) { + // One Light: #0184bc (teal) | Dark Plus: #d4d4d4 (light gray) + themed_span("text-[#0184bc]", "dark:text-[#d4d4d4]", value) +} + +fn punctuation(value: String) -> Element(msg) { + // One Light: #383a42 (dark gray) | Dark Plus: #d4d4d4 (light gray) + themed_span("text-[#383a42]", "dark:text-[#d4d4d4]", value) +} + +fn type_(value: String) -> Element(msg) { + // One Light: #c18401 (golden) | Dark Plus: #4ec9b0 (teal) + themed_span("text-[#c18401]", "dark:text-[#4ec9b0]", value) +} + +fn module(value: String) -> Element(msg) { + // One Light: #c18401 (golden) | Dark Plus: #4ec9b0 (teal) + themed_span("text-[#c18401]", "dark:text-[#4ec9b0]", value) +} + +fn variable(value: String) -> Element(msg) { + // One Light: #e45649 (red) | Dark Plus: #9cdcfe (light blue) + themed_span("text-[#e45649]", "dark:text-[#9cdcfe]", value) +} + +fn constant(value: String) -> Element(msg) { + // One Light: #986801 (brown) | Dark Plus: #4fc1ff (cyan) + themed_span("text-[#986801]", "dark:text-[#4fc1ff]", value) +} + +fn builtin(value: String) -> Element(msg) { + // One Light: #c18401 (golden) | Dark Plus: #4ec9b0 (teal) + themed_span("text-[#c18401]", "dark:text-[#4ec9b0]", value) +} + +fn tag(value: String) -> Element(msg) { + // One Light: #e45649 (red) | Dark Plus: #569cd6 (blue) + themed_span("text-[#e45649]", "dark:text-[#569cd6]", value) +} + +fn attribute(value: String) -> Element(msg) { + // One Light: #986801 (brown) | Dark Plus: #9cdcfe (light blue) + themed_span("text-[#986801]", "dark:text-[#9cdcfe]", value) +} + +fn selector(value: String) -> Element(msg) { + // One Light: #e45649 (red) | Dark Plus: #d7ba7d (gold) + themed_span("text-[#e45649]", "dark:text-[#d7ba7d]", value) +} + +fn property(value: String) -> Element(msg) { + // One Light: #986801 (brown) | Dark Plus: #9cdcfe (light blue) + themed_span("text-[#986801]", "dark:text-[#9cdcfe]", value) +} + +fn regex(value: String) -> Element(msg) { + // One Light: #50a14f (green) | Dark Plus: #d16969 (red) + themed_span("text-[#50a14f]", "dark:text-[#d16969]", value) +} + +fn custom(name: String, value: String) -> Element(msg) { + case name { + "important" -> + html.span( + [ + attribute.class("font-bold text-[#a626a4] dark:text-[#569cd6]"), + ], + [element.text(value)], + ) + "bold" -> html.span([attribute.class("font-bold")], [element.text(value)]) + "italic" -> html.span([attribute.class("italic")], [element.text(value)]) + "strike" -> + html.span([attribute.class("line-through")], [element.text(value)]) + "code" -> themed_span("text-[#50a14f]", "dark:text-[#ce9178]", value) + "url" -> + html.span( + [ + attribute.class("underline text-[#0184bc] dark:text-[#4ec9b0]"), + ], + [element.text(value)], + ) + _ -> element.text(value) + } +} + +fn themed_span( + light_class: String, + dark_class: String, + value: String, +) -> Element(msg) { + html.span([attribute.class(light_class <> " " <> dark_class)], [ + element.text(value), + ]) +} diff --git a/src/blog/config.gleam b/src/blog/config.gleam new file mode 100644 index 0000000..3bb8d42 --- /dev/null +++ b/src/blog/config.gleam @@ -0,0 +1,196 @@ +import blog/components/md_components +import blog/components/syntax_highlighting +import blog/pages/blog +import blog/pages/home +import blog/pages/not_found +import blog/pages/privacy +import blog/site +import blog/template/blog as blog_template +import blogatto/config +import blogatto/config/feed +import blogatto/config/feed/atom as atom_feed +import blogatto/config/feed/rss as rss_feed +import blogatto/config/post +import blogatto/config/robots +import blogatto/config/sitemap +import gleam/dict +import gleam/list +import gleam/option +import gleam/string +import gleam/time/timestamp +import marceau + +pub fn config() -> config.Config(Nil) { + let md = + post.default() + |> post.path("./blog") + |> post.route_prefix("blog") + |> post.template(blog_template.template) + |> post.components(md_components.components()) + |> post.syntax_highlighting(syntax_highlighting.config()) + + let rss = + rss_feed.new(site.feed_title, site.origin, site.feed_description) + |> rss_feed.language(site.language) + |> rss_feed.output("/rss.xml") + |> rss_feed.serialize(serialize_rss_feed_item) + + let atom = + atom_feed.new( + site.origin <> "/", + atom_feed.PlainText(site.feed_title), + timestamp.system_time(), + ) + |> atom_feed.subtitle(site.feed_description) + |> atom_feed.link(atom_feed.Link( + href: site.origin <> "/atom.xml", + rel: option.Some("self"), + content_type: option.Some("application/atom+xml"), + hreflang: option.Some(site.language), + title: option.None, + length: option.None, + )) + |> atom_feed.author(atom_feed.Person( + name: site.author_name, + email: option.Some(site.author_email), + uri: option.Some("https://www.veeso.me/"), + )) + |> atom_feed.output("/atom.xml") + |> atom_feed.serialize(serialize_atom_feed_item) + |> atom_feed.rights(atom_feed.PlainText( + "© 2026 春晏 + +文章采用 CC BY-NC-ND 4.0 许可协议。", + )) + + site.origin + |> config.new() + |> config.output_dir("./dist") + |> config.static_dir("./static") + |> config.post(md) + |> config.atom_feed(atom) + |> config.rss_feed(rss) + |> config.sitemap( + sitemap.new("/sitemap.xml") + |> sitemap.filter(fn(url) { + url != site.origin <> "/404" && url != site.origin <> "/404/" + }) + |> sitemap.serialize(fn(url) { + sitemap.SitemapEntry( + url: canonical_sitemap_url(url), + priority: option.None, + last_modified: option.None, + change_frequency: option.None, + ) + }), + ) + |> config.route("/", home.home) + |> config.route("/blog/", blog.blog) + |> config.route("/privacy/", privacy.privacy) + |> config.route("/404/", not_found.not_found) + |> config.robots( + robots.RobotsConfig(sitemap_url: site.origin <> "/sitemap.xml", robots: [ + robots.Robot( + user_agent: "*", + allowed_routes: ["/"], + disallowed_routes: [], + ), + ]), + ) +} + +fn serialize_rss_feed_item( + metadata: feed.FeedMetadata(msg), +) -> rss_feed.RssFeedItem { + let enclosure = case metadata.post.featured_image { + option.None -> option.None + option.Some(featured_image) -> { + let url = case featured_image { + "http" <> _ -> featured_image + path -> site.origin <> "/blog/" <> metadata.post.slug <> "/" <> path + } + let mime = image_mime_type(featured_image) + option.Some(rss_feed.Enclosure(url:, length: 0, enclosure_type: mime)) + } + } + + let categories = + metadata.post.extras + |> dict.get("category") + |> option.from_result + |> option.map(fn(x) { [x] }) + |> option.unwrap(or: []) + + rss_feed.RssFeedItem( + title: metadata.post.title, + description: metadata.post.excerpt, + link: option.Some(metadata.url), + author: option.Some(site.author_email), + comments: option.None, + source: option.None, + pub_date: option.Some(metadata.post.date), + categories:, + enclosure:, + guid: option.Some(metadata.url), + ) +} + +fn serialize_atom_feed_item( + metadata: feed.FeedMetadata(msg), +) -> atom_feed.AtomFeedItem { + let categories = + metadata.post.extras + |> dict.get("category") + |> option.from_result + |> option.map(fn(x) { + [atom_feed.Category(term: x, scheme: option.None, label: option.Some(x))] + }) + |> option.unwrap(or: []) + + atom_feed.AtomFeedItem( + id: metadata.url, + title: atom_feed.PlainText(metadata.post.title), + updated: metadata.post.date, + authors: [ + atom_feed.Person( + name: site.author_name, + email: option.Some(site.author_email), + uri: option.Some("https://www.veeso.me/"), + ), + ], + content: option.None, + link: option.Some(atom_feed.Link( + href: metadata.url, + rel: option.Some("alternate"), + content_type: option.None, + hreflang: option.Some(site.language), + title: option.None, + length: option.None, + )), + summary: option.Some(atom_feed.PlainText(metadata.post.excerpt)), + categories:, + contributors: [], + published: option.Some(metadata.post.date), + rights: option.None, + source: option.None, + ) +} + +fn image_mime_type(filename: String) -> String { + let name = string.lowercase(filename) + let extension = + name + |> string.split(".") + |> list.last() + |> option.from_result() + |> option.unwrap("") + + marceau.extension_to_mime_type(extension) +} + +fn canonical_sitemap_url(url: String) -> String { + case string.ends_with(url, "/") { + True -> url + False -> url <> "/" + } +} diff --git a/src/blog/dev.gleam b/src/blog/dev.gleam new file mode 100644 index 0000000..23e9217 --- /dev/null +++ b/src/blog/dev.gleam @@ -0,0 +1,29 @@ +//// Runner for dev server with live reloading and file watching. + +import blog/config +import blogatto/dev +import gleam/io +import tailwind + +pub fn main() { + case tailwind.install() { + Ok(_) -> io.println("Tailwindcss installed successfully!") + Error(e) -> panic as { "Failed to install Tailwind: " <> e } + } + + config.config() + |> dev.new() + |> dev.after_build(build_tailwind_css) + |> dev.port(3000) + |> dev.start() +} + +fn build_tailwind_css() -> Result(Nil, String) { + case tailwind.run(["--input=assets/blog.css", "--output=dist/blog.css"]) { + Ok(out) -> { + io.println("Tailwindcss built successfully: " <> out) + Ok(Nil) + } + Error(e) -> Error("Failed to run Tailwind: " <> e) + } +} diff --git a/src/blog/pages/blog.gleam b/src/blog/pages/blog.gleam new file mode 100644 index 0000000..c92cd43 --- /dev/null +++ b/src/blog/pages/blog.gleam @@ -0,0 +1,49 @@ +//// Blog listing page showing all published Rust posts. + +import blog/components +import blog/components/heading +import blog/components/post_preview +import blog/site +import blog/template/page +import blogatto/post +import gleam/dict +import gleam/list +import gleam/option +import lustre/element.{type Element} +import lustre/element/html + +/// Render the blog listing page with all published posts in a responsive grid. +pub fn blog(posts: List(post.Post(Nil))) -> Element(Nil) { + let url = site.origin <> "/blog/" + let config = + page.PageConfig( + title: "Rust 文章 | chunyan.dev", + description: "阅读春晏的 Rust 文章,了解实际开发中的问题、解决思路和项目经验。", + url:, + featured_image: option.Some(site.origin <> "/og_preview.jpeg"), + page_type: "website", + structured_data: option.None, + noindex: False, + ) + + page.page(config, [page_content(posts)], element.none()) +} + +fn page_content(posts: List(post.Post(Nil))) -> Element(Nil) { + element.fragment([ + heading.h1(dict.new(), "", [element.text("全部 Rust 文章")]), + html.div( + [ + components.classes([ + "grid", + "grid-cols-2", + "gap-4", + "sm:grid-cols-1", + "items-start", + "justify-start", + ]), + ], + list.map(posts, post_preview.post_preview), + ), + ]) +} diff --git a/src/blog/pages/home.gleam b/src/blog/pages/home.gleam new file mode 100644 index 0000000..126be87 --- /dev/null +++ b/src/blog/pages/home.gleam @@ -0,0 +1,86 @@ +//// Homepage with the author's bio and latest Rust posts. + +import blog/components +import blog/components/container +import blog/components/heading +import blog/components/post_preview +import blog/site +import blog/template/page +import blogatto/post +import gleam/dict +import gleam/list +import gleam/option +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/html + +/// Render the homepage with the author's bio and the four latest posts. +pub fn home(posts: List(post.Post(Nil))) -> Element(Nil) { + let url = site.origin <> "/" + let config = + page.PageConfig( + title: "春晏的 Rust 博客 | chunyan.dev", + description: "春晏的 Rust 开发笔记:从所有权、异步编程到性能优化,分享实际项目中的经验、踩坑和解决办法。", + url:, + featured_image: option.Some(site.origin <> "/og_preview.jpeg"), + page_type: "website", + structured_data: option.Some(page.website_structured_data(url)), + noindex: False, + ) + + page.page(config, [page_content(posts)], element.none()) +} + +fn page_content(posts: List(post.Post(Nil))) -> Element(Nil) { + element.fragment([ + heading.h1(dict.new(), "", [element.text("春晏的 Rust 开发笔记")]), + bio(), + latest_posts(posts), + ]) +} + +fn bio() -> Element(Nil) { + container.responsive_row( + ["items-center", "justify-between", "gap-8", "p-10"], + [ + html.div([], [ + html.img([ + attribute.src("/avatar.webp"), + attribute.alt("春晏的头像"), + attribute.loading("eager"), + components.classes(["rounded-full", "h-auto", "w-[128px]"]), + ]), + ]), + html.div([attribute.class("flex-1")], [ + html.p( + [ + components.classes([ + "text-brand", + "w-full", + "mb-3", + "text-justify", + "dark:text-gray-200", + ]), + ], + [ + element.text( + "你好,我是春晏(Christian Visintin),住在意大利乌迪内,是一名自由软件工程师,也做开源项目。这里专门聊 Rust:写代码时踩过的坑、折腾出来的东西,还有一些可能没必要、但我还是想说的看法。", + ), + ], + ), + ]), + ], + ) +} + +fn latest_posts(posts: List(post.Post(Nil))) -> Element(Nil) { + let latest_posts = list.take(posts, 4) + + html.div([], [ + heading.h2(dict.new(), "", [element.text("最新文章")]), + html.div( + [components.classes(["grid", "grid-cols-2", "gap-x-4", "sm:grid-cols-1"])], + list.map(latest_posts, post_preview.post_preview), + ), + ]) +} diff --git a/src/blog/pages/not_found.gleam b/src/blog/pages/not_found.gleam new file mode 100644 index 0000000..2862330 --- /dev/null +++ b/src/blog/pages/not_found.gleam @@ -0,0 +1,52 @@ +//// Chinese error page for paths that do not exist. + +import blog/components +import blog/components/heading +import blog/site +import blog/template/page +import blogatto/post +import gleam/dict +import gleam/option +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/html + +/// Render the internal page used as the site's HTTP 404 document. +pub fn not_found(_posts: List(post.Post(Nil))) -> Element(Nil) { + let url = site.origin <> "/404/" + let config = + page.PageConfig( + title: "页面不存在 | chunyan.dev", + description: "这个页面可能已移动,或者地址有误。", + url:, + featured_image: option.Some(site.origin <> "/og_preview.jpeg"), + page_type: "website", + structured_data: option.None, + noindex: True, + ) + + page.page(config, [page_content()], element.none()) +} + +fn page_content() -> Element(Nil) { + html.div([components.classes(["flex", "flex-col", "gap-4", "p-8"])], [ + heading.h1(dict.new(), "", [element.text("页面不存在")]), + html.p([], [element.text("这个页面可能已移动,或者地址有误。")]), + html.div([components.classes(["flex", "gap-4", "sm:flex-col"])], [ + html.a( + [ + attribute.href("/"), + components.classes(["underline", "font-medium"]), + ], + [element.text("返回首页")], + ), + html.a( + [ + attribute.href("/blog/"), + components.classes(["underline", "font-medium"]), + ], + [element.text("浏览 Rust 文章")], + ), + ]), + ]) +} diff --git a/src/blog/pages/privacy.gleam b/src/blog/pages/privacy.gleam new file mode 100644 index 0000000..4b44a8e --- /dev/null +++ b/src/blog/pages/privacy.gleam @@ -0,0 +1,232 @@ +//// Privacy information for the static blog. + +import blog/components +import blog/components/heading +import blog/site +import blog/template/page +import blogatto/post +import gleam/dict +import gleam/option +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/html + +/// VAT number of the data controller. +const author_vat = "IT03104140300" + +/// Contact email for privacy-related requests. +const contact_email = "christian.visintin@veeso.dev" + +/// Render the privacy information page. +pub fn privacy(_posts: List(post.Post(Nil))) -> Element(Nil) { + let url = site.origin <> "/privacy/" + let config = + page.PageConfig( + title: "隐私政策 | chunyan.dev", + description: "了解 chunyan.dev 的网站托管、主题偏好存储和数据处理方式。", + url:, + featured_image: option.Some(site.origin <> "/og_preview.jpeg"), + page_type: "website", + structured_data: option.None, + noindex: False, + ) + + page.page(config, [page_content()], element.none()) +} + +fn page_content() -> Element(Nil) { + html.div([components.classes(["flex", "flex-col", "gap-2"])], [ + heading.h1(dict.new(), "", [element.text("隐私政策")]), + last_updated(), + overview(), + data_controller(), + cookies(), + hosting(), + analytics(), + third_party_resources(), + international_transfers(), + your_rights(), + external_links(), + changes(), + ]) +} + +fn last_updated() -> Element(msg) { + html.p( + [ + components.classes([ + "text-sm", + "text-gray-500", + "dark:text-gray-400", + "mb-4", + ]), + ], + [element.text("最后更新:2026年9月17日")], + ) +} + +fn overview() -> Element(msg) { + section("概览", [ + paragraph([ + element.text( + "这是 chunyan.dev 的个人 Rust 博客。网站不使用广告、跟踪 Cookie 或分析脚本,也不会通过本网站出售个人数据。为了提供网页并保障服务安全,托管服务商可能处理访问所必需的技术信息。本政策说明网站涉及的数据处理、用途以及你可以行使的权利,并参考欧盟《通用数据保护条例》(GDPR)和意大利数据保护法(D.Lgs. 196/2003,经 D.Lgs. 101/2018 修订)。", + ), + ]), + ]) +} + +fn data_controller() -> Element(msg) { + section("数据控制者和联系方式", [ + paragraph([ + element.text("数据控制者是 "), + html.strong([], [element.text("veeso.dev di Christian Visintin")]), + element.text(",增值税号为 "), + element.text(author_vat), + element.text("。如需咨询隐私问题或行使相关权利,请联系 "), + mail_link(contact_email), + element.text("。"), + ]), + ]) +} + +fn cookies() -> Element(msg) { + section("Cookie 和本地存储", [ + paragraph([ + element.text( + "本网站不使用 Cookie 来记录或分析你的行为,也不显示 Cookie 同意横幅。主题偏好(浅色或深色模式)会通过浏览器的 localStorage 保存在你的设备上。这项设置只用于记住显示偏好,不会发送给我,也不用于识别或跟踪你。", + ), + ]), + ]) +} + +fn hosting() -> Element(msg) { + section("网站托管和服务器日志", [ + paragraph([ + element.text( + "本网站由 Vercel 提供托管。像其他网站服务器一样,托管服务可能为了传输页面、维护服务安全和防止滥用而处理访问请求所需的技术信息,例如 IP 地址、浏览器信息、请求地址、来源页面和时间戳。相关处理由托管服务商按照其自身的隐私政策和服务条款进行。", + ), + ]), + paragraph([ + html.strong([], [element.text("处理依据:")]), + element.text("运营网站、维护安全并处理滥用行为所需的合法利益。网站本身不会利用这些技术信息建立广告画像。"), + ]), + ]) +} + +fn analytics() -> Element(msg) { + section("分析脚本", [ + paragraph([ + element.text( + "本网站没有加载 Umami 或其他访问分析脚本,因此不会通过分析服务收集浏览量、来源或设备统计。若未来启用分析服务,我会在发布前更新本政策,准确说明实际使用的服务。", + ), + ]), + ]) +} + +fn third_party_resources() -> Element(msg) { + section("第三方资源", [ + paragraph([ + element.text( + "网页的样式、字体回退、图标和代码高亮所需资源随网站一同提供或由浏览器完成,不依赖 Google Fonts、jsDelivr 或其他第三方 CDN。页面上的 GitHub、Mastodon、X 以及分享链接只有在你主动点击后才会打开;离开本站后,目标服务的隐私政策适用。", + ), + ]), + ]) +} + +fn international_transfers() -> Element(msg) { + section("跨境数据传输", [ + paragraph([ + element.text( + "当你主动访问外部服务时,相关服务可能按照其自身政策在你所在国家或其他国家处理技术信息。本站不会为了分析或广告而主动把访客数据发送给这些服务。", + ), + ]), + ]) +} + +fn your_rights() -> Element(msg) { + section("你的权利", [ + paragraph([ + element.text( + "在适用的法律范围内,你可以请求访问、更正、删除或限制处理与你有关的个人数据,也可以反对某些处理并请求数据可携带。由于本站不建立访客账户,也不运行分析脚本,我可能无法把匿名技术日志与具体个人对应起来。", + ), + ]), + paragraph([ + element.text("如需行使权利,请通过 "), + mail_link(contact_email), + element.text(" 联系我。你也可以向意大利个人数据保护监管机构 "), + external_link("https://www.garanteprivacy.it", "意大利个人数据保护机构"), + element.text("或你居住地的数据保护机构投诉。"), + ]), + ]) +} + +fn external_links() -> Element(msg) { + section("外部链接", [ + paragraph([ + element.text( + "本网站包含 GitHub、Mastodon 和 X 等外部服务的链接。打开这些链接后,目标网站会按照自己的隐私政策处理数据;我不负责外部网站的内容或隐私实践。", + ), + ]), + ]) +} + +fn changes() -> Element(msg) { + section("政策变更", [ + paragraph([ + element.text("本隐私政策可能随网站功能或实际数据处理方式变化而更新。任何变更都会发布在本页面,并同步更新“最后更新”日期。"), + ]), + ]) +} + +fn section(title: String, body: List(Element(msg))) -> Element(msg) { + html.section([components.classes(["mb-4"])], [ + heading.h2(dict.new(), "", [element.text(title)]), + ..body + ]) +} + +fn paragraph(children: List(Element(msg))) -> Element(msg) { + html.p( + [ + components.classes([ + "mb-3", + "text-brand", + "dark:text-gray-200", + "text-justify", + ]), + ], + children, + ) +} + +fn mail_link(email: String) -> Element(msg) { + html.a( + [ + attribute.href("mailto:" <> email), + components.classes([ + "text-brand", + "dark:text-white", + "underline", + "font-medium", + ]), + ], + [element.text(email)], + ) +} + +fn external_link(href: String, label: String) -> Element(msg) { + html.a( + [ + attribute.href(href), + attribute.target("_blank"), + attribute.rel("noopener noreferrer"), + components.classes([ + "text-brand", + "dark:text-white", + "underline", + "font-medium", + ]), + ], + [element.text(label)], + ) +} diff --git a/src/blog/site.gleam b/src/blog/site.gleam new file mode 100644 index 0000000..421e02c --- /dev/null +++ b/src/blog/site.gleam @@ -0,0 +1,19 @@ +//// Shared public identity and canonical site values. + +pub const name = "chunyan.dev" + +pub const origin = "https://blog.chunyan.dev" + +pub const author_name = "春晏" + +pub const author_email = "christian.visintin@veeso.dev" + +pub const language = "zh-CN" + +pub const og_locale = "zh_CN" + +pub const feed_title = "chunyan.dev · 春晏的 Rust 博客" + +pub const feed_description = "春晏的 Rust 开发笔记,分享实战经验、踩坑记录和技术思考。" + +pub const preview_image_alt = "chunyan.dev 的 Rust 博客预览图" diff --git a/src/blog/template/blog.gleam b/src/blog/template/blog.gleam new file mode 100644 index 0000000..232c8ca --- /dev/null +++ b/src/blog/template/blog.gleam @@ -0,0 +1,387 @@ +//// Blog post page template with article layout and share buttons. + +import blog/components +import blog/components/container +import blog/components/heading +import blog/components/post_meta +import blog/components/svg +import blog/site +import blog/template/page +import blogatto/post +import gleam/dict +import gleam/json +import gleam/list +import gleam/option +import gleam/string +import gleam/time/duration +import gleam/time/timestamp +import gleam/uri +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/html + +/// Render a full blog post page with featured image, metadata, and share buttons. +pub fn template( + post: post.Post(msg), + all_posts: List(post.Post(msg)), +) -> Element(msg) { + let config = + page.PageConfig( + title: post.title <> " | " <> site.name, + description: post.description, + url: post.url, + featured_image: absolute_featured_image(post), + page_type: "article", + structured_data: option.Some(article_structured_data(post)), + noindex: False, + ) + + page.page(config, [layout(post)], related_posts(post, all_posts)) +} + +/// Resolve the featured image to an absolute URL. +/// +/// Social platforms like X.com require absolute og:image / twitter:image URLs +/// to render preview cards; relative paths are silently ignored by them (while +/// Mastodon resolves them against the page URL). Already-absolute URLs are kept +/// as-is, relative paths are joined against the absolute post URL. +fn absolute_featured_image(post: post.Post(msg)) -> option.Option(String) { + post.featured_image + |> option.map(fn(image) { + case image { + "http" <> _ -> image + path -> post.url <> path + } + }) +} + +fn article_structured_data(post: post.Post(msg)) -> String { + let image = + post + |> absolute_featured_image + |> option.unwrap(or: site.origin <> "/og_preview.jpeg") + + json.object([ + #("@context", json.string("https://schema.org")), + #("@type", json.string("BlogPosting")), + #("headline", json.string(post.title)), + #("description", json.string(post.description)), + #("url", json.string(post.url)), + #( + "mainEntityOfPage", + json.object([ + #("@type", json.string("WebPage")), + #("@id", json.string(post.url)), + ]), + ), + #( + "datePublished", + json.string(timestamp.to_rfc3339(post.date, duration.seconds(0))), + ), + #("inLanguage", json.string(site.language)), + #( + "author", + json.object([ + #("@type", json.string("Person")), + #("name", json.string(site.author_name)), + ]), + ), + #("image", json.string(image)), + ]) + |> json.to_string + |> string.replace("<", "\\u003c") +} + +fn layout(post: post.Post(msg)) -> Element(msg) { + let featured_image = + post.featured_image + |> option.map(attribute.src) + |> option.unwrap(or: attribute.none()) + + html.div( + [components.classes(["m-4", "max-w-3xl", "w-auto", "sm:max-w-full", "p-2"])], + [ + html.img([ + featured_image, + attribute.alt("文章配图:" <> post.description), + components.classes(["rounded", "inset-0"]), + ]), + html.div([], [ + heading.h1(dict.new(), "", [element.text(post.title)]), + ]), + html.p( + [components.classes(["text-lg", "text-gray-600", "dark:text-gray-300"])], + [element.text(post.description)], + ), + html.div([components.classes(["mx-auto"])], [article(post)]), + ], + ) +} + +fn article(post: post.Post(msg)) -> Element(msg) { + html.article([components.classes(["px-4"])], [ + container.responsive_row( + [ + "items-center", + "justify-between", + ], + [ + html.div([], [ + post_meta.formatted_date(post.date), + element.text(" — "), + post_meta.reading_time(post), + ]), + share_buttons(post.url, post.title), + ], + ), + html.div([components.classes(["py-4"])], post.contents), + article_footer(post), + ]) +} + +fn article_footer(post: post.Post(msg)) -> Element(msg) { + container.col([], [ + container.responsive_row( + [ + "justify-between", + "items-center", + "my-10", + "sm:gap-8", + ], + [ + container.responsive_row( + [ + "items-center", + "justify-center", + "gap-8", + ], + [ + html.a( + [ + attribute.href("/blog/"), + components.classes([ + "font-medium", + "text-lg", + "text-brand", + "dark:text-gray-300", + "underline", + "hover:no-underline", + ]), + ], + [element.text("更多 Rust 文章")], + ), + html.a( + [ + attribute.href("https://hachyderm.io/@veeso_dev"), + components.classes([ + "font-medium", + "text-brand", + "dark:text-gray-200", + "underline", + "hover:no-underline", + ]), + ], + [ + svg.mastodon(20), + element.text("在 Mastodon 上关注我"), + ], + ), + share_buttons(post.url, post.title), + ], + ), + ], + ), + ]) +} + +fn share_buttons(url: String, title: String) -> Element(msg) { + container.row(["text-brand", "dark:text-gray-200", "gap-8", "justify-end"], [ + share_link( + facebook_share_url(url), + "分享到 Facebook", + svg.feather_icon("facebook"), + ), + share_link(x_share_url(url, title), "分享到 X", svg.x(20)), + share_link( + linkedin_share_url(url, title), + "分享到 LinkedIn", + svg.feather_icon("linkedin"), + ), + share_link(telegram_share_url(url, title), "分享到 Telegram", svg.telegram(20)), + share_link(whatsapp_share_url(url, title), "分享到 WhatsApp", svg.whatsapp(20)), + ]) +} + +fn share_link(href: String, label: String, icon: Element(msg)) -> Element(msg) { + html.a( + [ + attribute.href(href), + attribute.target("_blank"), + attribute.attribute("rel", "noopener noreferrer"), + attribute.attribute("aria-label", label), + components.classes([ + "transition-transform", "transform", "scale-100", "hover:scale-125", + "inline-flex", "items-center", + ]), + ], + [icon], + ) +} + +fn facebook_share_url(url: String) -> String { + "https://www.facebook.com/sharer/sharer.php?u=" <> uri.percent_encode(url) +} + +fn x_share_url(url: String, title: String) -> String { + "https://twitter.com/intent/tweet?url=" + <> uri.percent_encode(url) + <> "&text=" + <> uri.percent_encode(title) +} + +fn linkedin_share_url(url: String, title: String) -> String { + "https://www.linkedin.com/shareArticle?mini=true&url=" + <> uri.percent_encode(url) + <> "&title=" + <> uri.percent_encode(title) +} + +fn telegram_share_url(url: String, title: String) -> String { + "https://t.me/share/url?url=" + <> uri.percent_encode(url) + <> "&text=" + <> uri.percent_encode(title) +} + +fn whatsapp_share_url(url: String, title: String) -> String { + "https://wa.me/?text=" <> uri.percent_encode(title <> " " <> url) +} + +fn related_posts( + post: post.Post(msg), + all_posts: List(post.Post(msg)), +) -> Element(msg) { + case dict.get(post.extras, "category") { + Error(_) -> element.none() + Ok(category) -> { + let siblings = + all_posts + |> list.filter(fn(post) { + case dict.get(post.extras, "category") { + Error(_) -> False + Ok(post_category) -> post_category == category + } + }) + |> list.shuffle + |> list.take(2) + case siblings { + [] -> element.none() + siblings -> related_posts_view(siblings) + } + } + } +} + +fn related_posts_view(posts: List(post.Post(msg))) -> Element(msg) { + html.div([], [ + html.div( + [ + components.classes(["pt-4", "pb-2"]), + ], + [ + html.span( + [ + components.classes([ + "text-xl", + "block", + "text-brand", + "dark:text-white", + "font-normal", + ]), + ], + [element.text("你可能还想看")], + ), + ], + ), + html.div( + [ + components.classes([ + "grid", + "grid-cols-2", + "sm:grid-cols-1", + "gap-4", + "items-start", + "justify-start", + ]), + ], + list.map(posts, related_post_card), + ), + ]) +} + +fn related_post_card(post: post.Post(msg)) -> Element(msg) { + let featured_image = case post.featured_image { + option.None -> element.none() + option.Some(url) -> { + let featured_image = post_uri(post) <> url + html.img([ + attribute.src(featured_image), + attribute.alt("文章配图:" <> post.description), + attribute.class("rounded-t-lg"), + ]) + } + } + + html.a( + [ + attribute.href(post_uri(post)), + components.classes([ + "block", + "rounded", + "shadow-lg", + "dark:shadow-none", + "bg-white", + "dark:bg-zinc-800", + "text-brand", + "h-full", + "dark:text-gray-200", + "transition-transform", + "transform", + "hover:scale-105", + ]), + ], + [ + html.div([components.classes(["rounded-t-lg", "inset-0"])], [ + featured_image, + ]), + html.div([components.classes(["pt-4", "pb-6", "px-6"])], [ + html.div([], [ + html.span( + [ + components.classes([ + "text-md", + "sm:text-lg", + "py-2", + "dark:text-white", + "text-brand", + "font-normal", + ]), + ], + [element.text(post.title)], + ), + ]), + html.p( + [ + components.classes(["text-justify", "text-brand", "dark:text-white"]), + ], + [element.text(post.excerpt)], + ), + ]), + ], + ) +} + +/// relative url to post +fn post_uri(post: post.Post(msg)) -> String { + "/blog/" <> post.slug <> "/" +} diff --git a/src/blog/template/footer.gleam b/src/blog/template/footer.gleam new file mode 100644 index 0000000..e30bed3 --- /dev/null +++ b/src/blog/template/footer.gleam @@ -0,0 +1,88 @@ +//// Site footer with copyright notice. + +import blog/components +import blog/components/container +import blog/site +import gleam/int +import gleam/time/duration +import gleam/time/timestamp +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/html + +/// Render the site footer with copyright and the current year. +pub fn footer() -> Element(msg) { + html.footer([], [ + container.col( + [ + "bg-brand", + "text-white", + "py-10", + "items-center", + "justify-center", + "gap-4", + ], + [built_with_blogatto(), privacy_line(), copyright_line()], + ), + ]) +} + +fn built_with_blogatto() -> Element(msg) { + html.div( + [ + components.classes([ + "text-center", + "text-sm", + "text-gray-300", + ]), + ], + [ + element.text("由 "), + html.a( + [ + components.classes(["underline"]), + attribute.href("https://blogat.to"), + ], + [ + element.text("Blogatto"), + html.img([ + attribute.src("/blogatto.svg"), + attribute.alt("Blogatto 标志"), + components.classes(["inline", "h-8", "ml-1"]), + ]), + ], + ), + element.text(" 驱动"), + ], + ) +} + +fn privacy_line() -> Element(msg) { + html.div([components.classes(["text-center", "text-sm", "text-gray-300"])], [ + html.a([components.classes(["underline"]), attribute.href("/privacy/")], [ + element.text("隐私政策"), + ]), + ]) +} + +fn copyright_line() -> Element(msg) { + html.div([components.classes(["text-center", "text-sm", "text-gray-300"])], [ + element.text("© " <> current_year() <> " " <> site.author_name <> " · "), + html.a( + [ + attribute.href("https://creativecommons.org/licenses/by-nc-nd/4.0/"), + attribute.target("_blank"), + attribute.rel("noopener noreferrer"), + components.classes(["underline"]), + ], + [element.text("文章采用 CC BY-NC-ND 4.0 许可协议")], + ), + ]) +} + +fn current_year() -> String { + let #(date, _time) = + timestamp.system_time() + |> timestamp.to_calendar(duration.seconds(0)) + int.to_string(date.year) +} diff --git a/src/blog/template/page.gleam b/src/blog/template/page.gleam new file mode 100644 index 0000000..6816ef8 --- /dev/null +++ b/src/blog/template/page.gleam @@ -0,0 +1,277 @@ +//// Full HTML page template with SEO metadata, theme support, and site layout. + +import blog/components +import blog/components/container +import blog/site +import blog/template/footer +import blog/template/topbar +import gleam/json +import gleam/option.{type Option} +import gleam/string +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/html + +/// Configuration for rendering a page. +pub type PageConfig { + PageConfig( + /// Page title shown in the browser tab and meta tags. + title: String, + /// Page description for SEO meta tags. + description: String, + /// Canonical URL for this page. + url: String, + /// Optional featured image URL for OG/Twitter card tags. + featured_image: Option(String), + /// Open Graph page type, either `website` or `article`. + page_type: String, + /// Optional serialized JSON-LD structured data. + structured_data: Option(String), + /// Whether search engines should keep this page out of their index. + noindex: Bool, + ) +} + +/// Render a full HTML page with the given configuration and body children. +pub fn page( + config: PageConfig, + children: List(Element(msg)), + before_footer: Element(msg), +) -> Element(msg) { + html.html([attribute.lang(site.language)], [ + head(config), + body(children, before_footer), + ]) +} + +/// Serialize the site's homepage structured data. +pub fn website_structured_data(url: String) -> String { + json.object([ + #("@context", json.string("https://schema.org")), + #("@type", json.string("WebSite")), + #("name", json.string(site.name)), + #("url", json.string(url)), + #("inLanguage", json.string(site.language)), + #( + "author", + json.object([ + #("@type", json.string("Person")), + #("name", json.string(site.author_name)), + ]), + ), + ]) + |> json.to_string + |> escape_script_data +} + +fn head(config: PageConfig) -> Element(msg) { + html.head([], [ + html.meta([attribute.charset("UTF-8")]), + html.meta([ + attribute.name("viewport"), + attribute.content("width=device-width, initial-scale=1.0"), + ]), + html.title([], config.title), + html.meta([ + attribute.name("description"), + attribute.content(config.description), + ]), + noindex_meta(config.noindex), + html.link([ + attribute.rel("canonical"), + attribute.href(config.url), + ]), + og_meta("og:title", config.title), + og_meta("og:description", config.description), + og_meta("og:type", config.page_type), + og_meta("og:url", config.url), + og_meta("og:site_name", site.name), + og_meta("og:locale", site.og_locale), + html.meta([ + attribute.name("twitter:creator"), + attribute.content("@veeso_dev"), + ]), + html.meta([ + attribute.name("twitter:title"), + attribute.content(config.title), + ]), + html.meta([ + attribute.name("twitter:description"), + attribute.content(config.description), + ]), + html.meta([ + attribute.name("fediverse:creator"), + attribute.content("@veeso_dev@hachyderm.io"), + ]), + featured_image_meta(config.featured_image), + feed_discovery_links(), + html.link([ + attribute.rel("icon"), + attribute.type_("image/x-icon"), + attribute.href("/favicon.ico"), + ]), + html.link([ + attribute.rel("icon"), + attribute.type_("image/png"), + attribute.attribute("sizes", "16x16"), + attribute.href("/favicon-16x16.png"), + ]), + html.link([ + attribute.rel("icon"), + attribute.type_("image/png"), + attribute.attribute("sizes", "32x32"), + attribute.href("/favicon-32x32.png"), + ]), + html.link([ + attribute.rel("icon"), + attribute.type_("image/png"), + attribute.attribute("sizes", "96x96"), + attribute.href("/favicon-96x96.png"), + ]), + html.link([ + attribute.rel("stylesheet"), + attribute.href("/blog.css"), + ]), + structured_data(config.structured_data), + html.script([], dark_mode_js), + ]) +} + +fn noindex_meta(noindex: Bool) -> Element(msg) { + case noindex { + True -> + html.meta([ + attribute.name("robots"), + attribute.content("noindex, nofollow"), + ]) + False -> element.none() + } +} + +fn feed_discovery_links() -> Element(msg) { + element.fragment([ + html.link([ + attribute.rel("alternate"), + attribute.type_("application/rss+xml"), + attribute.title(site.feed_title <> "(RSS)"), + attribute.href("/rss.xml"), + ]), + html.link([ + attribute.rel("alternate"), + attribute.type_("application/atom+xml"), + attribute.title(site.feed_title <> "(Atom)"), + attribute.href("/atom.xml"), + ]), + ]) +} + +fn structured_data(data: Option(String)) -> Element(msg) { + case data { + option.Some(json) -> + html.script([attribute.type_("application/ld+json")], json) + option.None -> element.none() + } +} + +fn body( + children: List(Element(msg)), + before_footer: Element(msg), +) -> Element(msg) { + html.body([], [ + html.div([], [ + container.col( + [ + "bg-page", + "dark:bg-zinc-900", + "items-center", + "justify-center", + "pt-4", + "pb-12", + "sm:pt-0", + ], + [ + container.col( + [ + "items-center", + "bg-white", + "dark:bg-brand", + "text-brand", + "dark:text-white", + "rounded", + "shadow-xl", + "dark:shadow-none", + "justify-center", + "w-fit", + "sm:w-full", + "sm:rounded-none", + ], + [ + html.div( + [ + components.classes([ + "m-4", + "max-w-screen-md", + "w-auto", + "sm:max-w-full", + "p-2", + ]), + ], + [topbar.topbar(), html.main([], children)], + ), + ], + ), + html.div( + [ + components.classes([ + "max-w-screen-md", + "w-auto", + "sm:max-w-full", + "py-4", + ]), + ], + [before_footer], + ), + ], + ), + ]), + footer.footer(), + ]) +} + +fn featured_image_meta(image: Option(String)) -> Element(msg) { + case image { + option.Some(url) -> + element.fragment([ + og_meta("og:image", url), + og_meta("og:image:alt", site.preview_image_alt), + html.meta([ + attribute.name("twitter:card"), + attribute.content("summary_large_image"), + ]), + html.meta([attribute.name("twitter:image"), attribute.content(url)]), + html.link([ + attribute.rel("preload"), + attribute.as_("image"), + attribute.href(url), + ]), + ]) + option.None -> + html.meta([ + attribute.name("twitter:card"), + attribute.content("summary"), + ]) + } +} + +fn og_meta(property: String, content: String) -> Element(msg) { + html.meta([ + attribute.attribute("property", property), + attribute.content(content), + ]) +} + +fn escape_script_data(json: String) -> String { + string.replace(json, "<", "\\u003c") +} + +const dark_mode_js = "(function(){try{var t=window.localStorage.getItem('theme');var d=t==='dark'||(!t&&window.matchMedia('(prefers-color-scheme:dark)').matches);if(d)document.documentElement.classList.add('dark')}catch(_){}})()" diff --git a/src/blog/template/topbar.gleam b/src/blog/template/topbar.gleam new file mode 100644 index 0000000..809fd2b --- /dev/null +++ b/src/blog/template/topbar.gleam @@ -0,0 +1,200 @@ +//// Site topbar with logo, navigation links, theme toggle, and social icons. + +import blog/components +import blog/components/container +import blog/components/svg +import blog/site +import lustre/attribute +import lustre/element.{type Element} +import lustre/element/html + +const github_url = "https://github.com/veeso" + +const mastodon_url = "https://hachyderm.io/@veeso_dev" + +const x_url = "https://x.com/veeso_dev" + +const linkedin_url = "https://www.linkedin.com/in/christian-visintin/" + +const rss_url = "/rss.xml" + +const about_url = "https://www.veeso.me/" + +/// Render the site topbar with logo, navigation, and social links. +pub fn topbar() -> Element(msg) { + html.header([], [topbar_body()]) +} + +fn topbar_body() -> Element(msg) { + container.col(["items-start", "justify-between", "w-full", "top-0"], [ + logo_section(), + nav_section(), + ]) +} + +/// Logo, site title, and subtitle. +fn logo_section() -> Element(msg) { + html.div([components.classes(["flex", "gap-4", "items-center", "pb-4"])], [ + html.div([], [ + html.a( + [ + attribute.href("/"), + components.classes(["text-brand", "no-underline"]), + ], + [ + html.img([ + attribute.src("/logo.webp"), + attribute.alt("chunyan.dev 标志"), + attribute.width(64), + attribute.height(64), + attribute.attribute("loading", "eager"), + ]), + ], + ), + ]), + container.col([], [ + html.a( + [ + attribute.href("/"), + components.classes([ + "text-xl", "text-brand", "dark:text-gray-200", "no-underline", + "text-left", "sm:text-xl", + ]), + ], + [element.text(site.name)], + ), + html.span( + [ + components.classes([ + "block", "text-sm", "text-gray-500", "dark:text-gray-300", + ]), + ], + [element.text("春晏的 Rust 博客")], + ), + ]), + ]) +} + +/// Navigation links and controls row. +fn nav_section() -> Element(msg) { + container.responsive_row( + ["items-center", "justify-between", "w-full", "sm:items-start", "sm:gap-4"], + [nav_links(), controls()], + ) +} + +/// Article, about, and feed navigation links. +fn nav_links() -> Element(msg) { + html.nav( + [ + attribute.attribute("aria-label", "主要导航"), + components.classes(["flex", "gap-4"]), + ], + [ + html.a([attribute.href("/blog/"), nav_link_classes()], [ + element.text("文章"), + ]), + html.a( + [ + attribute.href(about_url), + attribute.target("_blank"), + nav_link_classes(), + ], + [element.text("关于我(英文)")], + ), + html.a([attribute.href(rss_url), nav_link_classes()], [ + element.text("RSS 订阅"), + ]), + ], + ) +} + +/// Theme toggle and social links. +fn controls() -> Element(msg) { + html.div( + [ + components.classes([ + "flex", "justify-self-end", "items-end", "justify-between", + ]), + ], + [ + html.div( + [ + components.classes([ + "flex", "items-center", "justify-between", "gap-8", + ]), + ], + [theme_toggle(), socials()], + ), + ], + ) +} + +/// Theme toggle button that switches between light and dark mode. +fn theme_toggle() -> Element(msg) { + html.button( + [ + attribute.id("theme-toggle"), + attribute.attribute("onclick", theme_toggle_js), + attribute.attribute("type", "button"), + attribute.attribute("aria-label", "切换深色模式"), + icon_link_classes(), + ], + [ + // Sun icon (visible in light mode, hidden in dark mode) + html.span( + [attribute.id("theme-icon-sun"), components.classes(["dark:hidden"])], + [svg.feather_icon("sun")], + ), + // Moon icon (hidden in light mode, visible in dark mode) + html.span( + [ + attribute.id("theme-icon-moon"), + components.classes(["hidden", "dark:inline"]), + ], + [svg.feather_icon("moon")], + ), + ], + ) +} + +/// Social media icon links. +fn socials() -> Element(msg) { + element.fragment([ + icon_link(github_url, "访问 GitHub 主页", svg.feather_icon("github")), + icon_link(mastodon_url, "访问 Mastodon 主页", svg.mastodon(24)), + icon_link(x_url, "访问 X 主页", svg.x(24)), + icon_link(linkedin_url, "访问 LinkedIn 主页", svg.feather_icon("linkedin")), + icon_link(rss_url, "RSS 订阅", svg.feather_icon("rss")), + ]) +} + +/// A link styled for icon display. +fn icon_link(href: String, label: String, icon: Element(msg)) -> Element(msg) { + html.a( + [ + attribute.href(href), + attribute.target("_blank"), + attribute.attribute("aria-label", label), + icon_link_classes(), + ], + [icon], + ) +} + +fn nav_link_classes() -> attribute.Attribute(msg) { + components.classes([ + "text-gray-500", "dark:text-gray-200", "no-underline", "text-xl", + "transition-colors", "duration-500", "hover:text-brand", "hover:underline", + "cursor-pointer", + ]) +} + +fn icon_link_classes() -> attribute.Attribute(msg) { + components.classes([ + "inline-flex", "items-center", "cursor-pointer", "text-brand", + "dark:text-white", + ]) +} + +const theme_toggle_js = "(function(){var d=document.documentElement;var isDark=d.classList.contains('dark');if(isDark){d.classList.remove('dark')}else{d.classList.add('dark')}try{window.localStorage.setItem('theme',isDark?'light':'dark')}catch(_){}})()" diff --git a/static/avatar.webp b/static/avatar.webp new file mode 100644 index 0000000..d24c5dd Binary files /dev/null and b/static/avatar.webp differ diff --git a/static/blogatto.svg b/static/blogatto.svg new file mode 100644 index 0000000..80f1fb9 --- /dev/null +++ b/static/blogatto.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/static/favicon-16x16.png b/static/favicon-16x16.png new file mode 100644 index 0000000..915ca3b Binary files /dev/null and b/static/favicon-16x16.png differ diff --git a/static/favicon-32x32.png b/static/favicon-32x32.png new file mode 100644 index 0000000..7b2f661 Binary files /dev/null and b/static/favicon-32x32.png differ diff --git a/static/favicon-96x96.png b/static/favicon-96x96.png new file mode 100644 index 0000000..0a4dcd8 Binary files /dev/null and b/static/favicon-96x96.png differ diff --git a/static/favicon.ico b/static/favicon.ico new file mode 100644 index 0000000..cdc79ea Binary files /dev/null and b/static/favicon.ico differ diff --git a/static/logo.webp b/static/logo.webp new file mode 100644 index 0000000..4655219 Binary files /dev/null and b/static/logo.webp differ diff --git a/static/og_preview.jpeg b/static/og_preview.jpeg new file mode 100644 index 0000000..a4ac935 Binary files /dev/null and b/static/og_preview.jpeg differ diff --git a/test/blog_test.gleam b/test/blog_test.gleam new file mode 100644 index 0000000..fba3c88 --- /dev/null +++ b/test/blog_test.gleam @@ -0,0 +1,13 @@ +import gleeunit + +pub fn main() -> Nil { + gleeunit.main() +} + +// gleeunit test functions end in `_test` +pub fn hello_world_test() { + let name = "Joe" + let greeting = "Hello, " <> name <> "!" + + assert greeting == "Hello, Joe!" +} diff --git a/test/page_test.gleam b/test/page_test.gleam new file mode 100644 index 0000000..bc8249d --- /dev/null +++ b/test/page_test.gleam @@ -0,0 +1,45 @@ +import blog/template/blog as blog_template +import blog/template/page +import blogatto/post +import gleam/dict +import gleam/option +import gleam/result +import gleam/string +import gleam/time/timestamp +import gleeunit +import lustre/element + +pub fn main() -> Nil { + gleeunit.main() +} + +pub fn structured_data_escapes_script_delimiters_test() { + let data = + page.website_structured_data("https://blog.chunyan.dev/\"") + + assert string.contains(data, "\\\"") + assert string.contains(data, "\\u003c/script>") + assert !string.contains(data, "") +} + +pub fn article_title_is_safe_in_structured_data_test() { + let article = + post.Post( + title: "标题 \"引用\" ", + slug: "test", + url: "https://blog.chunyan.dev/blog/test/", + date: timestamp.parse_rfc3339("2026-09-17T00:00:00Z") + |> result.unwrap(or: timestamp.unix_epoch), + description: "测试描述", + excerpt: "测试摘要", + language: option.None, + featured_image: option.None, + contents: [], + extras: dict.new(), + ) + + let rendered = blog_template.template(article, []) |> element.to_string + + assert string.contains(rendered, "\\\"引用\\\"") + assert string.contains(rendered, "\\u003c/script>") +} diff --git a/test/post_meta_test.gleam b/test/post_meta_test.gleam new file mode 100644 index 0000000..d883034 --- /dev/null +++ b/test/post_meta_test.gleam @@ -0,0 +1,68 @@ +import blog/components/post_meta +import blogatto/post +import gleam/dict +import gleam/option +import gleam/result +import gleam/string +import gleam/time/timestamp +import gleeunit +import lustre/element + +pub fn main() -> Nil { + gleeunit.main() +} + +pub fn dates_use_utc_plus_eight_test() { + let date = parse_date("2026-09-16T16:30:00Z") + let rendered = date |> post_meta.formatted_date |> element.to_string + + assert string.contains(rendered, "2026年9月17日") + assert string.contains(rendered, "datetime=\"2026-09-16T16:30:00Z\"") +} + +pub fn dates_cross_new_year_test() { + let date = parse_date("2026-12-31T16:00:00Z") + let rendered = date |> post_meta.formatted_date |> element.to_string + + assert string.contains(rendered, "2027年1月1日") +} + +pub fn missing_reading_time_is_one_minute_test() { + assert reading_time_for(dict.new()) == "约 1 分钟阅读" +} + +pub fn invalid_reading_time_is_one_minute_test() { + let extras = dict.new() |> dict.insert("reading_time", "not-a-number") + assert reading_time_for(extras) == "约 1 分钟阅读" +} + +pub fn non_positive_reading_time_is_one_minute_test() { + let zero = dict.new() |> dict.insert("reading_time", "0") + let negative = dict.new() |> dict.insert("reading_time", "-2") + + assert reading_time_for(zero) == "约 1 分钟阅读" + assert reading_time_for(negative) == "约 1 分钟阅读" +} + +fn parse_date(value: String) -> timestamp.Timestamp { + value + |> timestamp.parse_rfc3339 + |> result.unwrap(or: timestamp.unix_epoch) +} + +fn reading_time_for(extras: dict.Dict(String, String)) -> String { + post.Post( + title: "测试文章", + slug: "test", + url: "https://example.com/blog/test/", + date: timestamp.unix_epoch, + description: "测试", + excerpt: "测试", + language: option.None, + featured_image: option.None, + contents: [], + extras: extras, + ) + |> post_meta.reading_time + |> element.to_string +}