Compare commits
No commits in common. "master" and "fixes-2" have entirely different histories.
3
.github/FUNDING.yml
vendored
|
|
@ -1,3 +0,0 @@
|
||||||
# These are supported funding model platforms
|
|
||||||
|
|
||||||
github: [maddalax]
|
|
||||||
52
.github/workflows/release-auth-example.yml
vendored
|
|
@ -1,52 +0,0 @@
|
||||||
name: Build and Deploy htmgo auth example
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_run:
|
|
||||||
workflows: [ "Update HTMGO Framework Dependency" ] # The name of the first workflow
|
|
||||||
types:
|
|
||||||
- completed
|
|
||||||
workflow_dispatch: # Trigger on manual workflow_dispatch
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master # Trigger on pushes to master
|
|
||||||
paths:
|
|
||||||
- 'examples/simple-auth/**' # Trigger only if files in this directory change
|
|
||||||
- "framework-ui/**"
|
|
||||||
- "cli/**"
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build-and-push:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout code
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v2
|
|
||||||
|
|
||||||
- name: Log in to GitHub Container Registry
|
|
||||||
uses: docker/login-action@v2
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: ${{ github.actor }}
|
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Get short commit hash
|
|
||||||
id: vars
|
|
||||||
run: echo "::set-output name=short_sha::$(echo $GITHUB_SHA | cut -c1-7)"
|
|
||||||
|
|
||||||
- name: Build Docker image
|
|
||||||
run: |
|
|
||||||
cd ./examples/simple-auth && docker build -t ghcr.io/${{ github.repository_owner }}/simple-auth:${{ steps.vars.outputs.short_sha }} .
|
|
||||||
|
|
||||||
- name: Tag as latest Docker image
|
|
||||||
run: |
|
|
||||||
docker tag ghcr.io/${{ github.repository_owner }}/simple-auth:${{ steps.vars.outputs.short_sha }} ghcr.io/${{ github.repository_owner }}/simple-auth:latest
|
|
||||||
|
|
||||||
- name: Log in to GitHub Container Registry
|
|
||||||
run: echo "${{ secrets.CR_PAT }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin
|
|
||||||
|
|
||||||
- name: Push Docker image
|
|
||||||
run: |
|
|
||||||
docker push ghcr.io/${{ github.repository_owner }}/simple-auth:latest
|
|
||||||
7
.github/workflows/release-chat-example.yml
vendored
|
|
@ -1,10 +1,9 @@
|
||||||
name: Build and Deploy htmgo.dev chat example
|
name: Build and Deploy htmgo.dev chat example
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_run:
|
pull_request:
|
||||||
workflows: [ "Update HTMGO Framework Dependency" ] # The name of the first workflow
|
branches:
|
||||||
types:
|
- master
|
||||||
- completed
|
|
||||||
workflow_dispatch: # Trigger on manual workflow_dispatch
|
workflow_dispatch: # Trigger on manual workflow_dispatch
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
|
|
|
||||||
52
.github/workflows/release-hn-clone.yml
vendored
|
|
@ -1,52 +0,0 @@
|
||||||
name: Build and Deploy htmgo hackernews clone
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_run:
|
|
||||||
workflows: [ "Update HTMGO Framework Dependency" ] # The name of the first workflow
|
|
||||||
types:
|
|
||||||
- completed
|
|
||||||
workflow_dispatch: # Trigger on manual workflow_dispatch
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master # Trigger on pushes to master
|
|
||||||
paths:
|
|
||||||
- 'examples/hackernews/**' # Trigger only if files in this directory change
|
|
||||||
- "framework-ui/**"
|
|
||||||
- "cli/**"
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build-and-push:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout code
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v2
|
|
||||||
|
|
||||||
- name: Log in to GitHub Container Registry
|
|
||||||
uses: docker/login-action@v2
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: ${{ github.actor }}
|
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Get short commit hash
|
|
||||||
id: vars
|
|
||||||
run: echo "::set-output name=short_sha::$(echo $GITHUB_SHA | cut -c1-7)"
|
|
||||||
|
|
||||||
- name: Build Docker image
|
|
||||||
run: |
|
|
||||||
cd ./examples/hackernews && docker build -t ghcr.io/${{ github.repository_owner }}/hackernews:${{ steps.vars.outputs.short_sha }} .
|
|
||||||
|
|
||||||
- name: Tag as latest Docker image
|
|
||||||
run: |
|
|
||||||
docker tag ghcr.io/${{ github.repository_owner }}/hackernews:${{ steps.vars.outputs.short_sha }} ghcr.io/${{ github.repository_owner }}/hackernews:latest
|
|
||||||
|
|
||||||
- name: Log in to GitHub Container Registry
|
|
||||||
run: echo "${{ secrets.CR_PAT }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin
|
|
||||||
|
|
||||||
- name: Push Docker image
|
|
||||||
run: |
|
|
||||||
docker push ghcr.io/${{ github.repository_owner }}/hackernews:latest
|
|
||||||
7
.github/workflows/release-site.yml
vendored
|
|
@ -1,16 +1,13 @@
|
||||||
name: Build and Deploy htmgo.dev
|
name: Build and Deploy htmgo.dev
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_run:
|
|
||||||
workflows: [ "Update HTMGO Framework Dependency" ] # The name of the first workflow
|
|
||||||
types:
|
|
||||||
- completed
|
|
||||||
workflow_dispatch: # Trigger on manual workflow_dispatch
|
workflow_dispatch: # Trigger on manual workflow_dispatch
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master # Trigger on pushes to master
|
- master # Trigger on pushes to master
|
||||||
paths:
|
paths:
|
||||||
- 'htmgo-site/**' # Trigger only if files in this directory change
|
- 'htmgo-site/**' # Trigger only if files in this directory change
|
||||||
|
- "framework/**"
|
||||||
- "framework-ui/**"
|
- "framework-ui/**"
|
||||||
- "cli/**"
|
- "cli/**"
|
||||||
|
|
||||||
|
|
@ -49,4 +46,4 @@ jobs:
|
||||||
|
|
||||||
- name: Push Docker image
|
- name: Push Docker image
|
||||||
run: |
|
run: |
|
||||||
docker push ghcr.io/${{ github.repository_owner }}/htmgo-site:latest
|
docker push ghcr.io/${{ github.repository_owner }}/htmgo-site:latest
|
||||||
|
|
@ -1,10 +1,6 @@
|
||||||
name: Build and Deploy starter template
|
name: Build and Deploy starter template
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_run:
|
|
||||||
workflows: [ "Update HTMGO Framework Dependency" ] # The name of the first workflow
|
|
||||||
types:
|
|
||||||
- completed
|
|
||||||
workflow_dispatch: # Trigger on manual workflow_dispatch
|
workflow_dispatch: # Trigger on manual workflow_dispatch
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
|
|
@ -47,4 +43,4 @@ jobs:
|
||||||
|
|
||||||
- name: Push Docker image
|
- name: Push Docker image
|
||||||
run: |
|
run: |
|
||||||
docker push ghcr.io/${{ github.repository_owner }}/starter-template:latest
|
docker push ghcr.io/${{ github.repository_owner }}/starter-template:latest
|
||||||
6
.github/workflows/release-todo-example.yml
vendored
|
|
@ -1,10 +1,6 @@
|
||||||
name: Build and Deploy htmgo.dev todo example
|
name: Build and Deploy htmgo.dev todo example
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_run:
|
|
||||||
workflows: [ "Update HTMGO Framework Dependency" ] # The name of the first workflow
|
|
||||||
types:
|
|
||||||
- completed
|
|
||||||
workflow_dispatch: # Trigger on manual workflow_dispatch
|
workflow_dispatch: # Trigger on manual workflow_dispatch
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
|
|
@ -47,4 +43,4 @@ jobs:
|
||||||
|
|
||||||
- name: Push Docker image
|
- name: Push Docker image
|
||||||
run: |
|
run: |
|
||||||
docker push ghcr.io/${{ github.repository_owner }}/htmgo-todo-example:latest
|
docker push ghcr.io/${{ github.repository_owner }}/htmgo-todo-example:latest
|
||||||
48
.github/workflows/release-ws-test.yml
vendored
|
|
@ -1,48 +0,0 @@
|
||||||
name: Build and Deploy ws-test
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_run:
|
|
||||||
workflows: [ "Update HTMGO Framework Dependency" ] # The name of the first workflow
|
|
||||||
types:
|
|
||||||
- completed
|
|
||||||
workflow_dispatch:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- ws-testing
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build-and-push:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout code
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v2
|
|
||||||
|
|
||||||
- name: Log in to GitHub Container Registry
|
|
||||||
uses: docker/login-action@v2
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: ${{ github.actor }}
|
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Get short commit hash
|
|
||||||
id: vars
|
|
||||||
run: echo "::set-output name=short_sha::$(echo $GITHUB_SHA | cut -c1-7)"
|
|
||||||
|
|
||||||
- name: Build Docker image
|
|
||||||
run: |
|
|
||||||
cd ./examples/ws-example && docker build -t ghcr.io/${{ github.repository_owner }}/ws-example:${{ steps.vars.outputs.short_sha }} .
|
|
||||||
|
|
||||||
- name: Tag as latest Docker image
|
|
||||||
run: |
|
|
||||||
docker tag ghcr.io/${{ github.repository_owner }}/ws-example:${{ steps.vars.outputs.short_sha }} ghcr.io/${{ github.repository_owner }}/ws-example:latest
|
|
||||||
|
|
||||||
- name: Log in to GitHub Container Registry
|
|
||||||
run: echo "${{ secrets.CR_PAT }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin
|
|
||||||
|
|
||||||
- name: Push Docker image
|
|
||||||
run: |
|
|
||||||
docker push ghcr.io/${{ github.repository_owner }}/ws-example:latest
|
|
||||||
33
.github/workflows/run-cli-tests.yml
vendored
|
|
@ -1,33 +0,0 @@
|
||||||
name: CLI Tests
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- '**' # Runs on any pull request to any branch
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
test:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout code
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set up Go
|
|
||||||
uses: actions/setup-go@v4
|
|
||||||
with:
|
|
||||||
go-version: '1.23' # Specify the Go version you need
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: cd ./cli/htmgo && go mod download
|
|
||||||
|
|
||||||
- name: Run Go tests
|
|
||||||
run: cd ./cli/htmgo/tasks/astgen && go test ./... -coverprofile=coverage.txt
|
|
||||||
|
|
||||||
- name: Upload results to Codecov
|
|
||||||
uses: codecov/codecov-action@v4
|
|
||||||
with:
|
|
||||||
token: ${{ secrets.CODECOV_TOKEN }}
|
|
||||||
9
.github/workflows/run-framework-tests.yml
vendored
|
|
@ -3,7 +3,7 @@ name: Framework Tests
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- '**' # Runs on any branch push
|
||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- '**' # Runs on any pull request to any branch
|
- '**' # Runs on any pull request to any branch
|
||||||
|
|
@ -25,9 +25,4 @@ jobs:
|
||||||
run: cd ./framework && go mod download
|
run: cd ./framework && go mod download
|
||||||
|
|
||||||
- name: Run Go tests
|
- name: Run Go tests
|
||||||
run: cd ./framework && go test ./... -coverprofile=coverage.txt
|
run: cd ./framework && go test ./...
|
||||||
|
|
||||||
- name: Upload results to Codecov
|
|
||||||
uses: codecov/codecov-action@v4
|
|
||||||
with:
|
|
||||||
token: ${{ secrets.CODECOV_TOKEN }}
|
|
||||||
|
|
|
||||||
3
.github/workflows/update-framework-dep.yml
vendored
|
|
@ -6,8 +6,7 @@ on:
|
||||||
branches:
|
branches:
|
||||||
- master # Trigger on pushes to master
|
- master # Trigger on pushes to master
|
||||||
paths:
|
paths:
|
||||||
- 'framework/**'
|
- 'framework/**' # Trigger only if files in this directory change
|
||||||
- 'tools/html-to-htmgo/**'
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
update-htmgo-dep:
|
update-htmgo-dep:
|
||||||
|
|
|
||||||
|
|
@ -1,128 +0,0 @@
|
||||||
# Contributor Covenant Code of Conduct
|
|
||||||
|
|
||||||
## Our Pledge
|
|
||||||
|
|
||||||
We as members, contributors, and leaders pledge to make participation in our
|
|
||||||
community a harassment-free experience for everyone, regardless of age, body
|
|
||||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
|
||||||
identity and expression, level of experience, education, socio-economic status,
|
|
||||||
nationality, personal appearance, race, religion, or sexual identity
|
|
||||||
and orientation.
|
|
||||||
|
|
||||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
|
||||||
diverse, inclusive, and healthy community.
|
|
||||||
|
|
||||||
## Our Standards
|
|
||||||
|
|
||||||
Examples of behavior that contributes to a positive environment for our
|
|
||||||
community include:
|
|
||||||
|
|
||||||
* Demonstrating empathy and kindness toward other people
|
|
||||||
* Being respectful of differing opinions, viewpoints, and experiences
|
|
||||||
* Giving and gracefully accepting constructive feedback
|
|
||||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
|
||||||
and learning from the experience
|
|
||||||
* Focusing on what is best not just for us as individuals, but for the
|
|
||||||
overall community
|
|
||||||
|
|
||||||
Examples of unacceptable behavior include:
|
|
||||||
|
|
||||||
* The use of sexualized language or imagery, and sexual attention or
|
|
||||||
advances of any kind
|
|
||||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
|
||||||
* Public or private harassment
|
|
||||||
* Publishing others' private information, such as a physical or email
|
|
||||||
address, without their explicit permission
|
|
||||||
* Other conduct which could reasonably be considered inappropriate in a
|
|
||||||
professional setting
|
|
||||||
|
|
||||||
## Enforcement Responsibilities
|
|
||||||
|
|
||||||
Community leaders are responsible for clarifying and enforcing our standards of
|
|
||||||
acceptable behavior and will take appropriate and fair corrective action in
|
|
||||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
|
||||||
or harmful.
|
|
||||||
|
|
||||||
Community leaders have the right and responsibility to remove, edit, or reject
|
|
||||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
|
||||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
|
||||||
decisions when appropriate.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
This Code of Conduct applies within all community spaces, and also applies when
|
|
||||||
an individual is officially representing the community in public spaces.
|
|
||||||
Examples of representing our community include using an official e-mail address,
|
|
||||||
posting via an official social media account, or acting as an appointed
|
|
||||||
representative at an online or offline event.
|
|
||||||
|
|
||||||
## Enforcement
|
|
||||||
|
|
||||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
|
||||||
reported to the community leaders responsible for enforcement at
|
|
||||||
maddox@htmgo.dev.
|
|
||||||
All complaints will be reviewed and investigated promptly and fairly.
|
|
||||||
|
|
||||||
All community leaders are obligated to respect the privacy and security of the
|
|
||||||
reporter of any incident.
|
|
||||||
|
|
||||||
## Enforcement Guidelines
|
|
||||||
|
|
||||||
Community leaders will follow these Community Impact Guidelines in determining
|
|
||||||
the consequences for any action they deem in violation of this Code of Conduct:
|
|
||||||
|
|
||||||
### 1. Correction
|
|
||||||
|
|
||||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
|
||||||
unprofessional or unwelcome in the community.
|
|
||||||
|
|
||||||
**Consequence**: A private, written warning from community leaders, providing
|
|
||||||
clarity around the nature of the violation and an explanation of why the
|
|
||||||
behavior was inappropriate. A public apology may be requested.
|
|
||||||
|
|
||||||
### 2. Warning
|
|
||||||
|
|
||||||
**Community Impact**: A violation through a single incident or series
|
|
||||||
of actions.
|
|
||||||
|
|
||||||
**Consequence**: A warning with consequences for continued behavior. No
|
|
||||||
interaction with the people involved, including unsolicited interaction with
|
|
||||||
those enforcing the Code of Conduct, for a specified period of time. This
|
|
||||||
includes avoiding interactions in community spaces as well as external channels
|
|
||||||
like social media. Violating these terms may lead to a temporary or
|
|
||||||
permanent ban.
|
|
||||||
|
|
||||||
### 3. Temporary Ban
|
|
||||||
|
|
||||||
**Community Impact**: A serious violation of community standards, including
|
|
||||||
sustained inappropriate behavior.
|
|
||||||
|
|
||||||
**Consequence**: A temporary ban from any sort of interaction or public
|
|
||||||
communication with the community for a specified period of time. No public or
|
|
||||||
private interaction with the people involved, including unsolicited interaction
|
|
||||||
with those enforcing the Code of Conduct, is allowed during this period.
|
|
||||||
Violating these terms may lead to a permanent ban.
|
|
||||||
|
|
||||||
### 4. Permanent Ban
|
|
||||||
|
|
||||||
**Community Impact**: Demonstrating a pattern of violation of community
|
|
||||||
standards, including sustained inappropriate behavior, harassment of an
|
|
||||||
individual, or aggression toward or disparagement of classes of individuals.
|
|
||||||
|
|
||||||
**Consequence**: A permanent ban from any sort of public interaction within
|
|
||||||
the community.
|
|
||||||
|
|
||||||
## Attribution
|
|
||||||
|
|
||||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
|
||||||
version 2.0, available at
|
|
||||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
|
||||||
|
|
||||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
|
||||||
enforcement ladder](https://github.com/mozilla/diversity).
|
|
||||||
|
|
||||||
[homepage]: https://www.contributor-covenant.org
|
|
||||||
|
|
||||||
For answers to common questions about this code of conduct, see the FAQ at
|
|
||||||
https://www.contributor-covenant.org/faq. Translations are available at
|
|
||||||
https://www.contributor-covenant.org/translations.
|
|
||||||
18
README.md
|
|
@ -1,3 +1,6 @@
|
||||||
|
> [!WARNING]
|
||||||
|
> htmgo is in alpha release and active development. API's likely will have breaking changes. Do not use this library at this time if you are expecting a rock solid stable api that will require no migrations. Please report any issues on GitHub.
|
||||||
|
|
||||||
## **htmgo**
|
## **htmgo**
|
||||||
|
|
||||||
### build simple and scalable systems with go + htmx
|
### build simple and scalable systems with go + htmx
|
||||||
|
|
@ -5,16 +8,8 @@
|
||||||
-------
|
-------
|
||||||
[](https://goreportcard.com/report/github.com/maddalax/htmgo)
|
[](https://goreportcard.com/report/github.com/maddalax/htmgo)
|
||||||

|

|
||||||
[](https://htmgo.dev/docs)
|
|
||||||
[](https://codecov.io/github/maddalax/htmgo)
|
|
||||||
[](https://htmgo.dev/discord)
|
|
||||||

|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<sup>looking for a python version? check out: https://fastht.ml</sup>
|
|
||||||
|
|
||||||
**introduction:**
|
**introduction:**
|
||||||
|
|
||||||
htmgo is a lightweight pure go way to build interactive websites / web applications using go & htmx.
|
htmgo is a lightweight pure go way to build interactive websites / web applications using go & htmx.
|
||||||
|
|
@ -39,12 +34,9 @@ func IndexPage(ctx *h.RequestContext) *h.Page {
|
||||||
2. live reload (rebuilds css, go, ent schema, and routes upon change)
|
2. live reload (rebuilds css, go, ent schema, and routes upon change)
|
||||||
3. automatic page and partial registration based on file path
|
3. automatic page and partial registration based on file path
|
||||||
4. built in tailwindcss support, no need to configure anything by default
|
4. built in tailwindcss support, no need to configure anything by default
|
||||||
5. custom [htmx extensions](https://github.com/maddalax/htmgo/tree/b610aefa36e648b98a13823a6f8d87566120cfcc/framework/assets/js/htmxextensions) to reduce boilerplate with common tasks
|
5. plugin architecture to include optional plugins to streamline development, such as http://entgo.io
|
||||||
|
6. custom [htmx extensions](https://github.com/maddalax/htmgo/tree/b610aefa36e648b98a13823a6f8d87566120cfcc/framework/assets/js/htmxextensions) to reduce boilerplate with common tasks
|
||||||
|
|
||||||
**get started:**
|
**get started:**
|
||||||
|
|
||||||
View documentation on [htmgo.dev](https://htmgo.dev/docs).
|
View documentation on [htmgo.dev](https://htmgo.dev/docs).
|
||||||
|
|
||||||
## Star History
|
|
||||||
|
|
||||||
[](https://star-history.com/#maddalax/htmgo&Date)
|
|
||||||
|
|
|
||||||
|
|
@ -3,25 +3,11 @@ module github.com/maddalax/htmgo/cli/htmgo
|
||||||
go 1.23.0
|
go 1.23.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/dave/jennifer v1.7.1
|
||||||
github.com/fsnotify/fsnotify v1.7.0
|
github.com/fsnotify/fsnotify v1.7.0
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b
|
|
||||||
github.com/maddalax/htmgo/tools/html-to-htmgo v0.0.0-20250703190716-06f01b3d7c1b
|
|
||||||
github.com/stretchr/testify v1.9.0
|
|
||||||
golang.org/x/mod v0.21.0
|
golang.org/x/mod v0.21.0
|
||||||
golang.org/x/sys v0.26.0
|
golang.org/x/net v0.29.0
|
||||||
|
golang.org/x/sys v0.25.0
|
||||||
golang.org/x/tools v0.25.0
|
golang.org/x/tools v0.25.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
|
||||||
)
|
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/bmatcuk/doublestar/v4 v4.7.1
|
|
||||||
github.com/go-chi/chi/v5 v5.1.0 // indirect
|
|
||||||
golang.org/x/net v0.30.0 // indirect
|
|
||||||
golang.org/x/text v0.19.0 // indirect
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
|
||||||
)
|
|
||||||
|
|
|
||||||
|
|
@ -1,32 +1,14 @@
|
||||||
github.com/bmatcuk/doublestar/v4 v4.7.1 h1:fdDeAqgT47acgwd9bd9HxJRDmc9UAmPpc+2m0CXv75Q=
|
github.com/dave/jennifer v1.7.1 h1:B4jJJDHelWcDhlRQxWeo0Npa/pYKBLrirAQoTN45txo=
|
||||||
github.com/bmatcuk/doublestar/v4 v4.7.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=
|
github.com/dave/jennifer v1.7.1/go.mod h1:nXbxhEmQfOZhWml3D1cDK5M1FLnMSozpbFN/m3RmGZc=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
|
||||||
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
|
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
|
||||||
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
|
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
|
||||||
github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
|
|
||||||
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
|
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b h1:m+xI+HBEQdie/Rs+mYI0HTFTMlYQSCv0l/siPDoywA4=
|
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b/go.mod h1:NGGzWVXWksrQJ9kV9SGa/A1F1Bjsgc08cN7ZVb98RqY=
|
|
||||||
github.com/maddalax/htmgo/tools/html-to-htmgo v0.0.0-20250703190716-06f01b3d7c1b h1:jvfp35fig2TzBjAgw82fe8+7cvaLX9EbipZUlj8FDDY=
|
|
||||||
github.com/maddalax/htmgo/tools/html-to-htmgo v0.0.0-20250703190716-06f01b3d7c1b/go.mod h1:FraJsj3NRuLBQDk83ZVa+psbNRNLe+rajVtVhYMEme4=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
|
||||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
|
||||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
|
||||||
golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0=
|
golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0=
|
||||||
golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
|
golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
|
||||||
golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4=
|
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
|
||||||
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
|
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
|
||||||
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
|
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
|
||||||
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
|
|
||||||
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
|
||||||
golang.org/x/tools v0.25.0 h1:oFU9pkj/iJgs+0DT+VMHrx+oBKs/LJMV+Uvg78sl+fE=
|
golang.org/x/tools v0.25.0 h1:oFU9pkj/iJgs+0DT+VMHrx+oBKs/LJMV+Uvg78sl+fE=
|
||||||
golang.org/x/tools v0.25.0/go.mod h1:/vtpO8WL1N9cQC3FN5zPqb//fRXskFHbLKk4OW1Q7rg=
|
golang.org/x/tools v0.25.0/go.mod h1:/vtpO8WL1N9cQC3FN5zPqb//fRXskFHbLKk4OW1Q7rg=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
|
|
|
||||||
119
cli/htmgo/htmltogo/entry.go
Normal file
|
|
@ -0,0 +1,119 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/dave/jennifer/jen"
|
||||||
|
"golang.org/x/net/html"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Example HTML input
|
||||||
|
htmlData := `
|
||||||
|
<body><nav class="flex gap-4 items-center p-4 text-slate-600 "><a href="/" class="cursor-pointer hover:text-blue-400 ">Home</a><a class="cursor-pointer hover:text-blue-400 " href="/news">News</a><a href="/patients" class="cursor-pointer hover:text-blue-400 ">Patients</a></nav><div id="active-modal"></div><div class="flex flex-col gap-2 bg-white h-full "><div class="flex flex-col p-4 w-full "><div><div class="flex justify-between items-center "><p class="text-lg font-bold ">Manage Patients</p><button hx-target="#active-modal" type="button" id="add-patient" class="flex gap-1 items-center border p-4 rounded cursor-hover bg-blue-700 text-white rounded p-2 h-12 " hx-get="htmgo/partials/patient.AddPatientSheet">Add Patient</button></div><div hx-get="htmgo/partials/patient.List" hx-trigger="load, patient-added from:body" class=""><div class="mt-8" id="patient-list"><div class="flex flex-col gap-2 rounded p-4 bg-red-100 "><p>Name: Sydne</p><p>Reason for visit: arm hurts</p></div></div></div></div></div></div><div hx-get="/livereload" hx-trigger="every 200ms" class=""></div></body>
|
||||||
|
`
|
||||||
|
|
||||||
|
// Parse the HTML
|
||||||
|
doc, err := html.Parse(bytes.NewReader([]byte(htmlData)))
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a new Jennifer file
|
||||||
|
f := jen.NewFile("main")
|
||||||
|
|
||||||
|
// Generate Jennifer code for the parsed HTML tree
|
||||||
|
generatedCode := processNode(doc.FirstChild)
|
||||||
|
|
||||||
|
// Add the generated code to the file
|
||||||
|
f.Func().Id("Render").Params().Block(generatedCode...)
|
||||||
|
|
||||||
|
// Render the generated code
|
||||||
|
var buf bytes.Buffer
|
||||||
|
err = f.Render(&buf)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
//// Format the generated code
|
||||||
|
//formattedCode, err := format.Source(buf.Bytes())
|
||||||
|
//if err != nil {
|
||||||
|
// log.Fatal(err)
|
||||||
|
//}
|
||||||
|
|
||||||
|
// Output the formatted code
|
||||||
|
fmt.Println(string(buf.Bytes()))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recursively process the HTML nodes and generate Jennifer code
|
||||||
|
func processNode(n *html.Node) []jen.Code {
|
||||||
|
var code []jen.Code
|
||||||
|
|
||||||
|
// Only process element nodes
|
||||||
|
if n.Type == html.ElementNode {
|
||||||
|
// Create a dynamic method call based on the tag name
|
||||||
|
tagMethod := strings.Title(n.Data) // Capitalize the first letter of the tag
|
||||||
|
|
||||||
|
// Add dynamic method call for the tag (e.g., h.Div(), h.Button(), etc.)
|
||||||
|
code = append(code, jen.Id("h").Dot(tagMethod).Call(mergeArgs(n)...))
|
||||||
|
}
|
||||||
|
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge attributes and children into a single slice for Call()
|
||||||
|
func mergeArgs(n *html.Node) []jen.Code {
|
||||||
|
// Process attributes
|
||||||
|
attrs := processAttributes(n.Attr)
|
||||||
|
|
||||||
|
// Process children
|
||||||
|
children := processChildren(n)
|
||||||
|
|
||||||
|
// Combine attributes and children into one slice
|
||||||
|
return append(attrs, children...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process child nodes of a given HTML node
|
||||||
|
func processChildren(n *html.Node) []jen.Code {
|
||||||
|
var children []jen.Code
|
||||||
|
|
||||||
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||||
|
children = append(children, processNode(c)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return children
|
||||||
|
}
|
||||||
|
|
||||||
|
func FormatFieldName(name string) string {
|
||||||
|
split := strings.Split(name, "_")
|
||||||
|
if strings.Contains(name, "-") {
|
||||||
|
split = strings.Split(name, "-")
|
||||||
|
}
|
||||||
|
parts := make([]string, 0)
|
||||||
|
for _, s := range split {
|
||||||
|
parts = append(parts, PascalCase(s))
|
||||||
|
}
|
||||||
|
return strings.Join(parts, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func PascalCase(s string) string {
|
||||||
|
if s == "" {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
// Convert the first rune (character) to uppercase and concatenate with the rest of the string
|
||||||
|
return strings.ToUpper(string(s[0])) + s[1:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process the attributes of an HTML node and return Jennifer code
|
||||||
|
func processAttributes(attrs []html.Attribute) []jen.Code {
|
||||||
|
var args []jen.Code
|
||||||
|
for _, attr := range attrs {
|
||||||
|
// Dynamically handle all attributes
|
||||||
|
attrMethod := FormatFieldName(attr.Key) // E.g., convert "data-role" to "DataRole"
|
||||||
|
args = append(args, jen.Id("h").Dot(attrMethod).Call(jen.Lit(attr.Val)))
|
||||||
|
}
|
||||||
|
return args
|
||||||
|
}
|
||||||
|
|
@ -4,7 +4,6 @@ import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/process"
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/process"
|
||||||
"github.com/maddalax/htmgo/framework/config"
|
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
|
|
@ -18,10 +17,6 @@ func HasFileFromRoot(file string) bool {
|
||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetConfig() *config.ProjectConfig {
|
|
||||||
return config.FromConfigFile(process.GetWorkingDir())
|
|
||||||
}
|
|
||||||
|
|
||||||
func CreateHtmgoDir() {
|
func CreateHtmgoDir() {
|
||||||
if !HasFileFromRoot("__htmgo") {
|
if !HasFileFromRoot("__htmgo") {
|
||||||
CreateDirFromRoot("__htmgo")
|
CreateDirFromRoot("__htmgo")
|
||||||
|
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
package dirutil
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/bmatcuk/doublestar/v4"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func matchesAny(patterns []string, path string) bool {
|
|
||||||
for _, pattern := range patterns {
|
|
||||||
matched, err :=
|
|
||||||
doublestar.Match(strings.ReplaceAll(pattern, `\`, "/"), strings.ReplaceAll(path, `\`, "/"))
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error matching pattern: %v\n", err)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if matched {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsGlobExclude(path string, excludePatterns []string) bool {
|
|
||||||
return matchesAny(excludePatterns, path)
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsGlobMatch(path string, patterns []string, excludePatterns []string) bool {
|
|
||||||
if matchesAny(excludePatterns, path) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return matchesAny(patterns, path)
|
|
||||||
}
|
|
||||||
|
|
@ -9,22 +9,20 @@ import (
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/copyassets"
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/copyassets"
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/css"
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/css"
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/downloadtemplate"
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/downloadtemplate"
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/formatter"
|
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/process"
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/process"
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/reloader"
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/reloader"
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/run"
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/run"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
const version = "1.0.6"
|
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
needsSignals := true
|
done := RegisterSignals()
|
||||||
|
|
||||||
commandMap := make(map[string]*flag.FlagSet)
|
commandMap := make(map[string]*flag.FlagSet)
|
||||||
commands := []string{"template", "run", "watch", "build", "setup", "css", "schema", "generate", "format", "version"}
|
commands := []string{"template", "run", "watch", "build", "setup", "css", "schema", "generate"}
|
||||||
|
|
||||||
for _, command := range commands {
|
for _, command := range commands {
|
||||||
commandMap[command] = flag.NewFlagSet(command, flag.ExitOnError)
|
commandMap[command] = flag.NewFlagSet(command, flag.ExitOnError)
|
||||||
|
|
@ -58,15 +56,6 @@ func main() {
|
||||||
slog.Debug("Running task:", slog.String("task", taskName))
|
slog.Debug("Running task:", slog.String("task", taskName))
|
||||||
slog.Debug("working dir:", slog.String("dir", process.GetWorkingDir()))
|
slog.Debug("working dir:", slog.String("dir", process.GetWorkingDir()))
|
||||||
|
|
||||||
if taskName == "format" {
|
|
||||||
needsSignals = false
|
|
||||||
}
|
|
||||||
|
|
||||||
done := make(chan bool, 1)
|
|
||||||
if needsSignals {
|
|
||||||
done = RegisterSignals()
|
|
||||||
}
|
|
||||||
|
|
||||||
if taskName == "watch" {
|
if taskName == "watch" {
|
||||||
fmt.Printf("Running in watch mode\n")
|
fmt.Printf("Running in watch mode\n")
|
||||||
os.Setenv("ENV", "development")
|
os.Setenv("ENV", "development")
|
||||||
|
|
@ -78,9 +67,21 @@ func main() {
|
||||||
fmt.Printf("Generating CSS...\n")
|
fmt.Printf("Generating CSS...\n")
|
||||||
css.GenerateCss(process.ExitOnError)
|
css.GenerateCss(process.ExitOnError)
|
||||||
|
|
||||||
// generate ast needs to be run after css generation
|
wg := sync.WaitGroup{}
|
||||||
astgen.GenAst(process.ExitOnError)
|
|
||||||
run.EntGenerate()
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
astgen.GenAst(process.ExitOnError)
|
||||||
|
}()
|
||||||
|
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
run.EntGenerate()
|
||||||
|
}()
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
fmt.Printf("Starting server...\n")
|
fmt.Printf("Starting server...\n")
|
||||||
process.KillAll()
|
process.KillAll()
|
||||||
|
|
@ -89,22 +90,7 @@ func main() {
|
||||||
}()
|
}()
|
||||||
startWatcher(reloader.OnFileChange)
|
startWatcher(reloader.OnFileChange)
|
||||||
} else {
|
} else {
|
||||||
if taskName == "version" {
|
if taskName == "schema" {
|
||||||
fmt.Printf("htmgo cli version %s\n", version)
|
|
||||||
os.Exit(0)
|
|
||||||
}
|
|
||||||
if taskName == "format" {
|
|
||||||
if len(os.Args) < 3 {
|
|
||||||
fmt.Println(fmt.Sprintf("Usage: htmgo format <file>"))
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
file := os.Args[2]
|
|
||||||
if file == "." {
|
|
||||||
formatter.FormatDir(process.GetWorkingDir())
|
|
||||||
} else {
|
|
||||||
formatter.FormatFile(os.Args[2])
|
|
||||||
}
|
|
||||||
} else if taskName == "schema" {
|
|
||||||
reader := bufio.NewReader(os.Stdin)
|
reader := bufio.NewReader(os.Stdin)
|
||||||
fmt.Print("Enter entity name:")
|
fmt.Print("Enter entity name:")
|
||||||
text, _ := reader.ReadString('\n')
|
text, _ := reader.ReadString('\n')
|
||||||
|
|
@ -118,10 +104,10 @@ func main() {
|
||||||
} else if taskName == "css" {
|
} else if taskName == "css" {
|
||||||
_ = css.GenerateCss(process.ExitOnError)
|
_ = css.GenerateCss(process.ExitOnError)
|
||||||
} else if taskName == "ast" {
|
} else if taskName == "ast" {
|
||||||
css.GenerateCss(process.ExitOnError)
|
|
||||||
_ = astgen.GenAst(process.ExitOnError)
|
_ = astgen.GenAst(process.ExitOnError)
|
||||||
} else if taskName == "run" {
|
} else if taskName == "run" {
|
||||||
run.MakeBuildable()
|
_ = astgen.GenAst(process.ExitOnError)
|
||||||
|
_ = css.GenerateCss(process.ExitOnError)
|
||||||
_ = run.Server(process.ExitOnError)
|
_ = run.Server(process.ExitOnError)
|
||||||
} else if taskName == "template" {
|
} else if taskName == "template" {
|
||||||
name := ""
|
name := ""
|
||||||
|
|
|
||||||
|
|
@ -2,21 +2,15 @@ package astgen
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/process"
|
||||||
"go/ast"
|
"go/ast"
|
||||||
"go/parser"
|
"go/parser"
|
||||||
"go/token"
|
"go/token"
|
||||||
"io/fs"
|
"golang.org/x/mod/modfile"
|
||||||
"log/slog"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"unicode"
|
|
||||||
|
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/internal/dirutil"
|
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/process"
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
"golang.org/x/mod/modfile"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Page struct {
|
type Page struct {
|
||||||
|
|
@ -30,7 +24,6 @@ type Partial struct {
|
||||||
FuncName string
|
FuncName string
|
||||||
Package string
|
Package string
|
||||||
Import string
|
Import string
|
||||||
Path string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const GeneratedDirName = "__htmgo"
|
const GeneratedDirName = "__htmgo"
|
||||||
|
|
@ -41,36 +34,6 @@ const ModuleName = "github.com/maddalax/htmgo/framework/h"
|
||||||
var PackageName = fmt.Sprintf("package %s", GeneratedDirName)
|
var PackageName = fmt.Sprintf("package %s", GeneratedDirName)
|
||||||
var GeneratedFileLine = fmt.Sprintf("// Package %s THIS FILE IS GENERATED. DO NOT EDIT.", GeneratedDirName)
|
var GeneratedFileLine = fmt.Sprintf("// Package %s THIS FILE IS GENERATED. DO NOT EDIT.", GeneratedDirName)
|
||||||
|
|
||||||
func toPascaleCase(input string) string {
|
|
||||||
words := strings.Split(input, "_")
|
|
||||||
for i := range words {
|
|
||||||
words[i] = strings.Title(strings.ToLower(words[i]))
|
|
||||||
}
|
|
||||||
return strings.Join(words, "")
|
|
||||||
}
|
|
||||||
|
|
||||||
func isValidGoVariableName(name string) bool {
|
|
||||||
// Variable name must not be empty
|
|
||||||
if name == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
// First character must be a letter or underscore
|
|
||||||
if !unicode.IsLetter(rune(name[0])) && name[0] != '_' {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
// Remaining characters must be letters, digits, or underscores
|
|
||||||
for _, char := range name[1:] {
|
|
||||||
if !unicode.IsLetter(char) && !unicode.IsDigit(char) && char != '_' {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func normalizePath(path string) string {
|
|
||||||
return strings.ReplaceAll(path, `\`, "/")
|
|
||||||
}
|
|
||||||
|
|
||||||
func sliceCommonPrefix(dir1, dir2 string) string {
|
func sliceCommonPrefix(dir1, dir2 string) string {
|
||||||
// Use filepath.Clean to normalize the paths
|
// Use filepath.Clean to normalize the paths
|
||||||
dir1 = filepath.Clean(dir1)
|
dir1 = filepath.Clean(dir1)
|
||||||
|
|
@ -96,35 +59,9 @@ func sliceCommonPrefix(dir1, dir2 string) string {
|
||||||
|
|
||||||
// Return the longer one
|
// Return the longer one
|
||||||
if len(slicedDir1) > len(slicedDir2) {
|
if len(slicedDir1) > len(slicedDir2) {
|
||||||
return normalizePath(slicedDir1)
|
return slicedDir1
|
||||||
}
|
}
|
||||||
return normalizePath(slicedDir2)
|
return slicedDir2
|
||||||
}
|
|
||||||
|
|
||||||
func hasOnlyReqContextParam(funcType *ast.FuncType) bool {
|
|
||||||
if len(funcType.Params.List) != 1 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if funcType.Params.List[0].Names == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if len(funcType.Params.List[0].Names) != 1 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
t := funcType.Params.List[0].Type
|
|
||||||
name, ok := t.(*ast.StarExpr)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
selectorExpr, ok := name.X.(*ast.SelectorExpr)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
ident, ok := selectorExpr.X.(*ast.Ident)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return ident.Name == "h" && selectorExpr.Sel.Name == "RequestContext"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func findPublicFuncsReturningHPartial(dir string, predicate func(partial Partial) bool) ([]Partial, error) {
|
func findPublicFuncsReturningHPartial(dir string, predicate func(partial Partial) bool) ([]Partial, error) {
|
||||||
|
|
@ -163,11 +100,10 @@ func findPublicFuncsReturningHPartial(dir string, predicate func(partial Partial
|
||||||
if selectorExpr, ok := starExpr.X.(*ast.SelectorExpr); ok {
|
if selectorExpr, ok := starExpr.X.(*ast.SelectorExpr); ok {
|
||||||
// Check if the package name is 'h' and type is 'Partial'.
|
// Check if the package name is 'h' and type is 'Partial'.
|
||||||
if ident, ok := selectorExpr.X.(*ast.Ident); ok && ident.Name == "h" {
|
if ident, ok := selectorExpr.X.(*ast.Ident); ok && ident.Name == "h" {
|
||||||
if selectorExpr.Sel.Name == "Partial" && hasOnlyReqContextParam(funcDecl.Type) {
|
if selectorExpr.Sel.Name == "Partial" {
|
||||||
p := Partial{
|
p := Partial{
|
||||||
Package: node.Name.Name,
|
Package: node.Name.Name,
|
||||||
Path: normalizePath(sliceCommonPrefix(cwd, path)),
|
Import: sliceCommonPrefix(cwd, strings.ReplaceAll(filepath.Dir(path), `\`, `/`)),
|
||||||
Import: sliceCommonPrefix(cwd, normalizePath(filepath.Dir(path))),
|
|
||||||
FuncName: funcDecl.Name.Name,
|
FuncName: funcDecl.Name.Name,
|
||||||
}
|
}
|
||||||
if predicate(p) {
|
if predicate(p) {
|
||||||
|
|
@ -230,11 +166,11 @@ func findPublicFuncsReturningHPage(dir string) ([]Page, error) {
|
||||||
if selectorExpr, ok := starExpr.X.(*ast.SelectorExpr); ok {
|
if selectorExpr, ok := starExpr.X.(*ast.SelectorExpr); ok {
|
||||||
// Check if the package name is 'h' and type is 'Partial'.
|
// Check if the package name is 'h' and type is 'Partial'.
|
||||||
if ident, ok := selectorExpr.X.(*ast.Ident); ok && ident.Name == "h" {
|
if ident, ok := selectorExpr.X.(*ast.Ident); ok && ident.Name == "h" {
|
||||||
if selectorExpr.Sel.Name == "Page" && hasOnlyReqContextParam(funcDecl.Type) {
|
if selectorExpr.Sel.Name == "Page" {
|
||||||
pages = append(pages, Page{
|
pages = append(pages, Page{
|
||||||
Package: node.Name.Name,
|
Package: node.Name.Name,
|
||||||
Import: normalizePath(filepath.Dir(path)),
|
Import: strings.ReplaceAll(filepath.Dir(path), `\`, `/`),
|
||||||
Path: normalizePath(path),
|
Path: path,
|
||||||
FuncName: funcDecl.Name.Name,
|
FuncName: funcDecl.Name.Name,
|
||||||
})
|
})
|
||||||
break
|
break
|
||||||
|
|
@ -260,51 +196,70 @@ func findPublicFuncsReturningHPage(dir string) ([]Page, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildGetPartialFromContext(builder *CodeBuilder, partials []Partial) {
|
func buildGetPartialFromContext(builder *CodeBuilder, partials []Partial) {
|
||||||
moduleName := GetModuleName()
|
fName := "GetPartialFromContext"
|
||||||
|
|
||||||
var routerHandlerMethod = func(path string, caller string) string {
|
body := `
|
||||||
return fmt.Sprintf(`
|
path := r.URL.Path
|
||||||
router.Handle("%s", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
`
|
||||||
cc := r.Context().Value(h.RequestContextKey).(*h.RequestContext)
|
|
||||||
partial := %s(cc)
|
if len(partials) == 0 {
|
||||||
|
body = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
moduleName := GetModuleName()
|
||||||
|
for _, f := range partials {
|
||||||
|
if f.FuncName == fName {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
caller := fmt.Sprintf("%s.%s", f.Package, f.FuncName)
|
||||||
|
path := fmt.Sprintf("/%s/%s.%s", moduleName, f.Import, f.FuncName)
|
||||||
|
|
||||||
|
body += fmt.Sprintf(`
|
||||||
|
if path == "%s" || path == "%s" {
|
||||||
|
cc := r.Context().Value(h.RequestContextKey).(*h.RequestContext)
|
||||||
|
return %s(cc)
|
||||||
|
}
|
||||||
|
`, f.FuncName, path, caller)
|
||||||
|
}
|
||||||
|
|
||||||
|
body += "return nil"
|
||||||
|
|
||||||
|
f := Function{
|
||||||
|
Name: fName,
|
||||||
|
Parameters: []NameType{
|
||||||
|
{Name: "r", Type: "*http.Request"},
|
||||||
|
},
|
||||||
|
Return: []ReturnType{
|
||||||
|
{Type: "*h.Partial"},
|
||||||
|
},
|
||||||
|
Body: body,
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.Append(builder.BuildFunction(f))
|
||||||
|
|
||||||
|
registerFunction := fmt.Sprintf(`
|
||||||
|
func RegisterPartials(router *chi.Mux) {
|
||||||
|
router.Handle("/%s/partials*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
partial := GetPartialFromContext(r)
|
||||||
if partial == nil {
|
if partial == nil {
|
||||||
w.WriteHeader(404)
|
w.WriteHeader(404)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.PartialView(w, partial)
|
h.PartialView(w, partial)
|
||||||
}))`, path, caller)
|
}))
|
||||||
}
|
|
||||||
|
|
||||||
handlerMethods := make([]string, 0)
|
|
||||||
|
|
||||||
for _, f := range partials {
|
|
||||||
caller := fmt.Sprintf("%s.%s", f.Package, f.FuncName)
|
|
||||||
path := fmt.Sprintf("/%s/%s.%s", moduleName, f.Import, f.FuncName)
|
|
||||||
handlerMethods = append(handlerMethods, routerHandlerMethod(path, caller))
|
|
||||||
}
|
|
||||||
|
|
||||||
registerFunction := fmt.Sprintf(`
|
|
||||||
func RegisterPartials(router *chi.Mux) {
|
|
||||||
%s
|
|
||||||
}
|
}
|
||||||
`, strings.Join(handlerMethods, "\n"))
|
`, moduleName)
|
||||||
|
|
||||||
builder.AppendLine(registerFunction)
|
builder.AppendLine(registerFunction)
|
||||||
}
|
}
|
||||||
|
|
||||||
func writePartialsFile() {
|
func writePartialsFile() {
|
||||||
config := dirutil.GetConfig()
|
|
||||||
|
|
||||||
cwd := process.GetWorkingDir()
|
cwd := process.GetWorkingDir()
|
||||||
partialPath := filepath.Join(cwd)
|
partialPath := filepath.Join(cwd, "partials")
|
||||||
partials, err := findPublicFuncsReturningHPartial(partialPath, func(partial Partial) bool {
|
partials, err := findPublicFuncsReturningHPartial(partialPath, func(partial Partial) bool {
|
||||||
return partial.FuncName != "GetPartialFromContext"
|
return partial.FuncName != "GetPartialFromContext"
|
||||||
})
|
})
|
||||||
|
|
||||||
partials = h.Filter(partials, func(partial Partial) bool {
|
|
||||||
return !dirutil.IsGlobExclude(partial.Path, config.AutomaticPartialRoutingIgnore)
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return
|
return
|
||||||
|
|
@ -313,13 +268,10 @@ func writePartialsFile() {
|
||||||
builder := NewCodeBuilder(nil)
|
builder := NewCodeBuilder(nil)
|
||||||
builder.AppendLine(GeneratedFileLine)
|
builder.AppendLine(GeneratedFileLine)
|
||||||
builder.AppendLine(PackageName)
|
builder.AppendLine(PackageName)
|
||||||
|
builder.AddImport(ModuleName)
|
||||||
|
builder.AddImport(HttpModuleName)
|
||||||
builder.AddImport(ChiModuleName)
|
builder.AddImport(ChiModuleName)
|
||||||
|
|
||||||
if len(partials) > 0 {
|
|
||||||
builder.AddImport(ModuleName)
|
|
||||||
builder.AddImport(HttpModuleName)
|
|
||||||
}
|
|
||||||
|
|
||||||
moduleName := GetModuleName()
|
moduleName := GetModuleName()
|
||||||
for _, partial := range partials {
|
for _, partial := range partials {
|
||||||
builder.AddImport(fmt.Sprintf(`%s/%s`, moduleName, partial.Import))
|
builder.AddImport(fmt.Sprintf(`%s/%s`, moduleName, partial.Import))
|
||||||
|
|
@ -365,7 +317,6 @@ func formatRoute(path string) string {
|
||||||
}
|
}
|
||||||
|
|
||||||
func writePagesFile() {
|
func writePagesFile() {
|
||||||
config := dirutil.GetConfig()
|
|
||||||
|
|
||||||
builder := NewCodeBuilder(nil)
|
builder := NewCodeBuilder(nil)
|
||||||
builder.AppendLine(GeneratedFileLine)
|
builder.AppendLine(GeneratedFileLine)
|
||||||
|
|
@ -375,10 +326,6 @@ func writePagesFile() {
|
||||||
|
|
||||||
pages, _ := findPublicFuncsReturningHPage("pages")
|
pages, _ := findPublicFuncsReturningHPage("pages")
|
||||||
|
|
||||||
pages = h.Filter(pages, func(page Page) bool {
|
|
||||||
return !dirutil.IsGlobExclude(page.Path, config.AutomaticPageRoutingIgnore)
|
|
||||||
})
|
|
||||||
|
|
||||||
if len(pages) > 0 {
|
if len(pages) > 0 {
|
||||||
builder.AddImport(ModuleName)
|
builder.AddImport(ModuleName)
|
||||||
}
|
}
|
||||||
|
|
@ -424,96 +371,9 @@ func writePagesFile() {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeAssetsFile() {
|
|
||||||
cwd := process.GetWorkingDir()
|
|
||||||
config := dirutil.GetConfig()
|
|
||||||
|
|
||||||
slog.Debug("writing assets file", slog.String("cwd", cwd), slog.String("config", config.PublicAssetPath))
|
|
||||||
|
|
||||||
distAssets := filepath.Join(cwd, "assets", "dist")
|
|
||||||
hasAssets := false
|
|
||||||
|
|
||||||
builder := strings.Builder{}
|
|
||||||
|
|
||||||
builder.WriteString(`package assets`)
|
|
||||||
builder.WriteString("\n")
|
|
||||||
|
|
||||||
filepath.WalkDir(distAssets, func(path string, d fs.DirEntry, err error) error {
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if d.IsDir() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.HasPrefix(d.Name(), ".") {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
path = strings.ReplaceAll(path, distAssets, "")
|
|
||||||
httpUrl := normalizePath(fmt.Sprintf("%s%s", config.PublicAssetPath, path))
|
|
||||||
|
|
||||||
path = normalizePath(path)
|
|
||||||
path = strings.ReplaceAll(path, "/", "_")
|
|
||||||
path = strings.ReplaceAll(path, "//", "_")
|
|
||||||
|
|
||||||
name := strings.ReplaceAll(path, ".", "_")
|
|
||||||
name = strings.ReplaceAll(name, "-", "_")
|
|
||||||
|
|
||||||
name = toPascaleCase(name)
|
|
||||||
|
|
||||||
if isValidGoVariableName(name) {
|
|
||||||
builder.WriteString(fmt.Sprintf(`const %s = "%s"`, name, httpUrl))
|
|
||||||
builder.WriteString("\n")
|
|
||||||
hasAssets = true
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
builder.WriteString("\n")
|
|
||||||
|
|
||||||
str := builder.String()
|
|
||||||
|
|
||||||
if hasAssets {
|
|
||||||
WriteFile(filepath.Join(GeneratedDirName, "assets", "assets-generated.go"), func(content *ast.File) string {
|
|
||||||
return str
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func HasModuleFile(path string) bool {
|
|
||||||
_, err := os.Stat(path)
|
|
||||||
return !os.IsNotExist(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func CheckPagesDirectory(path string) error {
|
|
||||||
pagesPath := filepath.Join(path, "pages")
|
|
||||||
_, err := os.Stat(pagesPath)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("The directory pages does not exist.")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetModuleName() string {
|
func GetModuleName() string {
|
||||||
wd := process.GetWorkingDir()
|
wd := process.GetWorkingDir()
|
||||||
modPath := filepath.Join(wd, "go.mod")
|
modPath := filepath.Join(wd, "go.mod")
|
||||||
|
|
||||||
if HasModuleFile(modPath) == false {
|
|
||||||
fmt.Fprintf(os.Stderr, "Module not found: go.mod file does not exist.")
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
checkDir := CheckPagesDirectory(wd)
|
|
||||||
if checkDir != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, checkDir.Error())
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
goModBytes, err := os.ReadFile(modPath)
|
goModBytes, err := os.ReadFile(modPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "error reading go.mod: %v\n", err)
|
fmt.Fprintf(os.Stderr, "error reading go.mod: %v\n", err)
|
||||||
|
|
@ -532,7 +392,6 @@ func GenAst(flags ...process.RunFlag) error {
|
||||||
}
|
}
|
||||||
writePartialsFile()
|
writePartialsFile()
|
||||||
writePagesFile()
|
writePagesFile()
|
||||||
writeAssetsFile()
|
|
||||||
|
|
||||||
WriteFile("__htmgo/setup-generated.go", func(content *ast.File) string {
|
WriteFile("__htmgo/setup-generated.go", func(content *ast.File) string {
|
||||||
|
|
||||||
|
|
|
||||||
82
cli/htmgo/tasks/astgen/map.go
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
package astgen
|
||||||
|
|
||||||
|
// OrderedMap is a generic data structure that maintains the order of keys.
|
||||||
|
type OrderedMap[K comparable, V any] struct {
|
||||||
|
keys []K
|
||||||
|
values map[K]V
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entries returns the key-value pairs in the order they were added.
|
||||||
|
func (om *OrderedMap[K, V]) Entries() []struct {
|
||||||
|
Key K
|
||||||
|
Value V
|
||||||
|
} {
|
||||||
|
entries := make([]struct {
|
||||||
|
Key K
|
||||||
|
Value V
|
||||||
|
}, len(om.keys))
|
||||||
|
for i, key := range om.keys {
|
||||||
|
entries[i] = struct {
|
||||||
|
Key K
|
||||||
|
Value V
|
||||||
|
}{
|
||||||
|
Key: key,
|
||||||
|
Value: om.values[key],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return entries
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOrderedMap creates a new OrderedMap.
|
||||||
|
func NewOrderedMap[K comparable, V any]() *OrderedMap[K, V] {
|
||||||
|
return &OrderedMap[K, V]{
|
||||||
|
keys: []K{},
|
||||||
|
values: make(map[K]V),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set adds or updates a key-value pair in the OrderedMap.
|
||||||
|
func (om *OrderedMap[K, V]) Set(key K, value V) {
|
||||||
|
// Check if the key already exists
|
||||||
|
if _, exists := om.values[key]; !exists {
|
||||||
|
om.keys = append(om.keys, key) // Append key to the keys slice if it's a new key
|
||||||
|
}
|
||||||
|
om.values[key] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get retrieves a value by key.
|
||||||
|
func (om *OrderedMap[K, V]) Get(key K) (V, bool) {
|
||||||
|
value, exists := om.values[key]
|
||||||
|
return value, exists
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keys returns the keys in the order they were added.
|
||||||
|
func (om *OrderedMap[K, V]) Keys() []K {
|
||||||
|
return om.keys
|
||||||
|
}
|
||||||
|
|
||||||
|
// Values returns the values in the order of their keys.
|
||||||
|
func (om *OrderedMap[K, V]) Values() []V {
|
||||||
|
values := make([]V, len(om.keys))
|
||||||
|
for i, key := range om.keys {
|
||||||
|
values[i] = om.values[key]
|
||||||
|
}
|
||||||
|
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete removes a key-value pair from the OrderedMap.
|
||||||
|
func (om *OrderedMap[K, V]) Delete(key K) {
|
||||||
|
if _, exists := om.values[key]; exists {
|
||||||
|
// Remove the key from the map
|
||||||
|
delete(om.values, key)
|
||||||
|
|
||||||
|
// Remove the key from the keys slice
|
||||||
|
for i, k := range om.keys {
|
||||||
|
if k == key {
|
||||||
|
om.keys = append(om.keys[:i], om.keys[i+1:]...)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
/assets/dist
|
|
||||||
tmp
|
|
||||||
node_modules
|
|
||||||
.idea
|
|
||||||
__htmgo
|
|
||||||
dist
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
//go:build !prod
|
|
||||||
// +build !prod
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"astgen-project-sample/internal/embedded"
|
|
||||||
"io/fs"
|
|
||||||
)
|
|
||||||
|
|
||||||
func GetStaticAssets() fs.FS {
|
|
||||||
return embedded.NewOsFs()
|
|
||||||
}
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
//go:build prod
|
|
||||||
// +build prod
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"embed"
|
|
||||||
"io/fs"
|
|
||||||
)
|
|
||||||
|
|
||||||
//go:embed assets/dist/*
|
|
||||||
var staticAssets embed.FS
|
|
||||||
|
|
||||||
func GetStaticAssets() fs.FS {
|
|
||||||
return staticAssets
|
|
||||||
}
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
module astgen-project-sample
|
|
||||||
|
|
||||||
go 1.23.0
|
|
||||||
|
|
||||||
require github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b
|
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/go-chi/chi/v5 v5.1.0 // indirect
|
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
|
||||||
)
|
|
||||||
|
|
@ -1,18 +0,0 @@
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
|
||||||
github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
|
|
||||||
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
|
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b h1:m+xI+HBEQdie/Rs+mYI0HTFTMlYQSCv0l/siPDoywA4=
|
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b/go.mod h1:NGGzWVXWksrQJ9kV9SGa/A1F1Bjsgc08cN7ZVb98RqY=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
|
||||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
|
||||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
|
||||||
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
|
|
||||||
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
# htmgo configuration
|
|
||||||
|
|
||||||
# if tailwindcss is enabled, htmgo will automatically compile your tailwind and output it to assets/dist
|
|
||||||
tailwind: true
|
|
||||||
|
|
||||||
# which directories to ignore when watching for changes, supports glob patterns through https://github.com/bmatcuk/doublestar
|
|
||||||
watch_ignore: [".git", "node_modules", "dist/*"]
|
|
||||||
|
|
||||||
# files to watch for changes, supports glob patterns through https://github.com/bmatcuk/doublestar
|
|
||||||
watch_files: ["**/*.go", "**/*.css", "**/*.md"]
|
|
||||||
|
|
||||||
# files or directories to ignore when automatically registering routes for pages
|
|
||||||
# supports glob patterns through https://github.com/bmatcuk/doublestar
|
|
||||||
automatic_page_routing_ignore: ["root.go"]
|
|
||||||
|
|
||||||
# files or directories to ignore when automatically registering routes for partials
|
|
||||||
# supports glob patterns through https://github.com/bmatcuk/doublestar
|
|
||||||
automatic_partial_routing_ignore: []
|
|
||||||
|
|
||||||
# url path of where the public assets are located
|
|
||||||
public_asset_path: "/public"
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
package embedded
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io/fs"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
type OsFs struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
func (receiver OsFs) Open(name string) (fs.File, error) {
|
|
||||||
return os.Open(name)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewOsFs() OsFs {
|
|
||||||
return OsFs{}
|
|
||||||
}
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"astgen-project-sample/__htmgo"
|
|
||||||
"fmt"
|
|
||||||
"github.com/maddalax/htmgo/framework/config"
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
"github.com/maddalax/htmgo/framework/service"
|
|
||||||
"io/fs"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
locator := service.NewLocator()
|
|
||||||
cfg := config.Get()
|
|
||||||
|
|
||||||
h.Start(h.AppOpts{
|
|
||||||
ServiceLocator: locator,
|
|
||||||
LiveReload: true,
|
|
||||||
Register: func(app *h.App) {
|
|
||||||
sub, err := fs.Sub(GetStaticAssets(), "assets/dist")
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
http.FileServerFS(sub)
|
|
||||||
|
|
||||||
// change this in htmgo.yml (public_asset_path)
|
|
||||||
app.Router.Handle(fmt.Sprintf("%s/*", cfg.PublicAssetPath),
|
|
||||||
http.StripPrefix(cfg.PublicAssetPath, http.FileServerFS(sub)))
|
|
||||||
|
|
||||||
__htmgo.Register(app.Router)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
package pages
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
)
|
|
||||||
|
|
||||||
func IndexPage(ctx *h.RequestContext) *h.Page {
|
|
||||||
return RootPage(
|
|
||||||
h.Div(
|
|
||||||
h.Class("flex flex-col gap-4 items-center pt-24 min-h-screen bg-neutral-100"),
|
|
||||||
h.H3(
|
|
||||||
h.Id("intro-text"),
|
|
||||||
h.Text("hello htmgo"),
|
|
||||||
h.Class("text-5xl"),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("mt-3"),
|
|
||||||
),
|
|
||||||
h.Div(),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPartial(ctx *h.RequestContext) *h.Partial {
|
|
||||||
return h.NewPartial(
|
|
||||||
h.Div(
|
|
||||||
h.Text("Hello World"),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
package pages
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
)
|
|
||||||
|
|
||||||
func RootPage(children ...h.Ren) *h.Page {
|
|
||||||
title := "htmgo template"
|
|
||||||
description := "an example of the htmgo template"
|
|
||||||
author := "htmgo"
|
|
||||||
url := "https://htmgo.dev"
|
|
||||||
|
|
||||||
return h.NewPage(
|
|
||||||
h.Html(
|
|
||||||
h.HxExtensions(
|
|
||||||
h.BaseExtensions(),
|
|
||||||
),
|
|
||||||
h.Head(
|
|
||||||
h.Title(
|
|
||||||
h.Text(title),
|
|
||||||
),
|
|
||||||
h.Meta("viewport", "width=device-width, initial-scale=1"),
|
|
||||||
h.Meta("title", title),
|
|
||||||
h.Meta("charset", "utf-8"),
|
|
||||||
h.Meta("author", author),
|
|
||||||
h.Meta("description", description),
|
|
||||||
h.Meta("og:title", title),
|
|
||||||
h.Meta("og:url", url),
|
|
||||||
h.Link("canonical", url),
|
|
||||||
h.Meta("og:description", description),
|
|
||||||
),
|
|
||||||
h.Body(
|
|
||||||
h.Div(
|
|
||||||
h.Class("flex flex-col gap-2 bg-white h-full"),
|
|
||||||
h.Fragment(children...),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,18 +0,0 @@
|
||||||
package partials
|
|
||||||
|
|
||||||
import "github.com/maddalax/htmgo/framework/h"
|
|
||||||
|
|
||||||
func CountersPartial(ctx *h.RequestContext) *h.Partial {
|
|
||||||
return h.NewPartial(
|
|
||||||
h.Div(
|
|
||||||
h.Text("my counter"),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func SwapFormError(ctx *h.RequestContext, error string) *h.Partial {
|
|
||||||
return h.SwapPartial(
|
|
||||||
ctx,
|
|
||||||
h.Div(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,66 +0,0 @@
|
||||||
package astgen
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/internal/dirutil"
|
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/process"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestAstGen(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
workingDir, err := filepath.Abs("./project-sample")
|
|
||||||
|
|
||||||
assert.NoError(t, err)
|
|
||||||
process.SetWorkingDir(workingDir)
|
|
||||||
assert.NoError(t, os.Chdir(workingDir))
|
|
||||||
|
|
||||||
err = dirutil.DeleteDir(filepath.Join(process.GetWorkingDir(), "__htmgo"))
|
|
||||||
assert.NoError(t, err)
|
|
||||||
err = process.Run(process.NewRawCommand("", "go build ."))
|
|
||||||
assert.Error(t, err)
|
|
||||||
err = GenAst()
|
|
||||||
assert.NoError(t, err)
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
// project was buildable after astgen, confirmed working
|
|
||||||
err = process.Run(process.NewRawCommand("server", "go run ."))
|
|
||||||
assert.NoError(t, err)
|
|
||||||
}()
|
|
||||||
|
|
||||||
time.Sleep(time.Second * 1)
|
|
||||||
|
|
||||||
urls := []string{
|
|
||||||
"/astgen-project-sample/partials.CountersPartial",
|
|
||||||
"/",
|
|
||||||
"/astgen-project-sample/pages.TestPartial",
|
|
||||||
}
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
serverProcess := process.GetProcessByName("server")
|
|
||||||
assert.NotNil(t, serverProcess)
|
|
||||||
process.KillProcess(*serverProcess)
|
|
||||||
}()
|
|
||||||
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
|
|
||||||
for _, url := range urls {
|
|
||||||
wg.Add(1)
|
|
||||||
go func() {
|
|
||||||
defer wg.Done()
|
|
||||||
// ensure we can get a 200 response on the partials
|
|
||||||
resp, e := http.Get(fmt.Sprintf("http://localhost:3000%s", url))
|
|
||||||
assert.NoError(t, e)
|
|
||||||
assert.Equal(t, http.StatusOK, resp.StatusCode, fmt.Sprintf("%s was not a 200 response", url))
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
}
|
|
||||||
|
|
@ -7,3 +7,16 @@ import (
|
||||||
func PanicF(format string, args ...interface{}) {
|
func PanicF(format string, args ...interface{}) {
|
||||||
panic(fmt.Sprintf(format, args...))
|
panic(fmt.Sprintf(format, args...))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Unique[T any](slice []T, key func(item T) string) []T {
|
||||||
|
var result []T
|
||||||
|
seen := make(map[string]bool)
|
||||||
|
for _, v := range slice {
|
||||||
|
k := key(v)
|
||||||
|
if _, ok := seen[k]; !ok {
|
||||||
|
seen[k] = true
|
||||||
|
result = append(result, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -92,7 +92,7 @@ func CopyAssets() {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if dirutil.GetConfig().Tailwind && !dirutil.HasFileFromRoot("tailwind.config.js") {
|
if !dirutil.HasFileFromRoot("tailwind.config.js") {
|
||||||
err = dirutil.CopyFile(
|
err = dirutil.CopyFile(
|
||||||
filepath.Join(assetCssDir, "tailwind.config.js"),
|
filepath.Join(assetCssDir, "tailwind.config.js"),
|
||||||
filepath.Join(process.GetWorkingDir(), "tailwind.config.js"),
|
filepath.Join(process.GetWorkingDir(), "tailwind.config.js"),
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func IsTailwindEnabled() bool {
|
func IsTailwindEnabled() bool {
|
||||||
return dirutil.GetConfig().Tailwind && dirutil.HasFileFromRoot("tailwind.config.js")
|
return dirutil.HasFileFromRoot("tailwind.config.js")
|
||||||
}
|
}
|
||||||
|
|
||||||
func Setup() bool {
|
func Setup() bool {
|
||||||
|
|
@ -78,7 +78,7 @@ func downloadTailwindCli() {
|
||||||
log.Fatal(fmt.Sprintf("Unsupported OS/ARCH: %s/%s", os, arch))
|
log.Fatal(fmt.Sprintf("Unsupported OS/ARCH: %s/%s", os, arch))
|
||||||
}
|
}
|
||||||
fileName := fmt.Sprintf(`tailwindcss-%s`, distro)
|
fileName := fmt.Sprintf(`tailwindcss-%s`, distro)
|
||||||
url := fmt.Sprintf(`https://github.com/tailwindlabs/tailwindcss/releases/download/v3.4.16/%s`, fileName)
|
url := fmt.Sprintf(`https://github.com/tailwindlabs/tailwindcss/releases/latest/download/%s`, fileName)
|
||||||
|
|
||||||
cmd := fmt.Sprintf(`curl -LO %s`, url)
|
cmd := fmt.Sprintf(`curl -LO %s`, url)
|
||||||
process.Run(process.NewRawCommand("tailwind-cli-download", cmd, process.ExitOnError))
|
process.Run(process.NewRawCommand("tailwind-cli-download", cmd, process.ExitOnError))
|
||||||
|
|
|
||||||
|
|
@ -1,50 +0,0 @@
|
||||||
package formatter
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/maddalax/htmgo/tools/html-to-htmgo/htmltogo"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func FormatDir(dir string) {
|
|
||||||
files, err := os.ReadDir(dir)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("error reading dir: %s\n", err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, file := range files {
|
|
||||||
if file.IsDir() {
|
|
||||||
FormatDir(filepath.Join(dir, file.Name()))
|
|
||||||
} else {
|
|
||||||
FormatFile(filepath.Join(dir, file.Name()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func FormatFile(file string) {
|
|
||||||
if !strings.HasSuffix(file, ".go") {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Printf("formatting file: %s\n", file)
|
|
||||||
|
|
||||||
source, err := os.ReadFile(file)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("error reading file: %s\n", err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
str := string(source)
|
|
||||||
|
|
||||||
if !strings.Contains(str, "github.com/maddalax/htmgo/framework/h") {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
parsed := htmltogo.Indent(str)
|
|
||||||
|
|
||||||
os.WriteFile(file, []byte(parsed), 0644)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
@ -12,10 +12,7 @@ func KillProcess(process CmdWithFlags) error {
|
||||||
if process.Cmd == nil || process.Cmd.Process == nil {
|
if process.Cmd == nil || process.Cmd.Process == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
err := exec.Command("taskkill", "/F", "/T", "/PID", strconv.Itoa(process.Cmd.Process.Pid)).Run()
|
Run(NewRawCommand("killprocess", fmt.Sprintf("taskkill /F /T /PID %s", strconv.Itoa(process.Cmd.Process.Pid))))
|
||||||
if err != nil {
|
|
||||||
fmt.Println(err)
|
|
||||||
}
|
|
||||||
time.Sleep(time.Millisecond * 50)
|
time.Sleep(time.Millisecond * 50)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -115,7 +115,7 @@ func OnShutdown() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// give it a second
|
// give it a second
|
||||||
time.Sleep(time.Second * 1)
|
time.Sleep(time.Second * 2)
|
||||||
// force kill
|
// force kill
|
||||||
KillAll()
|
KillAll()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,23 +9,12 @@ import (
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
func MakeBuildable() {
|
|
||||||
copyassets.CopyAssets()
|
|
||||||
css.GenerateCss(process.ExitOnError)
|
|
||||||
astgen.GenAst(process.ExitOnError)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Build() {
|
func Build() {
|
||||||
MakeBuildable()
|
copyassets.CopyAssets()
|
||||||
|
astgen.GenAst(process.ExitOnError)
|
||||||
|
css.GenerateCss(process.ExitOnError)
|
||||||
|
|
||||||
_ = os.RemoveAll("./dist")
|
process.RunOrExit(process.NewRawCommand("", "mkdir -p ./dist"))
|
||||||
|
|
||||||
err := os.Mkdir("./dist", 0755)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error creating dist directory", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
if os.Getenv("SKIP_GO_BUILD") != "1" {
|
if os.Getenv("SKIP_GO_BUILD") != "1" {
|
||||||
process.RunOrExit(process.NewRawCommand("", fmt.Sprintf("go build -tags prod -o ./dist")))
|
process.RunOrExit(process.NewRawCommand("", fmt.Sprintf("go build -tags prod -o ./dist")))
|
||||||
|
|
|
||||||
|
|
@ -1,42 +1,7 @@
|
||||||
package run
|
package run
|
||||||
|
|
||||||
import (
|
import "github.com/maddalax/htmgo/cli/htmgo/tasks/process"
|
||||||
"fmt"
|
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/process"
|
|
||||||
"io/fs"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Server(flags ...process.RunFlag) error {
|
func Server(flags ...process.RunFlag) error {
|
||||||
buildDir := "./__htmgo/temp-build"
|
return process.Run(process.NewRawCommand("run-server", "go run .", flags...))
|
||||||
_ = os.RemoveAll(buildDir)
|
|
||||||
err := os.Mkdir(buildDir, 0755)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
process.RunOrExit(process.NewRawCommand("", fmt.Sprintf("go build -o %s", buildDir)))
|
|
||||||
|
|
||||||
binaryPath := ""
|
|
||||||
|
|
||||||
// find the binary that was built
|
|
||||||
err = filepath.WalkDir(buildDir, func(path string, d fs.DirEntry, err error) error {
|
|
||||||
if d.IsDir() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
binaryPath = path
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if binaryPath == "" {
|
|
||||||
return fmt.Errorf("could not find the binary")
|
|
||||||
}
|
|
||||||
|
|
||||||
return process.Run(process.NewRawCommand("run-server", fmt.Sprintf("./%s", binaryPath), flags...))
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,19 @@
|
||||||
package run
|
package run
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/astgen"
|
||||||
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/copyassets"
|
||||||
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/css"
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/process"
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/process"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Setup() {
|
func Setup() {
|
||||||
process.RunOrExit(process.NewRawCommand("", "go mod download"))
|
process.RunOrExit(process.NewRawCommand("", "go mod download"))
|
||||||
process.RunOrExit(process.NewRawCommand("", "go mod tidy"))
|
process.RunOrExit(process.NewRawCommand("", "go mod tidy"))
|
||||||
MakeBuildable()
|
|
||||||
|
copyassets.CopyAssets()
|
||||||
|
astgen.GenAst(process.ExitOnError)
|
||||||
|
css.GenerateCss(process.ExitOnError)
|
||||||
|
|
||||||
EntGenerate()
|
EntGenerate()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,7 @@ func ReplaceTextInFile(file string, text string, replacement string) error {
|
||||||
|
|
||||||
func ReplaceTextInDirRecursive(dir string, text string, replacement string, filter func(file string) bool) error {
|
func ReplaceTextInDirRecursive(dir string, text string, replacement string, filter func(file string) bool) error {
|
||||||
return filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
|
return filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
|
||||||
if filter(filepath.Base(path)) {
|
if filter(path) {
|
||||||
_ = ReplaceTextInFile(path, text, replacement)
|
_ = ReplaceTextInFile(path, text, replacement)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,6 @@ import (
|
||||||
"github.com/fsnotify/fsnotify"
|
"github.com/fsnotify/fsnotify"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/internal"
|
"github.com/maddalax/htmgo/cli/htmgo/internal"
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/internal/dirutil"
|
|
||||||
"github.com/maddalax/htmgo/cli/htmgo/tasks/module"
|
"github.com/maddalax/htmgo/cli/htmgo/tasks/module"
|
||||||
"log"
|
"log"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
|
@ -14,10 +13,11 @@ import (
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var ignoredDirs = []string{".git", ".idea", "node_modules", "vendor"}
|
||||||
|
|
||||||
func startWatcher(cb func(version string, file []*fsnotify.Event)) {
|
func startWatcher(cb func(version string, file []*fsnotify.Event)) {
|
||||||
events := make([]*fsnotify.Event, 0)
|
events := make([]*fsnotify.Event, 0)
|
||||||
debouncer := internal.NewDebouncer(500 * time.Millisecond)
|
debouncer := internal.NewDebouncer(500 * time.Millisecond)
|
||||||
config := dirutil.GetConfig()
|
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
if r := recover(); r != nil {
|
if r := recover(); r != nil {
|
||||||
|
|
@ -35,22 +35,22 @@ func startWatcher(cb func(version string, file []*fsnotify.Event)) {
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case event, ok := <-watcher.Events:
|
case event, ok := <-watcher.Events:
|
||||||
|
slog.Debug("event:", slog.String("name", event.Name), slog.String("op", event.Op.String()))
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if event.Has(fsnotify.Remove) {
|
if event.Has(fsnotify.Remove) {
|
||||||
if dirutil.IsGlobMatch(event.Name, config.WatchFiles, config.WatchIgnore) {
|
err = watcher.Remove(event.Name)
|
||||||
watcher.Remove(event.Name)
|
if err != nil {
|
||||||
continue
|
slog.Error("Error removing directory from watcher:", slog.String("path", event.Name), slog.String("error", err.Error()))
|
||||||
|
} else {
|
||||||
|
slog.Debug("Stopped watching directory:", slog.String("path", event.Name))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if event.Has(fsnotify.Create) {
|
if event.Has(fsnotify.Create) {
|
||||||
if dirutil.IsGlobMatch(event.Name, config.WatchFiles, config.WatchIgnore) {
|
|
||||||
watcher.Add(event.Name)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
info, err := os.Stat(event.Name)
|
info, err := os.Stat(event.Name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Error getting file info:", slog.String("path", event.Name), slog.String("error", err.Error()))
|
slog.Error("Error getting file info:", slog.String("path", event.Name), slog.String("error", err.Error()))
|
||||||
|
|
@ -67,9 +67,6 @@ func startWatcher(cb func(version string, file []*fsnotify.Event)) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if event.Has(fsnotify.Write) || event.Has(fsnotify.Remove) || event.Has(fsnotify.Rename) {
|
if event.Has(fsnotify.Write) || event.Has(fsnotify.Remove) || event.Has(fsnotify.Rename) {
|
||||||
if !dirutil.IsGlobMatch(event.Name, config.WatchFiles, config.WatchIgnore) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
events = append(events, &event)
|
events = append(events, &event)
|
||||||
debouncer.Do(func() {
|
debouncer.Do(func() {
|
||||||
seen := make(map[string]bool)
|
seen := make(map[string]bool)
|
||||||
|
|
@ -84,12 +81,11 @@ func startWatcher(cb func(version string, file []*fsnotify.Event)) {
|
||||||
events = make([]*fsnotify.Event, 0)
|
events = make([]*fsnotify.Event, 0)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
case err, ok := <-watcher.Errors:
|
case err, ok := <-watcher.Errors:
|
||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
slog.Error("error:", slog.String("error", err.Error()))
|
slog.Error("error:", err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
@ -110,22 +106,22 @@ func startWatcher(cb func(version string, file []*fsnotify.Event)) {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// Ignore directories in the ignoredDirs list
|
// Ignore directories in the ignoredDirs list
|
||||||
if dirutil.IsGlobExclude(path, config.WatchIgnore) {
|
for _, ignoredDir := range ignoredDirs {
|
||||||
return filepath.SkipDir
|
if ignoredDir == info.Name() {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only watch directories
|
// Only watch directories
|
||||||
if info.IsDir() {
|
if info.IsDir() {
|
||||||
err = watcher.Add(path)
|
err = watcher.Add(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Error adding directory to watcher:", slog.String("error", err.Error()))
|
slog.Error("Error adding directory to watcher:", err)
|
||||||
} else {
|
} else {
|
||||||
slog.Debug("Watching directory:", slog.String("path", path))
|
slog.Debug("Watching directory:", slog.String("path", path))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,25 +11,18 @@ import (
|
||||||
func MessageRow(message *Message) *h.Element {
|
func MessageRow(message *Message) *h.Element {
|
||||||
return h.Div(
|
return h.Div(
|
||||||
h.Attribute("hx-swap-oob", "beforeend"),
|
h.Attribute("hx-swap-oob", "beforeend"),
|
||||||
h.Class("flex flex-col gap-4 w-full break-words whitespace-normal"),
|
h.Class("flex flex-col gap-4 w-full break-words whitespace-normal"), // Ensure container breaks long words
|
||||||
// Ensure container breaks long words
|
|
||||||
h.Id("messages"),
|
h.Id("messages"),
|
||||||
h.Div(
|
h.Div(
|
||||||
h.Class("flex flex-col gap-1"),
|
h.Class("flex flex-col gap-1"),
|
||||||
h.Div(
|
h.Div(
|
||||||
h.Class("flex gap-2 items-center"),
|
h.Class("flex gap-2 items-center"),
|
||||||
h.Pf(
|
h.Pf(message.UserName, h.Class("font-bold")),
|
||||||
message.UserName,
|
|
||||||
h.Class("font-bold"),
|
|
||||||
),
|
|
||||||
h.Pf(message.CreatedAt.In(time.Local).Format("01/02 03:04 PM")),
|
h.Pf(message.CreatedAt.In(time.Local).Format("01/02 03:04 PM")),
|
||||||
),
|
),
|
||||||
h.Article(
|
h.Article(
|
||||||
h.Class("break-words whitespace-normal"),
|
h.Class("break-words whitespace-normal"), // Ensure message text wraps correctly
|
||||||
// Ensure message text wraps correctly
|
h.P(h.Text(message.Message)),
|
||||||
h.P(
|
|
||||||
h.Text(message.Message),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -28,28 +28,12 @@ func Button(props ButtonProps) h.Ren {
|
||||||
text := h.Text(props.Text)
|
text := h.Text(props.Text)
|
||||||
|
|
||||||
button := h.Button(
|
button := h.Button(
|
||||||
h.If(
|
h.If(props.Id != "", h.Id(props.Id)),
|
||||||
props.Id != "",
|
h.If(props.Children != nil, h.Children(props.Children...)),
|
||||||
h.Id(props.Id),
|
|
||||||
),
|
|
||||||
h.If(
|
|
||||||
props.Children != nil,
|
|
||||||
h.Children(props.Children...),
|
|
||||||
),
|
|
||||||
h.Class("flex gap-1 items-center justify-center border p-4 rounded cursor-hover", props.Class),
|
h.Class("flex gap-1 items-center justify-center border p-4 rounded cursor-hover", props.Class),
|
||||||
h.If(
|
h.If(props.Get != "", h.Get(props.Get)),
|
||||||
props.Get != "",
|
h.If(props.Target != "", h.HxTarget(props.Target)),
|
||||||
h.Get(props.Get),
|
h.IfElse(props.Type != "", h.Type(props.Type), h.Type("button")),
|
||||||
),
|
|
||||||
h.If(
|
|
||||||
props.Target != "",
|
|
||||||
h.HxTarget(props.Target),
|
|
||||||
),
|
|
||||||
h.IfElse(
|
|
||||||
props.Type != "",
|
|
||||||
h.Type(props.Type),
|
|
||||||
h.Type("button"),
|
|
||||||
),
|
|
||||||
text,
|
text,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,9 +6,6 @@ func FormError(error string) *h.Element {
|
||||||
return h.Div(
|
return h.Div(
|
||||||
h.Id("form-error"),
|
h.Id("form-error"),
|
||||||
h.Text(error),
|
h.Text(error),
|
||||||
h.If(
|
h.If(error != "", h.Class("p-4 bg-rose-400 text-white rounded")),
|
||||||
error != "",
|
|
||||||
h.Class("p-4 bg-rose-400 text-white rounded"),
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -19,14 +19,11 @@ type InputProps struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func Input(props InputProps) *h.Element {
|
func Input(props InputProps) *h.Element {
|
||||||
validation := h.If(
|
validation := h.If(props.ValidationPath != "", h.Children(
|
||||||
props.ValidationPath != "",
|
h.Post(props.ValidationPath, hx.BlurEvent),
|
||||||
h.Children(
|
h.Attribute("hx-swap", "innerHTML transition:true"),
|
||||||
h.Post(props.ValidationPath, hx.BlurEvent),
|
h.Attribute("hx-target", "next div"),
|
||||||
h.Attribute("hx-swap", "innerHTML transition:true"),
|
))
|
||||||
h.Attribute("hx-target", "next div"),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
if props.Type == "" {
|
if props.Type == "" {
|
||||||
props.Type = "text"
|
props.Type = "text"
|
||||||
|
|
@ -35,41 +32,18 @@ func Input(props InputProps) *h.Element {
|
||||||
input := h.Input(
|
input := h.Input(
|
||||||
props.Type,
|
props.Type,
|
||||||
h.Class("border p-2 rounded focus:outline-none focus:ring focus:ring-slate-800"),
|
h.Class("border p-2 rounded focus:outline-none focus:ring focus:ring-slate-800"),
|
||||||
h.If(
|
h.If(props.Name != "", h.Name(props.Name)),
|
||||||
props.Name != "",
|
h.If(props.Children != nil, h.Children(props.Children...)),
|
||||||
h.Name(props.Name),
|
h.If(props.Required, h.Required()),
|
||||||
),
|
h.If(props.Placeholder != "", h.Placeholder(props.Placeholder)),
|
||||||
h.If(
|
h.If(props.DefaultValue != "", h.Attribute("value", props.DefaultValue)),
|
||||||
props.Children != nil,
|
|
||||||
h.Children(props.Children...),
|
|
||||||
),
|
|
||||||
h.If(
|
|
||||||
props.Required,
|
|
||||||
h.Required(),
|
|
||||||
),
|
|
||||||
h.If(
|
|
||||||
props.Placeholder != "",
|
|
||||||
h.Placeholder(props.Placeholder),
|
|
||||||
),
|
|
||||||
h.If(
|
|
||||||
props.DefaultValue != "",
|
|
||||||
h.Attribute("value", props.DefaultValue),
|
|
||||||
),
|
|
||||||
validation,
|
validation,
|
||||||
)
|
)
|
||||||
|
|
||||||
wrapped := h.Div(
|
wrapped := h.Div(
|
||||||
h.If(
|
h.If(props.Id != "", h.Id(props.Id)),
|
||||||
props.Id != "",
|
|
||||||
h.Id(props.Id),
|
|
||||||
),
|
|
||||||
h.Class("flex flex-col gap-1"),
|
h.Class("flex flex-col gap-1"),
|
||||||
h.If(
|
h.If(props.Label != "", h.Label(h.Text(props.Label))),
|
||||||
props.Label != "",
|
|
||||||
h.Label(
|
|
||||||
h.Text(props.Label),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
input,
|
input,
|
||||||
h.Div(
|
h.Div(
|
||||||
h.Id(props.Id+"-error"),
|
h.Id(props.Id+"-error"),
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ go 1.23.0
|
||||||
require (
|
require (
|
||||||
github.com/go-chi/chi/v5 v5.1.0
|
github.com/go-chi/chi/v5 v5.1.0
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b
|
github.com/maddalax/htmgo/framework v0.0.0-20241007175724-1014f6c96107
|
||||||
github.com/mattn/go-sqlite3 v1.14.23
|
github.com/mattn/go-sqlite3 v1.14.23
|
||||||
github.com/puzpuzpuz/xsync/v3 v3.4.0
|
github.com/puzpuzpuz/xsync/v3 v3.4.0
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@ github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
|
||||||
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
|
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b h1:m+xI+HBEQdie/Rs+mYI0HTFTMlYQSCv0l/siPDoywA4=
|
github.com/maddalax/htmgo/framework v0.0.0-20241007175724-1014f6c96107 h1:9dGhXM+1NefO9/FeEf5v5NsfVd3SBwh+ieXKzNvkrZ4=
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b/go.mod h1:NGGzWVXWksrQJ9kV9SGa/A1F1Bjsgc08cN7ZVb98RqY=
|
github.com/maddalax/htmgo/framework v0.0.0-20241007175724-1014f6c96107/go.mod h1:HYKI49Pb6oyY2opSJdTt145B1vWgfWIDohvlolynv80=
|
||||||
github.com/mattn/go-sqlite3 v1.14.23 h1:gbShiuAP1W5j9UOksQ06aiiqPMxYecovVGwmTxWtuw0=
|
github.com/mattn/go-sqlite3 v1.14.23 h1:gbShiuAP1W5j9UOksQ06aiiqPMxYecovVGwmTxWtuw0=
|
||||||
github.com/mattn/go-sqlite3 v1.14.23/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
github.com/mattn/go-sqlite3 v1.14.23/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
|
|
||||||
|
|
@ -17,10 +17,13 @@ func ChatRoom(ctx *h.RequestContext) *h.Page {
|
||||||
RootPage(
|
RootPage(
|
||||||
h.Div(
|
h.Div(
|
||||||
h.TriggerChildren(),
|
h.TriggerChildren(),
|
||||||
|
|
||||||
h.Attribute("sse-connect", fmt.Sprintf("/sse/chat/%s", roomId)),
|
h.Attribute("sse-connect", fmt.Sprintf("/sse/chat/%s", roomId)),
|
||||||
|
|
||||||
h.HxOnSseOpen(
|
h.HxOnSseOpen(
|
||||||
js.ConsoleLog("Connected to chat room"),
|
js.ConsoleLog("Connected to chat room"),
|
||||||
),
|
),
|
||||||
|
|
||||||
h.HxOnSseError(
|
h.HxOnSseError(
|
||||||
js.EvalJs(fmt.Sprintf(`
|
js.EvalJs(fmt.Sprintf(`
|
||||||
const reason = e.detail.event.data
|
const reason = e.detail.event.data
|
||||||
|
|
@ -35,27 +38,35 @@ func ChatRoom(ctx *h.RequestContext) *h.Page {
|
||||||
}
|
}
|
||||||
`, roomId, roomId)),
|
`, roomId, roomId)),
|
||||||
),
|
),
|
||||||
|
|
||||||
// Adjusted flex properties for responsive layout
|
// Adjusted flex properties for responsive layout
|
||||||
h.Class("flex flex-row h-screen bg-neutral-100 overflow-x-hidden"),
|
h.Class("flex flex-row h-screen bg-neutral-100 overflow-x-hidden"),
|
||||||
|
|
||||||
// Collapse Button for mobile
|
// Collapse Button for mobile
|
||||||
CollapseButton(),
|
CollapseButton(),
|
||||||
|
|
||||||
// Sidebar for connected users
|
// Sidebar for connected users
|
||||||
UserSidebar(),
|
UserSidebar(),
|
||||||
|
|
||||||
h.Div(
|
h.Div(
|
||||||
// Adjusted to fill height and width
|
// Adjusted to fill height and width
|
||||||
h.Class("flex flex-col h-full w-full bg-white p-4 overflow-hidden"),
|
h.Class("flex flex-col h-full w-full bg-white p-4 overflow-hidden"),
|
||||||
|
|
||||||
// Room name at the top, fixed
|
// Room name at the top, fixed
|
||||||
CachedRoomHeader(ctx),
|
CachedRoomHeader(ctx),
|
||||||
|
|
||||||
h.HxAfterSseMessage(
|
h.HxAfterSseMessage(
|
||||||
js.EvalJsOnSibling("#messages",
|
js.EvalJsOnSibling("#messages",
|
||||||
`element.scrollTop = element.scrollHeight;`),
|
`element.scrollTop = element.scrollHeight;`),
|
||||||
),
|
),
|
||||||
|
|
||||||
// Chat Messages
|
// Chat Messages
|
||||||
h.Div(
|
h.Div(
|
||||||
h.Id("messages"),
|
h.Id("messages"),
|
||||||
// Adjusted flex properties and removed max-width
|
// Adjusted flex properties and removed max-width
|
||||||
h.Class("flex flex-col gap-4 mb-4 overflow-auto flex-grow w-full pt-[50px]"),
|
h.Class("flex flex-col gap-4 mb-4 overflow-auto flex-grow w-full pt-[50px]"),
|
||||||
),
|
),
|
||||||
|
|
||||||
// Chat Input at the bottom
|
// Chat Input at the bottom
|
||||||
Form(),
|
Form(),
|
||||||
),
|
),
|
||||||
|
|
@ -80,10 +91,7 @@ func roomNameHeader(ctx *h.RequestContext) *h.Element {
|
||||||
}
|
}
|
||||||
return h.Div(
|
return h.Div(
|
||||||
h.Class("bg-neutral-700 text-white p-3 shadow-sm w-full fixed top-0 left-0 flex justify-center z-10"),
|
h.Class("bg-neutral-700 text-white p-3 shadow-sm w-full fixed top-0 left-0 flex justify-center z-10"),
|
||||||
h.H2F(
|
h.H2F(room.Name, h.Class("text-lg font-bold")),
|
||||||
room.Name,
|
|
||||||
h.Class("text-lg font-bold"),
|
|
||||||
),
|
|
||||||
h.Div(
|
h.Div(
|
||||||
h.Class("absolute right-5 top-3 cursor-pointer"),
|
h.Class("absolute right-5 top-3 cursor-pointer"),
|
||||||
h.Text("Share"),
|
h.Text("Share"),
|
||||||
|
|
@ -100,10 +108,7 @@ func UserSidebar() *h.Element {
|
||||||
return h.Div(
|
return h.Div(
|
||||||
h.Class("sidebar h-full pt-[67px] min-w-48 w-48 bg-neutral-200 p-4 flex-col justify-between gap-3 rounded-l-lg hidden md:flex"),
|
h.Class("sidebar h-full pt-[67px] min-w-48 w-48 bg-neutral-200 p-4 flex-col justify-between gap-3 rounded-l-lg hidden md:flex"),
|
||||||
h.Div(
|
h.Div(
|
||||||
h.H3F(
|
h.H3F("Connected Users", h.Class("text-lg font-bold")),
|
||||||
"Connected Users",
|
|
||||||
h.Class("text-lg font-bold"),
|
|
||||||
),
|
|
||||||
chat.ConnectedUsers(make([]db.User, 0), ""),
|
chat.ConnectedUsers(make([]db.User, 0), ""),
|
||||||
),
|
),
|
||||||
h.A(
|
h.A(
|
||||||
|
|
@ -116,11 +121,9 @@ func UserSidebar() *h.Element {
|
||||||
|
|
||||||
func CollapseButton() *h.Element {
|
func CollapseButton() *h.Element {
|
||||||
return h.Div(
|
return h.Div(
|
||||||
h.Class("fixed top-0 left-4 md:hidden z-50"),
|
h.Class("fixed top-0 left-4 md:hidden z-50"), // Always visible on mobile
|
||||||
// Always visible on mobile
|
|
||||||
h.Button(
|
h.Button(
|
||||||
h.Class("p-2 text-2xl bg-neutral-700 text-white rounded-md"),
|
h.Class("p-2 text-2xl bg-neutral-700 text-white rounded-md"), // Styling the button
|
||||||
// Styling the button
|
|
||||||
h.OnClick(
|
h.OnClick(
|
||||||
js.EvalJs(`
|
js.EvalJs(`
|
||||||
const sidebar = document.querySelector('.sidebar');
|
const sidebar = document.querySelector('.sidebar');
|
||||||
|
|
@ -128,16 +131,13 @@ func CollapseButton() *h.Element {
|
||||||
sidebar.classList.toggle('flex');
|
sidebar.classList.toggle('flex');
|
||||||
`),
|
`),
|
||||||
),
|
),
|
||||||
h.UnsafeRaw("☰"),
|
h.UnsafeRaw("☰"), // The icon for collapsing the sidebar
|
||||||
|
|
||||||
// The icon for collapsing the sidebar
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
func MessageInput() *h.Element {
|
func MessageInput() *h.Element {
|
||||||
return h.Input(
|
return h.Input("text",
|
||||||
"text",
|
|
||||||
h.Id("message-input"),
|
h.Id("message-input"),
|
||||||
h.Required(),
|
h.Required(),
|
||||||
h.Class("p-4 rounded-md border border-slate-200 w-full focus:outline-none focus:ring focus:ring-slate-200"),
|
h.Class("p-4 rounded-md border border-slate-200 w-full focus:outline-none focus:ring focus:ring-slate-200"),
|
||||||
|
|
|
||||||
|
|
@ -13,14 +13,12 @@ func ChatAppFirstScreen(ctx *h.RequestContext) *h.Page {
|
||||||
h.Class("flex flex-col items-center justify-center min-h-screen bg-neutral-100"),
|
h.Class("flex flex-col items-center justify-center min-h-screen bg-neutral-100"),
|
||||||
h.Div(
|
h.Div(
|
||||||
h.Class("bg-white p-8 rounded-lg shadow-lg w-full max-w-md"),
|
h.Class("bg-white p-8 rounded-lg shadow-lg w-full max-w-md"),
|
||||||
h.H2F(
|
h.H2F("htmgo chat", h.Class("text-3xl font-bold text-center mb-6")),
|
||||||
"htmgo chat",
|
|
||||||
h.Class("text-3xl font-bold text-center mb-6"),
|
|
||||||
),
|
|
||||||
h.Form(
|
h.Form(
|
||||||
h.Attribute("hx-swap", "none"),
|
h.Attribute("hx-swap", "none"),
|
||||||
h.PostPartial(partials.CreateOrJoinRoom),
|
h.PostPartial(partials.CreateOrJoinRoom),
|
||||||
h.Class("flex flex-col gap-6"),
|
h.Class("flex flex-col gap-6"),
|
||||||
|
|
||||||
// Username input at the top
|
// Username input at the top
|
||||||
components.Input(components.InputProps{
|
components.Input(components.InputProps{
|
||||||
Id: "username",
|
Id: "username",
|
||||||
|
|
@ -32,9 +30,11 @@ func ChatAppFirstScreen(ctx *h.RequestContext) *h.Page {
|
||||||
h.MaxLength(15),
|
h.MaxLength(15),
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
|
||||||
// Single box for Create or Join a Chat Room
|
// Single box for Create or Join a Chat Room
|
||||||
h.Div(
|
h.Div(
|
||||||
h.Class("p-4 border border-gray-300 rounded-md flex flex-col gap-6"),
|
h.Class("p-4 border border-gray-300 rounded-md flex flex-col gap-6"),
|
||||||
|
|
||||||
// Create New Chat Room input
|
// Create New Chat Room input
|
||||||
components.Input(components.InputProps{
|
components.Input(components.InputProps{
|
||||||
Name: "new-chat-room",
|
Name: "new-chat-room",
|
||||||
|
|
@ -45,20 +45,15 @@ func ChatAppFirstScreen(ctx *h.RequestContext) *h.Page {
|
||||||
h.MaxLength(20),
|
h.MaxLength(20),
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
|
||||||
// OR divider
|
// OR divider
|
||||||
h.Div(
|
h.Div(
|
||||||
h.Class("flex items-center justify-center gap-4"),
|
h.Class("flex items-center justify-center gap-4"),
|
||||||
h.Div(
|
h.Div(h.Class("border-t border-gray-300 flex-grow")),
|
||||||
h.Class("border-t border-gray-300 flex-grow"),
|
h.P(h.Text("OR"), h.Class("text-gray-500")),
|
||||||
),
|
h.Div(h.Class("border-t border-gray-300 flex-grow")),
|
||||||
h.P(
|
|
||||||
h.Text("OR"),
|
|
||||||
h.Class("text-gray-500"),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("border-t border-gray-300 flex-grow"),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
|
|
||||||
// Join Chat Room input
|
// Join Chat Room input
|
||||||
components.Input(components.InputProps{
|
components.Input(components.InputProps{
|
||||||
Id: "join-chat-room",
|
Id: "join-chat-room",
|
||||||
|
|
@ -72,8 +67,10 @@ func ChatAppFirstScreen(ctx *h.RequestContext) *h.Page {
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
|
||||||
// Error message
|
// Error message
|
||||||
components.FormError(""),
|
components.FormError(""),
|
||||||
|
|
||||||
// Submit button at the bottom
|
// Submit button at the bottom
|
||||||
components.PrimaryButton(components.ButtonProps{
|
components.PrimaryButton(components.ButtonProps{
|
||||||
Type: "submit",
|
Type: "submit",
|
||||||
|
|
|
||||||
|
|
@ -50,6 +50,7 @@ func Handle() http.HandlerFunc {
|
||||||
defer manager.Disconnect(sessionId)
|
defer manager.Disconnect(sessionId)
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
|
fmt.Printf("empting channels\n")
|
||||||
for len(writer) > 0 {
|
for len(writer) > 0 {
|
||||||
<-writer
|
<-writer
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -70,14 +70,16 @@ func (manager *SocketManager) Listen(listener chan SocketEvent) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (manager *SocketManager) dispatch(event SocketEvent) {
|
func (manager *SocketManager) dispatch(event SocketEvent) {
|
||||||
|
fmt.Printf("dispatching event: %s\n", event.Type)
|
||||||
done := make(chan struct{}, 1)
|
done := make(chan struct{}, 1)
|
||||||
go func() {
|
go func() {
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-done:
|
case <-done:
|
||||||
|
fmt.Printf("dispatched event: %s\n", event.Type)
|
||||||
return
|
return
|
||||||
case <-time.After(5 * time.Second):
|
case <-time.After(5 * time.Second):
|
||||||
fmt.Printf("havent dispatched listener event after 5s, chan blocked: %s\n", event.Type)
|
fmt.Printf("havent dispatched event after 5s, chan blocked: %s\n", event.Type)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Project exclude paths
|
|
||||||
/tmp/
|
|
||||||
node_modules/
|
|
||||||
dist/
|
|
||||||
js/dist
|
|
||||||
js/node_modules
|
|
||||||
go.work
|
|
||||||
go.work.sum
|
|
||||||
.idea
|
|
||||||
!framework/assets/dist
|
|
||||||
__htmgo
|
|
||||||
6
examples/hackernews/.gitignore
vendored
|
|
@ -1,6 +0,0 @@
|
||||||
/assets/dist
|
|
||||||
tmp
|
|
||||||
node_modules
|
|
||||||
.idea
|
|
||||||
__htmgo
|
|
||||||
dist
|
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
# Stage 1: Build the Go binary
|
|
||||||
FROM golang:1.23-alpine AS builder
|
|
||||||
|
|
||||||
RUN apk update
|
|
||||||
RUN apk add git
|
|
||||||
RUN apk add curl
|
|
||||||
|
|
||||||
# Set the working directory inside the container
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
# Copy go.mod and go.sum files
|
|
||||||
COPY go.mod go.sum ./
|
|
||||||
|
|
||||||
# Download and cache the Go modules
|
|
||||||
RUN go mod download
|
|
||||||
|
|
||||||
# Copy the source code into the container
|
|
||||||
COPY . .
|
|
||||||
|
|
||||||
# Build the Go binary for Linux
|
|
||||||
RUN GOPRIVATE=github.com/maddalax GOPROXY=direct go run github.com/maddalax/htmgo/cli/htmgo@latest build
|
|
||||||
|
|
||||||
|
|
||||||
# Stage 2: Create the smallest possible image
|
|
||||||
FROM gcr.io/distroless/base-debian11
|
|
||||||
|
|
||||||
# Set the working directory inside the container
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
# Copy the Go binary from the builder stage
|
|
||||||
COPY --from=builder /app/dist .
|
|
||||||
|
|
||||||
# Expose the necessary port (replace with your server port)
|
|
||||||
EXPOSE 3000
|
|
||||||
|
|
||||||
|
|
||||||
# Command to run the binary
|
|
||||||
CMD ["./hackernews"]
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
version: '3'
|
|
||||||
|
|
||||||
tasks:
|
|
||||||
run:
|
|
||||||
cmds:
|
|
||||||
- htmgo run
|
|
||||||
silent: true
|
|
||||||
|
|
||||||
build:
|
|
||||||
cmds:
|
|
||||||
- htmgo build
|
|
||||||
|
|
||||||
docker:
|
|
||||||
cmds:
|
|
||||||
- docker build .
|
|
||||||
|
|
||||||
watch:
|
|
||||||
cmds:
|
|
||||||
- htmgo watch
|
|
||||||
silent: true
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
//go:build !prod
|
|
||||||
// +build !prod
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"hackernews/internal/embedded"
|
|
||||||
"io/fs"
|
|
||||||
)
|
|
||||||
|
|
||||||
func GetStaticAssets() fs.FS {
|
|
||||||
return embedded.NewOsFs()
|
|
||||||
}
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
@tailwind base;
|
|
||||||
@tailwind components;
|
|
||||||
@tailwind utilities;
|
|
||||||
|
|
||||||
@layer utilities {
|
|
||||||
/* Chrome, Safari and Opera */
|
|
||||||
.no-scrollbar::-webkit-scrollbar {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.no-scrollbar {
|
|
||||||
-ms-overflow-style: none; /* IE and Edge */
|
|
||||||
scrollbar-width: none; /* Firefox */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
Before Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 6.9 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 23 KiB |
|
|
@ -1,16 +0,0 @@
|
||||||
//go:build prod
|
|
||||||
// +build prod
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"embed"
|
|
||||||
"io/fs"
|
|
||||||
)
|
|
||||||
|
|
||||||
//go:embed assets/dist/*
|
|
||||||
var staticAssets embed.FS
|
|
||||||
|
|
||||||
func GetStaticAssets() fs.FS {
|
|
||||||
return staticAssets
|
|
||||||
}
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
package components
|
|
||||||
|
|
||||||
import "github.com/maddalax/htmgo/framework/h"
|
|
||||||
|
|
||||||
func Badge(text string, active bool, children ...h.Ren) *h.Element {
|
|
||||||
return h.Button(
|
|
||||||
h.Text(text),
|
|
||||||
h.ClassX("font-semibold px-3 py-1 rounded-full cursor-pointer h-[32px]", h.ClassMap{
|
|
||||||
"bg-rose-500 text-white": active,
|
|
||||||
"bg-neutral-300": !active,
|
|
||||||
}),
|
|
||||||
h.Children(children...),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
module hackernews
|
|
||||||
|
|
||||||
go 1.23.0
|
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b
|
|
||||||
github.com/microcosm-cc/bluemonday v1.0.27
|
|
||||||
)
|
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/aymerick/douceur v0.2.0 // indirect
|
|
||||||
github.com/go-chi/chi/v5 v5.1.0 // indirect
|
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
|
||||||
github.com/gorilla/css v1.0.1 // indirect
|
|
||||||
golang.org/x/net v0.29.0 // indirect
|
|
||||||
)
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
|
|
||||||
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
|
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
|
||||||
github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
|
|
||||||
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
|
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
|
||||||
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
|
|
||||||
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
|
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b h1:m+xI+HBEQdie/Rs+mYI0HTFTMlYQSCv0l/siPDoywA4=
|
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b/go.mod h1:NGGzWVXWksrQJ9kV9SGa/A1F1Bjsgc08cN7ZVb98RqY=
|
|
||||||
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
|
|
||||||
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
|
||||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
|
||||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
|
||||||
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
|
|
||||||
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
package batch
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ParallelProcess[T any, Z any](items []T, concurrency int, cb func(item T) Z) []Z {
|
|
||||||
if len(items) == 0 {
|
|
||||||
return []Z{}
|
|
||||||
}
|
|
||||||
if len(items) == 1 {
|
|
||||||
return []Z{cb(items[0])}
|
|
||||||
}
|
|
||||||
results := make([]Z, len(items))
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
sem := make(chan struct{}, concurrency)
|
|
||||||
for i, item := range items {
|
|
||||||
wg.Add(1)
|
|
||||||
sem <- struct{}{}
|
|
||||||
go func(item T) {
|
|
||||||
defer func() {
|
|
||||||
wg.Done()
|
|
||||||
<-sem
|
|
||||||
}()
|
|
||||||
results[i] = cb(item)
|
|
||||||
}(item)
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
return results
|
|
||||||
}
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
package embedded
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io/fs"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
type OsFs struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
func (receiver OsFs) Open(name string) (fs.File, error) {
|
|
||||||
return os.Open(name)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewOsFs() OsFs {
|
|
||||||
return OsFs{}
|
|
||||||
}
|
|
||||||
|
|
@ -1,115 +0,0 @@
|
||||||
package httpjson
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
client *http.Client
|
|
||||||
once sync.Once // Consider allowing configuration parameters for the singleton
|
|
||||||
)
|
|
||||||
|
|
||||||
func getClient() *http.Client {
|
|
||||||
once.Do(func() {
|
|
||||||
client = &http.Client{
|
|
||||||
Timeout: 10 * time.Second,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return client
|
|
||||||
}
|
|
||||||
|
|
||||||
func Get[T any](url string) (*T, error) {
|
|
||||||
client := getClient()
|
|
||||||
resp, err := client.Get(url)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
var result T
|
|
||||||
body, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := json.Unmarshal(body, &result); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func Post[T any](url string, data T) (*http.Response, error) {
|
|
||||||
client := getClient()
|
|
||||||
body, err := json.Marshal(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := client.Post(url, "application/json", bytes.NewBuffer(body))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
|
|
||||||
return resp, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func Patch[T any](url string, data T) error {
|
|
||||||
client := getClient()
|
|
||||||
body, err := json.Marshal(data)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
req, err := http.NewRequest(http.MethodPatch, url, bytes.NewBuffer(body))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func Delete(url string) error {
|
|
||||||
client := getClient()
|
|
||||||
req, err := http.NewRequest(http.MethodDelete, url, nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
@ -1,152 +0,0 @@
|
||||||
package news
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
"hackernews/internal/batch"
|
|
||||||
"hackernews/internal/httpjson"
|
|
||||||
"hackernews/internal/sanitize"
|
|
||||||
"hackernews/internal/timeformat"
|
|
||||||
"log/slog"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
const baseUrl = "https://hacker-news.firebaseio.com/v0/"
|
|
||||||
|
|
||||||
func url(path string, qs *h.Qs) string {
|
|
||||||
return baseUrl + path + ".json?" + qs.ToString()
|
|
||||||
}
|
|
||||||
|
|
||||||
type Category struct {
|
|
||||||
Name string
|
|
||||||
Path string
|
|
||||||
}
|
|
||||||
|
|
||||||
var Categories = []Category{
|
|
||||||
{"Top Stories", "topstories"},
|
|
||||||
{"Best Stories", "beststories"},
|
|
||||||
{"New Stories", "newstories"},
|
|
||||||
}
|
|
||||||
|
|
||||||
type Comment struct {
|
|
||||||
By string `json:"by"`
|
|
||||||
Text string `json:"text"`
|
|
||||||
TimeRaw int64 `json:"time"`
|
|
||||||
Time time.Time `json:"-"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Kids []int `json:"kids"`
|
|
||||||
Parent int `json:"parent"`
|
|
||||||
Id int `json:"id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Story struct {
|
|
||||||
Id int `json:"id"`
|
|
||||||
By string `json:"by"`
|
|
||||||
Text string `json:"text"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Descendents int `json:"descendants"`
|
|
||||||
Score int `json:"score"`
|
|
||||||
Url string
|
|
||||||
TimeRaw int64 `json:"time"`
|
|
||||||
Time time.Time `json:"-"`
|
|
||||||
// comment ids
|
|
||||||
Kids []int
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetTopStoriesRequest struct {
|
|
||||||
Limit int
|
|
||||||
Page int
|
|
||||||
}
|
|
||||||
|
|
||||||
func MustItemId(ctx *h.RequestContext) int {
|
|
||||||
raw := h.GetQueryParam(ctx, "item")
|
|
||||||
parsed, err := strconv.ParseInt(raw, 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return int(parsed)
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetStories(category string, page int, limit int) []Story {
|
|
||||||
top, err := httpjson.Get[[]int](url(category, h.NewQs()))
|
|
||||||
if err != nil {
|
|
||||||
slog.Error("failed to load top stories", slog.String("err", err.Error()))
|
|
||||||
return make([]Story, 0)
|
|
||||||
}
|
|
||||||
ids := *top
|
|
||||||
start := page * limit
|
|
||||||
end := start + limit
|
|
||||||
|
|
||||||
if start > len(ids) {
|
|
||||||
return make([]Story, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
if end > len(ids) {
|
|
||||||
end = len(ids)
|
|
||||||
}
|
|
||||||
|
|
||||||
return batch.ParallelProcess[int, Story](
|
|
||||||
ids[start:end],
|
|
||||||
50,
|
|
||||||
func(id int) Story {
|
|
||||||
story, err := GetStory(id)
|
|
||||||
if err != nil {
|
|
||||||
slog.Error("failed to load story", slog.Int("id", id), slog.String("err", err.Error()))
|
|
||||||
return Story{}
|
|
||||||
}
|
|
||||||
return *story
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetTopStories(page int, limit int) []Story {
|
|
||||||
return GetStories("topstories", page, limit)
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetBestStories(page int, limit int) []Story {
|
|
||||||
return GetStories("beststories", page, limit)
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetNewStories(page int, limit int) []Story {
|
|
||||||
return GetStories("newstories", page, limit)
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetComments(ids []int) []Comment {
|
|
||||||
return batch.ParallelProcess(
|
|
||||||
ids,
|
|
||||||
50,
|
|
||||||
func(id int) Comment {
|
|
||||||
comment, err := GetComment(id)
|
|
||||||
if err != nil {
|
|
||||||
slog.Error("failed to load comment", slog.Int("id", id), slog.String("err", err.Error()))
|
|
||||||
return Comment{}
|
|
||||||
}
|
|
||||||
return *comment
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetComment(id int) (*Comment, error) {
|
|
||||||
c, err := httpjson.Get[Comment](url(fmt.Sprintf("item/%d", id), h.NewQs()))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
c.Text = sanitize.Sanitize(c.Text)
|
|
||||||
c.By = sanitize.Sanitize(c.By)
|
|
||||||
c.Time = timeformat.ParseUnix(c.TimeRaw)
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetStory(id int) (*Story, error) {
|
|
||||||
s, err := httpjson.Get[Story](url(fmt.Sprintf("item/%d", id), h.NewQs()))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
s.Title = sanitize.Sanitize(s.Title)
|
|
||||||
s.Text = sanitize.Sanitize(s.Text)
|
|
||||||
s.By = sanitize.Sanitize(s.By)
|
|
||||||
s.Time = timeformat.ParseUnix(s.TimeRaw)
|
|
||||||
return s, nil
|
|
||||||
}
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
package parse
|
|
||||||
|
|
||||||
import "strconv"
|
|
||||||
|
|
||||||
func MustParseInt(s string, fallback int) int {
|
|
||||||
v, err := strconv.ParseInt(s, 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
return fallback
|
|
||||||
}
|
|
||||||
return int(v)
|
|
||||||
}
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
package internal
|
|
||||||
|
|
||||||
import "math/rand"
|
|
||||||
|
|
||||||
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
|
||||||
|
|
||||||
func RandSeq(n int) string {
|
|
||||||
b := make([]rune, n)
|
|
||||||
for i := range b {
|
|
||||||
b[i] = letters[rand.Intn(len(letters))]
|
|
||||||
}
|
|
||||||
return string(b)
|
|
||||||
}
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
package sanitize
|
|
||||||
|
|
||||||
import "github.com/microcosm-cc/bluemonday"
|
|
||||||
|
|
||||||
var p = bluemonday.UGCPolicy()
|
|
||||||
|
|
||||||
func Sanitize(text string) string {
|
|
||||||
return p.Sanitize(text)
|
|
||||||
}
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
package timeformat
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ParseUnix(t int64) time.Time {
|
|
||||||
return time.UnixMilli(t * 1000)
|
|
||||||
}
|
|
||||||
|
|
||||||
func RelativeTime(t time.Time) string {
|
|
||||||
now := time.Now()
|
|
||||||
diff := now.Sub(t)
|
|
||||||
|
|
||||||
var pluralize = func(s string) string {
|
|
||||||
if s[0] == '1' {
|
|
||||||
return s[:len(s)-5] + " ago"
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
switch {
|
|
||||||
case diff < time.Minute:
|
|
||||||
return "just now"
|
|
||||||
case diff < time.Hour:
|
|
||||||
return pluralize(fmt.Sprintf("%d minutes ago", int(diff.Minutes())))
|
|
||||||
case diff < time.Hour*24:
|
|
||||||
return pluralize(fmt.Sprintf("%d hours ago", int(diff.Hours())))
|
|
||||||
case diff < time.Hour*24*7:
|
|
||||||
return pluralize(fmt.Sprintf("%d days ago", int(diff.Hours()/24)))
|
|
||||||
case diff < time.Hour*24*30:
|
|
||||||
return pluralize(fmt.Sprintf("%d weeks ago", int(diff.Hours()/(24*7))))
|
|
||||||
case diff < time.Hour*24*365:
|
|
||||||
return pluralize(fmt.Sprintf("%d months ago", int(diff.Hours()/(24*30))))
|
|
||||||
default:
|
|
||||||
return pluralize(fmt.Sprintf("%d years ago", int(diff.Hours()/(24*365))))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
"github.com/maddalax/htmgo/framework/service"
|
|
||||||
"hackernews/__htmgo"
|
|
||||||
"io/fs"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
locator := service.NewLocator()
|
|
||||||
|
|
||||||
h.Start(h.AppOpts{
|
|
||||||
ServiceLocator: locator,
|
|
||||||
LiveReload: true,
|
|
||||||
Register: func(app *h.App) {
|
|
||||||
sub, err := fs.Sub(GetStaticAssets(), "assets/dist")
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
http.FileServerFS(sub)
|
|
||||||
|
|
||||||
app.Router.Handle("/item", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
id := r.URL.Query().Get("id")
|
|
||||||
w.Header().Set("Location", fmt.Sprintf("/?item=%s", id))
|
|
||||||
w.WriteHeader(302)
|
|
||||||
}))
|
|
||||||
app.Router.Handle("/public/*", http.StripPrefix("/public", http.FileServerFS(sub)))
|
|
||||||
__htmgo.Register(app.Router)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
package pages
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
"hackernews/partials"
|
|
||||||
)
|
|
||||||
|
|
||||||
func IndexPage(ctx *h.RequestContext) *h.Page {
|
|
||||||
return h.NewPage(
|
|
||||||
RootPage(
|
|
||||||
h.Div(
|
|
||||||
h.Class("flex gap-2 min-h-screen"),
|
|
||||||
partials.StorySidebar(ctx),
|
|
||||||
h.Main(
|
|
||||||
h.Class("flex justify-left items-start p-6 w-full"),
|
|
||||||
partials.Story(ctx),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
package pages
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
)
|
|
||||||
|
|
||||||
func RootPage(children ...h.Ren) h.Ren {
|
|
||||||
banner := h.A(
|
|
||||||
h.Class("bg-neutral-200 text-neutral-600 text-center p-2 flex items-center justify-center"),
|
|
||||||
h.Href("https://github.com/maddalax/htmgo"),
|
|
||||||
h.Attribute("target", "_blank"),
|
|
||||||
h.Text("Built with htmgo.dev"),
|
|
||||||
)
|
|
||||||
|
|
||||||
return h.Html(
|
|
||||||
h.HxExtensions(
|
|
||||||
h.BaseExtensions(),
|
|
||||||
),
|
|
||||||
h.Head(
|
|
||||||
h.Meta("viewport", "width=device-width, initial-scale=1"),
|
|
||||||
h.Link("/public/favicon.ico", "icon"),
|
|
||||||
h.Link("/public/apple-touch-icon.png", "apple-touch-icon"),
|
|
||||||
h.Meta("title", "hackernews"),
|
|
||||||
h.Meta("charset", "utf-8"),
|
|
||||||
h.Meta("author", "htmgo"),
|
|
||||||
h.Meta("description", "hacker news reader, built with htmgo"),
|
|
||||||
h.Meta("og:title", "hacker news reader"),
|
|
||||||
h.Meta("og:url", "https://hn.htmgo.dev"),
|
|
||||||
h.Link("canonical", "https://hn.htmgo.dev"),
|
|
||||||
h.Meta("og:description", "hacker news reader, built with htmgo"),
|
|
||||||
h.Link("/public/main.css", "stylesheet"),
|
|
||||||
h.Script("/public/htmgo.js"),
|
|
||||||
),
|
|
||||||
h.Body(
|
|
||||||
banner,
|
|
||||||
h.Div(
|
|
||||||
h.Fragment(children...),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,103 +0,0 @@
|
||||||
package partials
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
"hackernews/internal/batch"
|
|
||||||
"hackernews/internal/news"
|
|
||||||
"hackernews/internal/sanitize"
|
|
||||||
"hackernews/internal/timeformat"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func StoryComments(ctx *h.RequestContext) *h.Partial {
|
|
||||||
return h.NewPartial(
|
|
||||||
h.Fragment(
|
|
||||||
h.OobSwap(
|
|
||||||
ctx,
|
|
||||||
h.Div(
|
|
||||||
h.Id("comments-loader"),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("flex flex-col gap-3 prose max-w-none"),
|
|
||||||
CachedStoryComments(news.MustItemId(ctx)),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
var CachedStoryComments = h.CachedPerKeyT[string, int](time.Minute*3, func(itemId int) (string, h.GetElementFunc) {
|
|
||||||
return fmt.Sprintf("story-comments-%d", itemId), func() *h.Element {
|
|
||||||
story, err := news.GetStory(itemId)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return h.Div(
|
|
||||||
h.Text("Failed to load story"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
comments := news.GetComments(story.Kids)
|
|
||||||
|
|
||||||
// parallel process because each comment needs to load its children comments
|
|
||||||
items := batch.ParallelProcess[news.Comment, *h.Element](comments, 50, func(item news.Comment) *h.Element {
|
|
||||||
return Comment(item, 0)
|
|
||||||
})
|
|
||||||
|
|
||||||
return h.List(items, func(item *h.Element, index int) *h.Element {
|
|
||||||
return item
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
func Comment(item news.Comment, nesting int) *h.Element {
|
|
||||||
if item.Text == "" {
|
|
||||||
return h.Empty()
|
|
||||||
}
|
|
||||||
|
|
||||||
children := news.GetComments(item.Kids)
|
|
||||||
|
|
||||||
return h.Div(
|
|
||||||
h.ClassX("block bg-white pb-2 pt-2", h.ClassMap{
|
|
||||||
"border-b border-gray-200": nesting == 0,
|
|
||||||
"border-l border-gray-200": nesting > 0,
|
|
||||||
}),
|
|
||||||
h.If(
|
|
||||||
nesting > 0,
|
|
||||||
h.Attribute("style", fmt.Sprintf("margin-left: %dpx", (nesting-1)*15)),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.If(
|
|
||||||
nesting > 0,
|
|
||||||
h.Class("pl-4"),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("flex gap-1 items-center"),
|
|
||||||
h.Div(
|
|
||||||
h.Class("font-bold text-rose-500"),
|
|
||||||
h.UnsafeRaw(sanitize.Sanitize(item.By)),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("text-sm text-gray-600"),
|
|
||||||
h.UnsafeRaw("•"),
|
|
||||||
h.TextF(" %s", timeformat.RelativeTime(item.Time)),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("text-sm text-gray-600"),
|
|
||||||
h.UnsafeRaw(sanitize.Sanitize(strings.TrimSpace(item.Text))),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
h.If(
|
|
||||||
len(children) > 0,
|
|
||||||
h.List(
|
|
||||||
children, func(child news.Comment, index int) *h.Element {
|
|
||||||
return h.Div(
|
|
||||||
Comment(child, nesting+1),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,165 +0,0 @@
|
||||||
package partials
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
"hackernews/components"
|
|
||||||
"hackernews/internal/news"
|
|
||||||
"hackernews/internal/parse"
|
|
||||||
"hackernews/internal/sanitize"
|
|
||||||
"hackernews/internal/timeformat"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
var ScrollJs = `
|
|
||||||
const scrollContainer = self;
|
|
||||||
let isDown = false;
|
|
||||||
let startX;
|
|
||||||
let scrollLeft;
|
|
||||||
|
|
||||||
scrollContainer.addEventListener("mousedown", (e) => {
|
|
||||||
isDown = true;
|
|
||||||
scrollContainer.classList.add("active");
|
|
||||||
startX = e.pageX - scrollContainer.offsetLeft;
|
|
||||||
scrollLeft = scrollContainer.scrollLeft;
|
|
||||||
});
|
|
||||||
|
|
||||||
scrollContainer.addEventListener("mouseleave", () => {
|
|
||||||
isDown = false;
|
|
||||||
scrollContainer.classList.remove("active");
|
|
||||||
});
|
|
||||||
|
|
||||||
scrollContainer.addEventListener("mouseup", () => {
|
|
||||||
isDown = false;
|
|
||||||
scrollContainer.classList.remove("active");
|
|
||||||
});
|
|
||||||
|
|
||||||
scrollContainer.addEventListener("mousemove", (e) => {
|
|
||||||
if (!isDown) return;
|
|
||||||
e.preventDefault();
|
|
||||||
const x = e.pageX - scrollContainer.offsetLeft;
|
|
||||||
const walk = (x - startX) * 3; // Adjust scroll speed here
|
|
||||||
scrollContainer.scrollLeft = scrollLeft - walk;
|
|
||||||
});
|
|
||||||
`
|
|
||||||
|
|
||||||
func StorySidebar(ctx *h.RequestContext) *h.Partial {
|
|
||||||
category := h.GetQueryParam(ctx, "category")
|
|
||||||
pageRaw := h.GetQueryParam(ctx, "page")
|
|
||||||
mode := h.GetQueryParam(ctx, "mode")
|
|
||||||
|
|
||||||
if pageRaw == "" {
|
|
||||||
pageRaw = "0"
|
|
||||||
}
|
|
||||||
|
|
||||||
if category == "" {
|
|
||||||
category = "topstories"
|
|
||||||
}
|
|
||||||
|
|
||||||
page := parse.MustParseInt(pageRaw, 0)
|
|
||||||
|
|
||||||
fetchMorePath := h.GetPartialPathWithQs(
|
|
||||||
StorySidebar,
|
|
||||||
h.NewQs("mode", "infinite", "page", fmt.Sprintf("%d", page+1), "category", category),
|
|
||||||
)
|
|
||||||
|
|
||||||
list := CachedStoryList(category, page, 50, fetchMorePath)
|
|
||||||
|
|
||||||
body := h.Aside(
|
|
||||||
h.Id("story-sidebar"),
|
|
||||||
h.JoinExtensions(
|
|
||||||
h.TriggerChildren(),
|
|
||||||
),
|
|
||||||
h.Class("sticky top-0 h-screen p-1 bg-gray-100 overflow-y-auto max-w-80 min-w-80"),
|
|
||||||
h.Div(
|
|
||||||
h.Class("flex flex-col gap-1"),
|
|
||||||
SidebarTitle(category),
|
|
||||||
h.Id("story-list"),
|
|
||||||
list,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
if mode == "infinite" {
|
|
||||||
return h.NewPartial(
|
|
||||||
list,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if ctx.IsHxRequest() {
|
|
||||||
return h.SwapManyPartial(ctx, body)
|
|
||||||
}
|
|
||||||
|
|
||||||
return h.NewPartial(body)
|
|
||||||
}
|
|
||||||
|
|
||||||
func SidebarTitle(defaultCategory string) *h.Element {
|
|
||||||
today := time.Now().Format("Mon, 02 Jan 2006")
|
|
||||||
return h.Div(
|
|
||||||
h.Class("flex flex-col px-2 pt-4 pb-2"),
|
|
||||||
h.Div(
|
|
||||||
h.Class("text-sm text-gray-600"),
|
|
||||||
h.Text(today),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("font-bold text-xl"),
|
|
||||||
h.Text("Hacker News"),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.OnLoad(
|
|
||||||
h.EvalJs(ScrollJs),
|
|
||||||
),
|
|
||||||
h.Class("scroll-container mt-2 flex gap-1 no-scrollbar overflow-y-hidden whitespace-nowrap overflow-x-auto"),
|
|
||||||
h.List(news.Categories, func(item news.Category, index int) *h.Element {
|
|
||||||
return CategoryBadge(defaultCategory, item)
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func CategoryBadge(defaultCategory string, category news.Category) *h.Element {
|
|
||||||
selected := category.Path == defaultCategory
|
|
||||||
return components.Badge(
|
|
||||||
category.Name,
|
|
||||||
selected,
|
|
||||||
h.Attribute("hx-swap", "none"),
|
|
||||||
h.If(
|
|
||||||
!selected,
|
|
||||||
h.PostPartialOnClickQs(
|
|
||||||
StorySidebar,
|
|
||||||
h.NewQs("category", category.Path),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
var CachedStoryList = h.CachedPerKeyT4(time.Minute*5, func(category string, page int, limit int, fetchMorePath string) (string, h.GetElementFunc) {
|
|
||||||
return fmt.Sprintf("%s-stories-%d-%d", category, page, limit), func() *h.Element {
|
|
||||||
stories := news.GetStories(category, page, limit)
|
|
||||||
return h.List(stories, func(item news.Story, index int) *h.Element {
|
|
||||||
return h.Div(
|
|
||||||
h.Attribute("hx-swap", "none"),
|
|
||||||
h.PostPartialOnClickQs(Story, h.NewQs("item", fmt.Sprintf("%d", item.Id))),
|
|
||||||
h.A(h.Href(item.Url)),
|
|
||||||
h.Class("block p-2 bg-white rounded-md shadow cursor-pointer"),
|
|
||||||
h.Div(
|
|
||||||
h.Class("font-bold"),
|
|
||||||
h.UnsafeRaw(sanitize.Sanitize(item.Title)),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("text-sm text-gray-600"),
|
|
||||||
h.Div(h.TextF("%s ", item.By), h.UnsafeRaw("•"), h.TextF(" %s", timeformat.RelativeTime(item.Time))),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("text-sm text-gray-600"),
|
|
||||||
h.UnsafeRaw(fmt.Sprintf("%d upvotes • %d comments", item.Score, item.Descendents)),
|
|
||||||
),
|
|
||||||
h.If(index == len(stories)-1, h.Div(
|
|
||||||
h.Id("load-more"),
|
|
||||||
h.Attribute("hx-swap", "beforeend"),
|
|
||||||
h.HxTarget("#story-list"),
|
|
||||||
h.Get(fetchMorePath, "intersect once"),
|
|
||||||
)),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
@ -1,93 +0,0 @@
|
||||||
package partials
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
"hackernews/internal/news"
|
|
||||||
"hackernews/internal/sanitize"
|
|
||||||
"hackernews/internal/timeformat"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Story(ctx *h.RequestContext) *h.Partial {
|
|
||||||
storyId := news.MustItemId(ctx)
|
|
||||||
if storyId == 0 {
|
|
||||||
return h.NewPartial(
|
|
||||||
h.Div(
|
|
||||||
h.Class("flex justify-center bg-neutral-300"),
|
|
||||||
h.Id("story-body"),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if ctx.IsHxRequest() {
|
|
||||||
return h.SwapManyPartialWithHeaders(
|
|
||||||
ctx,
|
|
||||||
h.PushUrlHeader(fmt.Sprintf("/?item=%d", storyId)),
|
|
||||||
h.Div(
|
|
||||||
h.Class("w-full"),
|
|
||||||
h.Id("story-body"),
|
|
||||||
CachedStoryBody(storyId),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return h.NewPartial(
|
|
||||||
CachedStoryBody(storyId),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
var CachedStoryBody = h.CachedPerKeyT[string, int](time.Minute*3, func(itemId int) (string, h.GetElementFunc) {
|
|
||||||
return fmt.Sprintf("story-%d", itemId), func() *h.Element {
|
|
||||||
story, err := news.GetStory(itemId)
|
|
||||||
if err != nil {
|
|
||||||
return h.Div(
|
|
||||||
h.Id("story-body"),
|
|
||||||
h.Text("Failed to load story"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return StoryBody(story)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
func StoryBody(story *news.Story) *h.Element {
|
|
||||||
return h.Div(
|
|
||||||
h.Class("w-full"),
|
|
||||||
h.Id("story-body"),
|
|
||||||
h.Div(
|
|
||||||
h.Class("prose prose-2xl border-b border-gray-200 pb-3 max-w-none w-full"),
|
|
||||||
h.H5(
|
|
||||||
h.Class("flex gap-2 items-left font-bold"),
|
|
||||||
h.UnsafeRaw(sanitize.Sanitize(story.Title)),
|
|
||||||
),
|
|
||||||
h.A(
|
|
||||||
h.Href(story.Url),
|
|
||||||
h.Class("text-sm text-rose-400 no-underline"),
|
|
||||||
h.Text(story.Url),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("text-sm text-gray-600"),
|
|
||||||
h.UnsafeRaw(sanitize.Sanitize(story.Text)),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("text-sm text-gray-600 mt-2"),
|
|
||||||
h.TextF("%d upvotes ", story.Score),
|
|
||||||
h.UnsafeRaw("•"),
|
|
||||||
h.TextF(" %s ", story.By),
|
|
||||||
h.UnsafeRaw("•"),
|
|
||||||
h.TextF(" %s", timeformat.RelativeTime(story.Time)),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Id("comments-loader"),
|
|
||||||
h.Class("flex justify-center items-center h-24"),
|
|
||||||
h.Div(
|
|
||||||
h.Class("animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-rose-500"),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Class("mt-2 min-w-3xl max-w-3xl"),
|
|
||||||
h.GetPartial(StoryComments, "load"),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
/** @type {import('tailwindcss').Config} */
|
|
||||||
module.exports = {
|
|
||||||
content: ["**/*.go"],
|
|
||||||
plugins: [
|
|
||||||
require('@tailwindcss/typography')
|
|
||||||
],
|
|
||||||
};
|
|
||||||
6
examples/minimal-htmgo/.gitignore
vendored
|
|
@ -1,6 +0,0 @@
|
||||||
/assets/dist
|
|
||||||
tmp
|
|
||||||
node_modules
|
|
||||||
.idea
|
|
||||||
__htmgo
|
|
||||||
dist
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
Minimal example that just uses htmgo for html rendering / js support and nothing else.
|
|
||||||
|
|
||||||
Removes automatic support for:
|
|
||||||
|
|
||||||
1. live reloading
|
|
||||||
2. tailwind recompilation
|
|
||||||
3. page/partial route registration
|
|
||||||
4. Single binary (since /public/ assets is required to be there), normally htmgo uses the embedded file system in other examples such as https://github.com/maddalax/htmgo/blob/master/templates/starter/assets_prod.go
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
module minimal-htmgo
|
|
||||||
|
|
||||||
go 1.23.0
|
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/go-chi/chi/v5 v5.1.0
|
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b
|
|
||||||
)
|
|
||||||
|
|
||||||
require github.com/google/uuid v1.6.0 // indirect
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
|
||||||
github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
|
|
||||||
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
|
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b h1:m+xI+HBEQdie/Rs+mYI0HTFTMlYQSCv0l/siPDoywA4=
|
|
||||||
github.com/maddalax/htmgo/framework v1.0.7-0.20250703190716-06f01b3d7c1b/go.mod h1:NGGzWVXWksrQJ9kV9SGa/A1F1Bjsgc08cN7ZVb98RqY=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
|
||||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
|
||||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
|
||||||
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
|
|
||||||
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
|
|
@ -1,44 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
"github.com/maddalax/htmgo/framework/js"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Index(ctx *h.RequestContext) *h.Page {
|
|
||||||
return h.NewPage(
|
|
||||||
h.Html(
|
|
||||||
h.HxExtensions(
|
|
||||||
h.BaseExtensions(),
|
|
||||||
),
|
|
||||||
h.Head(
|
|
||||||
h.Meta("viewport", "width=device-width, initial-scale=1"),
|
|
||||||
h.Script("/public/htmgo.js"),
|
|
||||||
),
|
|
||||||
h.Body(
|
|
||||||
h.Pf("hello htmgo"),
|
|
||||||
h.Div(
|
|
||||||
h.Get("/current-time", "load, every 1s"),
|
|
||||||
),
|
|
||||||
h.Div(
|
|
||||||
h.Button(
|
|
||||||
h.Text("Click me"),
|
|
||||||
h.OnClick(
|
|
||||||
js.EvalJs(`
|
|
||||||
console.log("you evalulated javascript");
|
|
||||||
alert("you clicked me");
|
|
||||||
`),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func CurrentTime(ctx *h.RequestContext) *h.Partial {
|
|
||||||
return h.NewPartial(
|
|
||||||
h.Pf("It is %s", time.Now().String()),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/go-chi/chi/v5"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
router := chi.NewRouter()
|
|
||||||
|
|
||||||
fileServer := http.StripPrefix("/public", http.FileServer(http.Dir("./public")))
|
|
||||||
router.Handle("/public/*", fileServer)
|
|
||||||
|
|
||||||
router.Get("/", func(writer http.ResponseWriter, request *http.Request) {
|
|
||||||
RenderPage(request, writer, Index)
|
|
||||||
})
|
|
||||||
|
|
||||||
router.Get("/current-time", func(writer http.ResponseWriter, request *http.Request) {
|
|
||||||
RenderPartial(request, writer, CurrentTime)
|
|
||||||
})
|
|
||||||
|
|
||||||
http.ListenAndServe(":3000", router)
|
|
||||||
}
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/maddalax/htmgo/framework/h"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
func RenderToString(element *h.Element) string {
|
|
||||||
return h.Render(element)
|
|
||||||
}
|
|
||||||
|
|
||||||
func RenderPage(req *http.Request, w http.ResponseWriter, page func(ctx *h.RequestContext) *h.Page) {
|
|
||||||
ctx := h.RequestContext{
|
|
||||||
Request: req,
|
|
||||||
Response: w,
|
|
||||||
}
|
|
||||||
h.HtmlView(w, page(&ctx))
|
|
||||||
}
|
|
||||||
|
|
||||||
func RenderPartial(req *http.Request, w http.ResponseWriter, partial func(ctx *h.RequestContext) *h.Partial) {
|
|
||||||
ctx := h.RequestContext{
|
|
||||||
Request: req,
|
|
||||||
Response: w,
|
|
||||||
}
|
|
||||||
h.PartialView(w, partial(&ctx))
|
|
||||||
}
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Project exclude paths
|
|
||||||
/tmp/
|
|
||||||
node_modules/
|
|
||||||
dist/
|
|
||||||
js/dist
|
|
||||||
js/node_modules
|
|
||||||
go.work
|
|
||||||
go.work.sum
|
|
||||||
.idea
|
|
||||||
!framework/assets/dist
|
|
||||||
__htmgo
|
|
||||||
6
examples/simple-auth/.gitignore
vendored
|
|
@ -1,6 +0,0 @@
|
||||||
/assets/dist
|
|
||||||
tmp
|
|
||||||
node_modules
|
|
||||||
.idea
|
|
||||||
__htmgo
|
|
||||||
dist
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
# Stage 1: Build the Go binary
|
|
||||||
FROM golang:1.23 AS builder
|
|
||||||
|
|
||||||
# Set the working directory inside the container
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
# Copy go.mod and go.sum files
|
|
||||||
COPY go.mod go.sum ./
|
|
||||||
|
|
||||||
# Download and cache the Go modules
|
|
||||||
RUN go mod download
|
|
||||||
|
|
||||||
# Copy the source code into the container
|
|
||||||
COPY . .
|
|
||||||
|
|
||||||
# Build the Go binary for Linux
|
|
||||||
RUN CGO_ENABLED=0 GOPRIVATE=github.com/maddalax LOG_LEVEL=debug go run github.com/maddalax/htmgo/cli/htmgo@latest build
|
|
||||||
|
|
||||||
RUN CGO_ENABLED=1 GOOS=linux go build -tags prod -o ./dist -a -ldflags '-linkmode external -extldflags "-static"' .
|
|
||||||
|
|
||||||
|
|
||||||
# Stage 2: Create the smallest possible image
|
|
||||||
FROM gcr.io/distroless/base-debian11
|
|
||||||
|
|
||||||
# Set the working directory inside the container
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
# Copy the Go binary from the builder stage
|
|
||||||
COPY --from=builder /app/dist .
|
|
||||||
|
|
||||||
# Expose the necessary port (replace with your server port)
|
|
||||||
EXPOSE 3000
|
|
||||||
|
|
||||||
|
|
||||||
# Command to run the binary
|
|
||||||
CMD ["./simpleauth"]
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
version: '3'
|
|
||||||
|
|
||||||
tasks:
|
|
||||||
run:
|
|
||||||
cmds:
|
|
||||||
- htmgo run
|
|
||||||
silent: true
|
|
||||||
|
|
||||||
build:
|
|
||||||
cmds:
|
|
||||||
- htmgo build
|
|
||||||
|
|
||||||
docker:
|
|
||||||
cmds:
|
|
||||||
- docker build .
|
|
||||||
|
|
||||||
watch:
|
|
||||||
cmds:
|
|
||||||
- htmgo watch
|
|
||||||
silent: true
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
//go:build !prod
|
|
||||||
// +build !prod
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io/fs"
|
|
||||||
"simpleauth/internal/embedded"
|
|
||||||
)
|
|
||||||
|
|
||||||
func GetStaticAssets() fs.FS {
|
|
||||||
return embedded.NewOsFs()
|
|
||||||
}
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
@tailwind base;
|
|
||||||
@tailwind components;
|
|
||||||
@tailwind utilities;
|
|
||||||
|
Before Width: | Height: | Size: 3.3 KiB |