24 Commits
Author SHA1 Message Date
Aeolin Ferjünnoz 4eaea29513 - added instructions on docker usage 2026-04-12 17:18:29 +02:00
Aeolin Ferjünnoz 806ad23315 - register and login working 2026-04-12 17:14:52 +02:00
Aeolin Ferjünnoz 6abc36bc9b - started implementing frontend to backend 2026-04-12 16:38:59 +02:00
Aeolin Ferjünnoz 3c9f7323ba - first version of backend done 2026-04-12 03:45:01 +02:00
Aeolin Ferjünnoz d466365348 - implement most controllers 2026-04-12 02:23:26 +02:00
Aeolin Ferjünnoz 22aabc8f27 - started implementing backend 2026-04-11 21:36:05 +02:00
nachbaisabel 3da8813c41 filter for marketplace 2026-04-07 23:56:55 +02:00
nachbaisabel 02b8a75947 prompt creation & detail page 2026-04-07 23:46:17 +02:00
nachbaisabel d2d5c0c66c new pages and linking 2026-04-06 20:58:30 +02:00
nachbaisabel 4105659b0b feed page 2026-04-06 20:18:25 +02:00
nachbaisabel da52852fdf removed files 2026-04-06 16:32:00 +02:00
nachbaisabel 7b23b296d3 marketplace 2026-04-06 16:30:55 +02:00
nachbaisabel a4a5d03f9f creators page 2026-04-06 16:21:33 +02:00
nachbaisabel 11e973ce61 login, signup, profile page setup 2026-04-05 18:04:51 +02:00
yogarathuvar c5a1692d6b Merge pull request 'Add initial HTML layout' (#1) from chore-html-layout into main
Reviewed-on: #1
2026-02-26 20:37:12 +01:00
Thuvaraka Yogarajah 566e6d41e3 Add initial HTML layout 2026-02-26 20:35:54 +01:00
nachbaisabel 373f217fe6 readme 2026-02-25 18:04:01 +01:00
klessafloria 57edcbedb7 README.md aktualisiert 2026-02-25 14:27:27 +01:00
nachbaisabel 93ae7cef36 readme update 2026-02-23 18:38:29 +01:00
nachbaisabel a20b2fe507 first readme 2026-02-23 18:32:19 +01:00
nachbaisabel b0aa18a3e0 readme 2026-02-22 19:09:37 +01:00
nachbaisabel 88740ecbc3 projektanforderungen moodle 2026-02-22 16:52:40 +01:00
nachbaisabel e14a0fd8d3 readme template 2026-02-22 16:46:47 +01:00
nachbaisabel 5383429a53 README.md hinzugefügt 2026-02-09 14:36:40 +01:00
51 changed files with 1216 additions and 6220 deletions

No files matched your search

-300
View File
@@ -1,300 +0,0 @@
# OnlyPrompt API
This file documents the backend endpoints used by the frontend. The backend is a helper service for server communication, authentication and shared data persistence.
Base URL in local Docker setup:
```text
http://localhost:1801
```
Authentication uses a `jwt` cookie set by the login endpoint. Protected endpoints require a logged-in user.
## Auth
### Register
```http
POST /api/v1/auth/register
Content-Type: application/json
```
Request:
```json
{
"displayName": "Isabelle",
"userName": "its_isabelle",
"email": "isabelle@test.com",
"password": "1234"
}
```
Response: created user data or validation errors.
### Login
```http
POST /api/v1/auth/login
Content-Type: application/json
```
Request:
```json
{
"userNameOrEmail": "isabelle@test.com",
"password": "1234"
}
```
Response: sets the auth cookie.
### Current User
```http
GET /api/v1/auth/me
```
Response:
```json
{
"id": "uuid",
"userName": "its_isabelle",
"email": "isabelle@test.com",
"roles": ["User"]
}
```
### Logout
```http
POST /api/v1/auth/logout
```
Deletes the auth cookie and redirects to login.
## Profiles
### Current Profile
```http
GET /api/v1/profiles/self
```
Response:
```json
{
"displayName": "Isabelle",
"slug": "its_isabelle",
"bio": "AI creator",
"avatarUrl": "data:image/png;base64,...",
"specialities": null,
"averageRating": 0,
"subscribers": 0
}
```
### Creator List
```http
GET /api/v1/profiles?sort=popular&limit=50&search=belle
```
Query parameters:
- `sort`: `popular`, `prompts`, `new`, `rating`
- `limit`: number of creators
- `search`: optional search term
Response: list of creator cards including follow state and avatar URL.
### Public Profile
```http
GET /api/v1/profiles/{creatorId}
```
Used by public creator profiles. The response contains display name, slug, bio, avatar URL, average rating and subscriber count.
### Update Profile
```http
PUT /api/v1/profiles
Content-Type: application/json
```
Request:
```json
{
"displayName": "Belle",
"userName": "lady_belle",
"slug": "lady_belle",
"bio": "Prompt creator",
"avatarUrl": "data:image/png;base64,...",
"specialities": null,
"isPublic": true
}
```
Updates profile data used on My Profile, Community and the topbar.
## Prompts
### List Prompts
```http
GET /api/v1/prompts?sortBy=date&ascending=false&limit=50&search=cat
```
Used by Marketplace. Supports sorting, search and category filtering.
Response items include prompt title, description, creator id, creator name, creator avatar, example image, price, like/save counts and access state.
### Feed
```http
GET /api/v1/feed?sortBy=date&ascending=false&limit=20
```
Used by Dashboard. Returns prompt cards with title, description, creator info, avatar and example image.
### Create Prompt
```http
POST /api/v1/prompts
Content-Type: application/json
```
Request:
```json
{
"title": "Luxury Cat Portrait",
"description": "Create a premium cat portrait prompt.",
"content": "Write the full prompt instructions here.",
"category": "art",
"subscriptionTier": null,
"slug": null,
"exampleOutput": "Example output text",
"exampleImageUrl": "data:image/png;base64,...",
"price": null
}
```
Response: created prompt. The frontend redirects to `/post-detail?id={id}`.
### Own Prompts
```http
GET /api/v1/prompts/mine
```
Used by My Profile to show prompts created by the logged-in user.
### Update Prompt
```http
PUT /api/v1/prompts/{id}
Content-Type: application/json
```
Request body uses the same editable fields as prompt creation. Used by the edit prompt flow.
### Prompt Detail
```http
GET /api/v1/prompts/{id}
```
Response includes:
- title and description
- prompt content if accessible
- category
- creator information
- price or free state
- example output
- example image
- rating data
- like/save state and counts
Paid prompts return no detail content for users without access.
### Likes and Saves
```http
PUT /api/v1/prompts/{id}/likes
DELETE /api/v1/prompts/{id}/likes
PUT /api/v1/prompts/{id}/saves
DELETE /api/v1/prompts/{id}/saves
```
Used by Dashboard, prompt detail and profile tabs to store user interactions.
### Reviews
```http
GET /api/v1/prompts/{id}/reviews
PUT /api/v1/prompts/{id}/reviews
```
`PUT` request:
```json
{
"comment": "Helpful prompt",
"rating": 5
}
```
Used for user feedback on prompts.
## Categories
### Minimal Categories
```http
GET /api/v1/categories/minimal
```
Used by Create New and Marketplace filters.
Response:
```json
[
{
"name": "Art",
"slug": "art"
}
]
```
Default categories are created automatically when the backend starts.
## Subscriptions
### Follow or Subscribe to Creator
```http
GET /api/v1/subscriptions/{creatorId}
PUT /api/v1/subscriptions/{creatorId}
DELETE /api/v1/subscriptions/{creatorId}
```
Used by Community and public profiles to read follow state, follow creators or unfollow creators.
## Error Handling
Common response codes used by the frontend:
- `200 OK`: request succeeded
- `400 Bad Request`: validation error or invalid request data
- `401 Unauthorized`: user is not logged in and should be redirected to login
- `404 Not Found`: requested prompt, profile or subscription was not found
The frontend handles failed requests with visible error states or redirects to login for unauthorized users.
@@ -1,8 +1,6 @@
namespace OnlyPrompt.Backend.ApiModels.Prompt namespace OnlyPrompt.Backend.ApiModels.Prompt
{ {
public record ApiPrompt(Guid Id, string Title, string Description, string? Content, DateTime TimeStamp, Guid CreatorId, string CreatorName, string CategoryName, string CategorySlug, string? ExampleOutput, string? ExampleImageUrl, decimal? Price, int LikeCount, bool IsLiked, int SaveCount, bool IsSaved, int? TierLevel, string? TierName, double? AverageRating, bool CanAccess); public record ApiPrompt(Guid Id, string Title, string Description, string Content, DateTime TimeStamp, Guid CreatorId, string CreatorName, int? TierLevel, string? TierName, double? AverageRating);
public record ApiMinimalPrompt(Guid Id, string Title, string Description, DateTime TimeStamp, Guid CreatorId, string CreatorName, string CreatorAvatarUrl, string? ExampleImageUrl, decimal? Price, int LikeCount, bool IsLiked, int SaveCount, bool IsSaved, int? TierLevel, string? TierName, double? AverageRating, bool CanAccess); public record ApiMinimalPrompt(Guid Id, string Title, DateTime TimeStamp, Guid CreatorId, string CreatorName, int? TierLevel, string? TierName, double? AverageRating, bool CanAccess);
public record ApiReview(Guid CreatorId, string CreatorName, string? Comment, int Rating); public record ApiReview(Guid CreatorId, string CreatorName, string? Comment, int Rating);
public record ApiLikeState(int LikeCount, bool IsLiked);
public record ApiSaveState(int SaveCount, bool IsSaved);
} }
@@ -1,5 +1,6 @@
namespace OnlyPrompt.Backend.ApiModels.Prompt using OnlyPrompt.Backend.Utils;
namespace OnlyPrompt.Backend.ApiModels.Prompt
{ {
public record ApiCreatePromptRequest(string Title, string Description, string Content, string Category, int? SubscriptionTier, string? Slug, string? ExampleOutput, string? ExampleImageUrl, decimal? Price); public record ApiCreatePromptRequest(string Title, string Description, string Content, Identifier Category, int? SubscriptionTier, string Slug);
public record ApiUpdatePromptRequest(string Title, string Description, string Content, string Category, string? ExampleOutput, string? ExampleImageUrl, decimal? Price);
} }
@@ -1,5 +1,4 @@
namespace OnlyPrompt.Backend.ApiModels.UserProfile namespace OnlyPrompt.Backend.ApiModels.UserProfile
{ {
public record ApiUserProfile(string DisplayName, string Slug, string? Bio, string AvatarUrl, string? Specialities, double AverageRating, int Subscribers); public record ApiUserProfile(string DisplayName, string Slug, string? Bio, string AvatarUrl, string? Specialities, double AverageRating, int Subscribers);
public record ApiCreatorCard(Guid UserId, string DisplayName, string Slug, string? Bio, string AvatarUrl, double AverageRating, int Subscribers, int PromptCount, bool IsFollowing);
} }
@@ -3,6 +3,6 @@ using System.ComponentModel.DataAnnotations;
namespace OnlyPrompt.Backend.ApiModels.UserProfile namespace OnlyPrompt.Backend.ApiModels.UserProfile
{ {
public record ApiUpdateProfileRequest([MaxLength(100)] string? DisplayName, [MaxLength(100)][NoWhitespace] string? UserName, [MaxLength(100)][NoWhitespace] string? Slug, string? Bio, string? AvatarUrl, string? Specialities, bool IsPublic); public record ApiUpdateProfileRequest([MaxLength(100)] string? DisplayName, [MaxLength(100)][NoWhitespace] string? Slug, string? Bio, string? AvatarUrl, string? Specialities, bool IsPublic);
public record ApiCreateReviewRequest(string? Comment, [Range(1, 5)] int Rating); public record ApiCreateReviewRequest(string? Comment, [Range(1, 5)] int Rating);
} }
@@ -16,7 +16,7 @@ namespace OnlyPrompt.Backend.Controllers
[Route("api/v1/auth")] [Route("api/v1/auth")]
public class AuthController : BaseController public class AuthController : BaseController
{ {
private static readonly CookieOptions AuthCookieOptions = new CookieOptions { Secure = false, HttpOnly = true, IsEssential = true, SameSite = SameSiteMode.Lax }; private static readonly CookieOptions AuthCookieOptions = new CookieOptions { Secure = true, HttpOnly = true, IsEssential = true };
private readonly IPasswordHasher<UserModel> _passwordHasher; private readonly IPasswordHasher<UserModel> _passwordHasher;
private readonly ITokenService _jwtService; private readonly ITokenService _jwtService;
private readonly ILogger<AuthController> _logger; private readonly ILogger<AuthController> _logger;
@@ -81,7 +81,6 @@ namespace OnlyPrompt.Backend.Controllers
AvatarUrl = avatarUrl, AvatarUrl = avatarUrl,
DisplayName = request.DisplayName, DisplayName = request.DisplayName,
Slug = slug, Slug = slug,
IsPublic = true,
}, },
Roles = [ModelConstants.UserRole], Roles = [ModelConstants.UserRole],
PasswordHash = null, PasswordHash = null,
@@ -104,18 +103,7 @@ namespace OnlyPrompt.Backend.Controllers
public RedirectHttpResult Logout() public RedirectHttpResult Logout()
{ {
this.Response.Cookies.Delete("jwt", AuthCookieOptions); this.Response.Cookies.Delete("jwt", AuthCookieOptions);
return TypedResults.Redirect("/login"); return TypedResults.Redirect("login");
}
[Authorize]
[HttpGet("me")]
public async Task<Results<Ok<ApiUser>, NotFound<string>>> GetCurrentUserAsync()
{
var user = await GetUserAsync();
if (user is null)
return TypedResults.NotFound("User not found");
return TypedResults.Ok(_mapper.Map<ApiUser>(user));
} }
} }
} }
@@ -15,7 +15,7 @@ namespace OnlyPrompt.Backend.Controllers
{ {
[ApiController] [ApiController]
[Route("api/v1/categories")] [Route("api/v1/categories")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] [Authorize(Roles = ModelConstants.AdminRole, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class CategoryController : BaseController public class CategoryController : BaseController
{ {
private static ValidationProblem SlugExistsProblem = TypedResults.ValidationProblem(new Dictionary<string, string[]> private static ValidationProblem SlugExistsProblem = TypedResults.ValidationProblem(new Dictionary<string, string[]>
@@ -53,7 +53,6 @@ namespace OnlyPrompt.Backend.Controllers
} }
[HttpPost] [HttpPost]
[Authorize(Roles = ModelConstants.AdminRole)]
public async Task<Results<Ok<ApiCategory>, ValidationProblem>> CreateCategoryAsync([FromBody] ApiCreateCategoryRequest request) public async Task<Results<Ok<ApiCategory>, ValidationProblem>> CreateCategoryAsync([FromBody] ApiCreateCategoryRequest request)
{ {
var exists = await _db.Categories.AnyAsync(c => c.Slug == request.Slug); var exists = await _db.Categories.AnyAsync(c => c.Slug == request.Slug);
@@ -70,7 +69,6 @@ namespace OnlyPrompt.Backend.Controllers
} }
[HttpPut("{id}")] [HttpPut("{id}")]
[Authorize(Roles = ModelConstants.AdminRole)]
public async Task<Results<Ok<ApiCategory>, NotFound<string>, ValidationProblem>> UpdateCategoryAsync(Identifier id, [FromBody] ApiUpdateCategoryRequest request) public async Task<Results<Ok<ApiCategory>, NotFound<string>, ValidationProblem>> UpdateCategoryAsync(Identifier id, [FromBody] ApiUpdateCategoryRequest request)
{ {
var category = await _db.Categories.FindByIdentifierAsync(id); var category = await _db.Categories.FindByIdentifierAsync(id);
@@ -97,7 +95,6 @@ namespace OnlyPrompt.Backend.Controllers
} }
[HttpDelete("{id}")] [HttpDelete("{id}")]
[Authorize(Roles = ModelConstants.AdminRole)]
public async Task<Results<NoContent, BadRequest<string>, NotFound<string>>> DeleteCategoryAsync(Identifier id, [FromQuery] Identifier? replaceWith = null) public async Task<Results<NoContent, BadRequest<string>, NotFound<string>>> DeleteCategoryAsync(Identifier id, [FromQuery] Identifier? replaceWith = null)
{ {
var hasPrompts = await _db.Prompts.AnyAsync(p => p.CategoryId == id.Id); var hasPrompts = await _db.Prompts.AnyAsync(p => p.CategoryId == id.Id);
@@ -31,7 +31,11 @@ namespace OnlyPrompt.Backend.Controllers
) )
{ {
var userId = User.GetUserId(); var userId = User.GetUserId();
var query = _db.Prompts.AsQueryable(); var query = _db.Prompts
.Where(
x => x.Creator.Subscribers.Any(s => s.SubscriberId == userId)
&& x.CreatorId != userId
);
if (category.HasValue) if (category.HasValue)
query = query.Where(x => category.Value.Id.HasValue ? x.CategoryId == category.Value.Id.Value : x.Category.Slug == category.Value.Slug); query = query.Where(x => category.Value.Id.HasValue ? x.CategoryId == category.Value.Id.Value : x.Category.Slug == category.Value.Slug);
@@ -44,9 +48,7 @@ namespace OnlyPrompt.Backend.Controllers
query = sortBy switch { query = sortBy switch {
FeedSortType.Date => query.OrderBy(x => x.UpdatedAt, ascending), FeedSortType.Date => query.OrderBy(x => x.UpdatedAt, ascending),
FeedSortType.Rating => ascending FeedSortType.Rating => query.OrderBy(x => x.Reviews.Average(r => (double?)r.Rating) ?? 2.5, ascending),
? query.OrderBy(x => x.Likes.Count).ThenBy(x => x.Reviews.Average(r => (double?)r.Rating) ?? 0)
: query.OrderByDescending(x => x.Likes.Count).ThenByDescending(x => x.Reviews.Average(r => (double?)r.Rating) ?? 0),
_ => query _ => query
}; };
@@ -56,19 +58,11 @@ namespace OnlyPrompt.Backend.Controllers
.Select(x => new ApiMinimalPrompt( .Select(x => new ApiMinimalPrompt(
x.Id, x.Id,
x.Title, x.Title,
x.Description,
x.UpdatedAt, x.UpdatedAt,
x.CreatorId, x.CreatorId,
x.Creator.Profile.DisplayName, x.Creator.Profile.DisplayName,
x.Creator.Profile.AvatarUrl, x.SubscriptionTier.Level,
x.ExampleImageUrl, x.SubscriptionTier.Name,
x.Price,
x.Likes.Count,
x.Likes.Any(l => l.UserId == userId),
x.Saves.Count,
x.Saves.Any(s => s.UserId == userId),
x.SubscriptionTier == null ? (int?)null : x.SubscriptionTier.Level,
x.SubscriptionTier == null ? null : x.SubscriptionTier.Name,
x.Reviews.Average(r => (double?)r.Rating), x.Reviews.Average(r => (double?)r.Rating),
x.SubscriptionTier == null || x.Creator.Subscribers.Any(s => s.SubscriberId == userId && x.SubscriptionTier.Level < s.SubscriptionTier.Level) x.SubscriptionTier == null || x.Creator.Subscribers.Any(s => s.SubscriberId == userId && x.SubscriptionTier.Level < s.SubscriptionTier.Level)
)).ToArrayAsync(); )).ToArrayAsync();
@@ -9,7 +9,6 @@ using OnlyPrompt.Backend.ApiModels.UserProfile;
using OnlyPrompt.Backend.Database; using OnlyPrompt.Backend.Database;
using OnlyPrompt.Backend.Database.Models; using OnlyPrompt.Backend.Database.Models;
using OnlyPrompt.Backend.Utils; using OnlyPrompt.Backend.Utils;
using System.ComponentModel.DataAnnotations;
namespace OnlyPrompt.Backend.Controllers namespace OnlyPrompt.Backend.Controllers
{ {
@@ -22,46 +21,17 @@ namespace OnlyPrompt.Backend.Controllers
{ {
{ nameof(UserProfileModel.Slug), new[] { "Slug already exists." } } { nameof(UserProfileModel.Slug), new[] { "Slug already exists." } }
}); });
private static ValidationProblem UserNameExistsProblem = TypedResults.ValidationProblem(new Dictionary<string, string[]>
{
{ nameof(UserModel.UserName), new[] { "Username is already taken." } }
});
public ProfileController(OnlyPromptContext db, IMapper mapper) : base(db, mapper) public ProfileController(OnlyPromptContext db, IMapper mapper) : base(db, mapper)
{ {
} }
[HttpGet("self")]
public async Task<Results<NotFound<string>, Ok<ApiUserProfile>>> GetSelfProfileAsync()
{
var userId = User.GetUserId();
if (userId is null)
return TypedResults.NotFound("Profile not found.");
var profile = await _db.UserProfiles
.Where(up => up.Id == userId.Value)
.Select(up => new ApiUserProfile(
up.DisplayName,
up.Slug,
up.Bio,
up.AvatarUrl,
up.Specialities,
_db.Reviews.Where(r => r.Prompt.CreatorId == up.Id).Average(r => (double?)r.Rating) ?? 0.0,
_db.Subscriptions.Count(s => s.SubscribedToId == up.Id)
))
.FirstOrDefaultAsync();
if (profile is null)
return TypedResults.NotFound("Profile not found.");
return TypedResults.Ok(profile);
}
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<Results<NotFound<string>, Ok<ApiUserProfile>>> GetProfileAsync(Identifier id) public async Task<Results<NotFound<string>, Ok<ApiUserProfile>>> GetProfileAsync(Identifier id)
{ {
var userId = User.GetUserId(); var userId = User.GetUserId();
var profile = await _db.UserProfiles.OfIdentifer(id) var profile = await _db.UserProfiles.OfIdentifer(id)
.Where(up => up.IsPublic || up.Id == userId)
.ProjectTo<ApiUserProfile>(_mapper.ConfigurationProvider) .ProjectTo<ApiUserProfile>(_mapper.ConfigurationProvider)
.FirstOrDefaultAsync(); .FirstOrDefaultAsync();
@@ -71,46 +41,6 @@ namespace OnlyPrompt.Backend.Controllers
return TypedResults.Ok(profile); return TypedResults.Ok(profile);
} }
[HttpGet]
public async Task<ApiCreatorCard[]> GetCreatorsAsync(
[Range(0, int.MaxValue)] int offset = 0,
[Range(1, 100)] int limit = 20,
[FromQuery] string sort = "popular",
[FromQuery] string? search = null
)
{
var userId = User.GetUserId();
var query = _db.UserProfiles.Where(up => up.Id != userId);
if (string.IsNullOrWhiteSpace(search) == false)
query = query.Where(up =>
up.DisplayName.Contains(search) ||
up.Slug.Contains(search) ||
up.User.UserName.Contains(search) ||
(up.Bio != null && up.Bio.Contains(search)));
var projected = query.Select(up => new ApiCreatorCard(
up.Id,
up.DisplayName,
up.Slug,
up.Bio,
up.AvatarUrl,
_db.Reviews.Where(r => r.Prompt.CreatorId == up.Id).Average(r => (double?)r.Rating) ?? 0.0,
_db.Subscriptions.Count(s => s.SubscribedToId == up.Id),
_db.Prompts.Count(p => p.CreatorId == up.Id),
_db.Subscriptions.Any(s => s.SubscribedToId == up.Id && s.SubscriberId == userId)
));
var allCreators = await projected.ToArrayAsync();
return (sort switch
{
"rating" => allCreators.OrderByDescending(c => c.AverageRating),
"new" => allCreators.OrderByDescending(c => c.UserId),
"prompts" => allCreators.OrderByDescending(c => c.PromptCount),
_ => allCreators.OrderByDescending(c => c.Subscribers),
}).Skip(offset).Take(limit).ToArray();
}
[HttpPut] [HttpPut]
public async Task<Results<ValidationProblem, NotFound<string>, Ok<ApiUserProfile>>> UpdateProfileAsync([FromBody] ApiUpdateProfileRequest request) public async Task<Results<ValidationProblem, NotFound<string>, Ok<ApiUserProfile>>> UpdateProfileAsync([FromBody] ApiUpdateProfileRequest request)
{ {
@@ -118,18 +48,6 @@ namespace OnlyPrompt.Backend.Controllers
if (self is null) if (self is null)
return TypedResults.NotFound("Profile not found."); return TypedResults.NotFound("Profile not found.");
var user = await GetUserAsync();
if (user is null)
return TypedResults.NotFound("User not found.");
if (string.IsNullOrEmpty(request.UserName) == false)
{
if (await _db.Users.AnyAsync(u => u.UserName == request.UserName && u.Id != user.Id))
return UserNameExistsProblem;
user.UserName = request.UserName;
}
if (string.IsNullOrEmpty(request.Slug) == false) if (string.IsNullOrEmpty(request.Slug) == false)
{ {
if (await _db.UserProfiles.AnyAsync(up => up.Slug == request.Slug && up.Id != self.Id)) if (await _db.UserProfiles.AnyAsync(up => up.Slug == request.Slug && up.Id != self.Id))
@@ -138,13 +56,13 @@ namespace OnlyPrompt.Backend.Controllers
self.Slug = request.Slug; self.Slug = request.Slug;
} }
if(request.AvatarUrl is not null) if(string.IsNullOrEmpty(request.AvatarUrl) == false)
self.AvatarUrl = request.AvatarUrl; self.AvatarUrl = request.AvatarUrl;
if(request.Bio is not null) if(string.IsNullOrEmpty(request.Bio) == false)
self.Bio = request.Bio; self.Bio = request.Bio;
if(request.Specialities is not null) if(string.IsNullOrEmpty(request.Specialities) == false)
self.Specialities = request.Specialities; self.Specialities = request.Specialities;
if (string.IsNullOrEmpty(request.DisplayName) == false) if (string.IsNullOrEmpty(request.DisplayName) == false)
@@ -152,15 +70,7 @@ namespace OnlyPrompt.Backend.Controllers
self.IsPublic = request.IsPublic; self.IsPublic = request.IsPublic;
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
var result = new ApiUserProfile( var result = _mapper.Map<ApiUserProfile>(self);
self.DisplayName,
self.Slug,
self.Bio,
self.AvatarUrl,
self.Specialities,
await _db.Reviews.Where(r => r.Prompt.CreatorId == self.Id).AverageAsync(r => (double?)r.Rating) ?? 0.0,
await _db.Subscriptions.CountAsync(s => s.SubscribedToId == self.Id)
);
return TypedResults.Ok(result); return TypedResults.Ok(result);
} }
@@ -33,236 +33,21 @@ namespace OnlyPrompt.Backend.Controllers
); );
} }
[HttpGet]
public async Task<ApiMinimalPrompt[]> GetPromptsAsync(
[Range(0, int.MaxValue)][FromQuery] int offset = 0,
[Range(1, 100)][FromQuery] int limit = 20,
[FromQuery] FeedSortType sortBy = FeedSortType.Date,
[FromQuery] bool ascending = false,
[FromQuery] Identifier? category = null,
[FromQuery] string? search = null
)
{
var userId = User.GetUserId();
var query = _db.Prompts.AsQueryable();
if (category.HasValue)
query = query.Where(x => category.Value.Id.HasValue ? x.CategoryId == category.Value.Id.Value : x.Category.Slug == category.Value.Slug);
if (!string.IsNullOrWhiteSpace(search))
query = query.Where(x => x.Title.Contains(search) || x.Description.Contains(search));
query = sortBy switch
{
FeedSortType.Date => query.OrderBy(x => x.UpdatedAt, ascending),
FeedSortType.Rating => ascending
? query.OrderBy(x => x.Likes.Count).ThenBy(x => x.Reviews.Average(r => (double?)r.Rating) ?? 0)
: query.OrderByDescending(x => x.Likes.Count).ThenByDescending(x => x.Reviews.Average(r => (double?)r.Rating) ?? 0),
_ => query
};
var prompts = await query
.Skip(offset)
.Take(limit)
.Select(x => new ApiMinimalPrompt(
x.Id,
x.Title,
x.Description,
x.UpdatedAt,
x.CreatorId,
x.Creator.Profile.DisplayName,
x.Creator.Profile.AvatarUrl,
x.ExampleImageUrl,
x.Price,
x.Likes.Count,
x.Likes.Any(l => l.UserId == userId),
x.Saves.Count,
x.Saves.Any(s => s.UserId == userId),
x.SubscriptionTier == null ? (int?)null : x.SubscriptionTier.Level,
x.SubscriptionTier == null ? null : x.SubscriptionTier.Name,
x.Reviews.Average(r => (double?)r.Rating),
x.CreatorId == userId || ((x.Price == null || x.Price <= 0) && (x.SubscriptionTier == null || x.Creator.Subscribers.Any(s => s.SubscriberId == userId && x.SubscriptionTier.Level < s.SubscriptionTier.Level)))
)).ToArrayAsync();
return prompts;
}
[HttpGet("mine")]
public async Task<ApiMinimalPrompt[]> GetOwnPromptsAsync()
{
var userId = User.GetUserId();
var prompts = await _db.Prompts
.Where(x => x.CreatorId == userId)
.OrderByDescending(x => x.UpdatedAt)
.Select(x => new ApiMinimalPrompt(
x.Id,
x.Title,
x.Description,
x.UpdatedAt,
x.CreatorId,
x.Creator.Profile.DisplayName,
x.Creator.Profile.AvatarUrl,
x.ExampleImageUrl,
x.Price,
x.Likes.Count,
x.Likes.Any(l => l.UserId == userId),
x.Saves.Count,
x.Saves.Any(s => s.UserId == userId),
x.SubscriptionTier == null ? (int?)null : x.SubscriptionTier.Level,
x.SubscriptionTier == null ? null : x.SubscriptionTier.Name,
x.Reviews.Average(r => (double?)r.Rating),
true
)).ToArrayAsync();
return prompts;
}
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<Results<Ok<ApiPrompt>, NotFound<string>>> GetPromptAsync(Identifier id) public async Task<Results<Ok<ApiPrompt>, NotFound<string>>> GetPromptAsync(Identifier id)
{ {
var userId = User.GetUserId(); var userId = User.GetUserId();
var prompt = await GetAccessiblePrompts(userId.Value)
var prompt = await _db.Prompts
.OfIdentifer(id) .OfIdentifer(id)
.FirstOrDefaultAsync(); .FirstOrDefaultAsync();
if (prompt is null)
return TypedResults.NotFound("Prompt not found");
if (prompt.CreatorId != userId && prompt.Price.HasValue && prompt.Price.Value > 0)
return TypedResults.NotFound("Prompt not found or requires payment");
var canAccess = await GetAccessiblePrompts(userId.Value).AnyAsync(p => p.Id == prompt.Id);
var apiPrompt = _mapper.Map<ApiPrompt>(prompt) with
{
Content = canAccess ? prompt.Prompt : null,
CanAccess = canAccess,
IsLiked = prompt.Likes.Any(l => l.UserId == userId),
LikeCount = prompt.Likes.Count,
IsSaved = prompt.Saves.Any(s => s.UserId == userId),
SaveCount = prompt.Saves.Count
};
return TypedResults.Ok(apiPrompt);
}
[HttpPut("{id}")]
public async Task<Results<Ok<ApiPrompt>, NotFound<string>>> UpdatePromptAsync(Identifier id, [FromBody] ApiUpdatePromptRequest request)
{
var userId = User.GetUserId();
var prompt = await _db.Prompts
.OfIdentifer(id)
.FirstOrDefaultAsync(p => p.CreatorId == userId);
if (prompt is null) if (prompt is null)
return TypedResults.NotFound("Prompt not found or no permission"); return TypedResults.NotFound("Prompt not found or no permission");
var category = await _db.Categories.FindByIdentifierAsync(new Identifier(request.Category)); var apiPrompt = _mapper.Map<ApiPrompt>(prompt);
if (category is null)
return TypedResults.NotFound("Category not found");
prompt.Title = request.Title;
prompt.Description = request.Description;
prompt.Prompt = request.Content;
prompt.Category = category;
prompt.ExampleOutput = request.ExampleOutput;
prompt.ExampleImageUrl = request.ExampleImageUrl;
prompt.Price = request.Price;
await _db.SaveChangesAsync();
var apiPrompt = _mapper.Map<ApiPrompt>(prompt) with { Content = prompt.Prompt, CanAccess = true };
return TypedResults.Ok(apiPrompt); return TypedResults.Ok(apiPrompt);
} }
[HttpPut("{id}/likes")]
public async Task<Results<Ok<ApiLikeState>, NotFound<string>>> LikePromptAsync(Identifier id)
{
var userId = User.GetUserId();
var prompt = await _db.Prompts
.OfIdentifer(id)
.FirstOrDefaultAsync();
if (prompt is null)
return TypedResults.NotFound("Prompt not found");
var exists = await _db.PromptLikes.AnyAsync(l => l.PromptId == prompt.Id && l.UserId == userId);
if (exists == false)
{
_db.PromptLikes.Add(new PromptLikeModel
{
PromptId = prompt.Id,
UserId = userId!.Value
});
await _db.SaveChangesAsync();
}
var count = await _db.PromptLikes.CountAsync(l => l.PromptId == prompt.Id);
return TypedResults.Ok(new ApiLikeState(count, true));
}
[HttpDelete("{id}/likes")]
public async Task<Results<Ok<ApiLikeState>, NotFound<string>>> UnlikePromptAsync(Identifier id)
{
var userId = User.GetUserId();
var prompt = await _db.Prompts
.OfIdentifer(id)
.FirstOrDefaultAsync();
if (prompt is null)
return TypedResults.NotFound("Prompt not found");
await _db.PromptLikes
.Where(l => l.PromptId == prompt.Id && l.UserId == userId)
.ExecuteDeleteAsync();
var count = await _db.PromptLikes.CountAsync(l => l.PromptId == prompt.Id);
return TypedResults.Ok(new ApiLikeState(count, false));
}
[HttpPut("{id}/saves")]
public async Task<Results<Ok<ApiSaveState>, NotFound<string>>> SavePromptAsync(Identifier id)
{
var userId = User.GetUserId();
var prompt = await _db.Prompts
.OfIdentifer(id)
.FirstOrDefaultAsync();
if (prompt is null)
return TypedResults.NotFound("Prompt not found");
var exists = await _db.PromptSaves.AnyAsync(s => s.PromptId == prompt.Id && s.UserId == userId);
if (exists == false)
{
_db.PromptSaves.Add(new PromptSaveModel
{
PromptId = prompt.Id,
UserId = userId!.Value
});
await _db.SaveChangesAsync();
}
var count = await _db.PromptSaves.CountAsync(s => s.PromptId == prompt.Id);
return TypedResults.Ok(new ApiSaveState(count, true));
}
[HttpDelete("{id}/saves")]
public async Task<Results<Ok<ApiSaveState>, NotFound<string>>> UnsavePromptAsync(Identifier id)
{
var userId = User.GetUserId();
var prompt = await _db.Prompts
.OfIdentifer(id)
.FirstOrDefaultAsync();
if (prompt is null)
return TypedResults.NotFound("Prompt not found");
await _db.PromptSaves
.Where(s => s.PromptId == prompt.Id && s.UserId == userId)
.ExecuteDeleteAsync();
var count = await _db.PromptSaves.CountAsync(s => s.PromptId == prompt.Id);
return TypedResults.Ok(new ApiSaveState(count, false));
}
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<Results<NoContent, NotFound<string>>> DeletePromptAsync(Identifier id) public async Task<Results<NoContent, NotFound<string>>> DeletePromptAsync(Identifier id)
{ {
@@ -284,7 +69,7 @@ namespace OnlyPrompt.Backend.Controllers
{ {
var userId = User.GetUserId(); var userId = User.GetUserId();
var category = await _db.Categories.FindByIdentifierAsync(new Identifier(request.Category)); var category = await _db.Categories.FindByIdentifierAsync(request.Category);
if (category is null) if (category is null)
return TypedResults.NotFound("Category not found"); return TypedResults.NotFound("Category not found");
@@ -310,9 +95,6 @@ namespace OnlyPrompt.Backend.Controllers
Title = request.Title, Title = request.Title,
Description = request.Description, Description = request.Description,
Prompt = request.Content, Prompt = request.Content,
ExampleOutput = request.ExampleOutput,
ExampleImageUrl = request.ExampleImageUrl,
Price = request.Price,
CreatorId = userId.Value, CreatorId = userId.Value,
SubscriptionTier = subscriptionTier, SubscriptionTier = subscriptionTier,
Category = category, Category = category,
@@ -26,8 +26,8 @@ namespace OnlyPrompt.Backend.Controllers
{ {
} }
[HttpPut("{userId}/{level?}")] [HttpPut("{userId}/{level}")]
public async Task<Results<Ok, BadRequest<string>, NotFound<string>>> SubscribeAsync([FromRoute(Name = "userId")] Identifier subscribeToId, int? level = null) public async Task<Results<Ok, BadRequest<string>, NotFound<string>>> SubscribeAsync(Identifier subscribeToId, int? level = null)
{ {
var userId = User.GetUserId(); var userId = User.GetUserId();
var subscribeTo = await _db.Users.Include(x => x.SubscriptionTiers.Where(st => st.Level == level)) var subscribeTo = await _db.Users.Include(x => x.SubscriptionTiers.Where(st => st.Level == level))
@@ -46,7 +46,7 @@ namespace OnlyPrompt.Backend.Controllers
return TypedResults.NotFound($"No subscription tier found for user {subscribeToId} with level {level.Value}"); return TypedResults.NotFound($"No subscription tier found for user {subscribeToId} with level {level.Value}");
var existingSubscription = await _db.Subscriptions.FirstOrDefaultAsync( var existingSubscription = await _db.Subscriptions.FirstOrDefaultAsync(
sub => (subscribeToId.Id.HasValue ? sub.SubscribedToId == subscribeToId.Id.Value : sub.SubscribedTo.Profile.Slug == subscribeToId.Slug) sub => subscribeToId.Id.HasValue ? sub.SubscribedToId == subscribeToId.Id.Value : sub.SubscribedTo.Profile.Slug == subscribeToId.Slug
&& sub.SubscriberId == userId && sub.SubscriberId == userId
); );
@@ -86,12 +86,12 @@ namespace OnlyPrompt.Backend.Controllers
} }
[HttpGet("{userId}")] [HttpGet("{userId}")]
public async Task<ApiSubscription?> GetCurrentSubscriptionAsync([FromRoute(Name = "userId")] Identifier subscribeToId) public async Task<ApiSubscription?> GetCurrentSubscriptionAsync(Identifier subscribeToId)
{ {
var userId = User.GetUserId(); var userId = User.GetUserId();
var subscription = await _db.Subscriptions var subscription = await _db.Subscriptions
.Where( .Where(
sub => (subscribeToId.Id.HasValue ? sub.SubscribedToId == subscribeToId.Id.Value : sub.SubscribedTo.Profile.Slug == subscribeToId.Slug) sub => subscribeToId.Id.HasValue ? sub.SubscribedToId == subscribeToId.Id.Value : sub.SubscribedTo.Profile.Slug == subscribeToId.Slug
&& sub.SubscriberId == userId && sub.SubscriberId == userId
) )
.ProjectTo<ApiSubscription>(_mapper.ConfigurationProvider) .ProjectTo<ApiSubscription>(_mapper.ConfigurationProvider)
@@ -101,12 +101,12 @@ namespace OnlyPrompt.Backend.Controllers
} }
[HttpDelete("{userId}")] [HttpDelete("{userId}")]
public async Task<Results<Ok, NotFound<string>>> UnsubscribeAsync([FromRoute(Name = "userId")] Identifier subscribeToId) public async Task<Results<Ok, NotFound<string>>> UnsubscribeAsync(Identifier subscribeToId)
{ {
var userId = User.GetUserId(); var userId = User.GetUserId();
var count = await _db.Subscriptions var count = await _db.Subscriptions
.Where( .Where(
sub => (subscribeToId.Id.HasValue ? sub.SubscribedToId == subscribeToId.Id.Value : sub.SubscribedTo.Profile.Slug == subscribeToId.Slug) sub => subscribeToId.Id.HasValue ? sub.SubscribedToId == subscribeToId.Id.Value : sub.SubscribedTo.Profile.Slug == subscribeToId.Slug
&& sub.SubscriberId == userId && sub.SubscriberId == userId
) )
.ExecuteDeleteAsync(); .ExecuteDeleteAsync();
@@ -1,15 +0,0 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace OnlyPrompt.Backend.Database.Models
{
public class PromptLikeModel
{
[ForeignKey(nameof(Prompt))]
public Guid PromptId { get; set; }
public virtual PromptModel Prompt { get; set; }
[ForeignKey(nameof(User))]
public Guid UserId { get; set; }
public virtual UserModel User { get; set; }
}
}
@@ -25,17 +25,12 @@ namespace OnlyPrompt.Backend.Database.Models
[MaxLength(200)] [MaxLength(200)]
public required string Title { get; set; } public required string Title { get; set; }
[MaxLength(4000)]
public required string Prompt { get; set; } public required string Prompt { get; set; }
[MaxLength(1000)] [MaxLength(1000)]
public required string Description { get; set; } public required string Description { get; set; }
public string? ExampleOutput { get; set; }
public string? ExampleImageUrl { get; set; }
public decimal? Price { get; set; }
[MaxLength(ModelConstants.MaxSlugLength)] [MaxLength(ModelConstants.MaxSlugLength)]
[Column(TypeName = "citext")] [Column(TypeName = "citext")]
public required string Slug { get; set; } public required string Slug { get; set; }
@@ -46,7 +41,5 @@ namespace OnlyPrompt.Backend.Database.Models
[DeleteBehavior(DeleteBehavior.SetNull)] [DeleteBehavior(DeleteBehavior.SetNull)]
public virtual SubscriptionTierModel? SubscriptionTier { get; set; } public virtual SubscriptionTierModel? SubscriptionTier { get; set; }
public virtual IList<ReviewModel> Reviews { get; set; } = new List<ReviewModel>(); public virtual IList<ReviewModel> Reviews { get; set; } = new List<ReviewModel>();
public virtual IList<PromptLikeModel> Likes { get; set; } = new List<PromptLikeModel>();
public virtual IList<PromptSaveModel> Saves { get; set; } = new List<PromptSaveModel>();
} }
} }
@@ -1,15 +0,0 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace OnlyPrompt.Backend.Database.Models
{
public class PromptSaveModel
{
[ForeignKey(nameof(Prompt))]
public Guid PromptId { get; set; }
public virtual PromptModel Prompt { get; set; }
[ForeignKey(nameof(User))]
public Guid UserId { get; set; }
public virtual UserModel User { get; set; }
}
}
@@ -24,6 +24,6 @@ namespace OnlyPrompt.Backend.Database.Models
public string? Specialities { get; set; } public string? Specialities { get; set; }
public virtual UserModel User { get; set; } public virtual UserModel User { get; set; }
public bool IsPublic { get; set; } = true; public bool IsPublic { get; set; } = false;
} }
} }
@@ -14,8 +14,6 @@ namespace OnlyPrompt.Backend.Database
public DbSet<SubscriptionTierModel> SubscriptionTiers { get; set; } public DbSet<SubscriptionTierModel> SubscriptionTiers { get; set; }
public DbSet<SubscriptionModel> Subscriptions { get; set; } public DbSet<SubscriptionModel> Subscriptions { get; set; }
public DbSet<ReviewModel> Reviews { get; set; } public DbSet<ReviewModel> Reviews { get; set; }
public DbSet<PromptLikeModel> PromptLikes { get; set; }
public DbSet<PromptSaveModel> PromptSaves { get; set; }
public OnlyPromptContext(DbContextOptions<OnlyPromptContext> options) : base(options) public OnlyPromptContext(DbContextOptions<OnlyPromptContext> options) : base(options)
{ {
@@ -88,36 +86,6 @@ namespace OnlyPrompt.Backend.Database
.HasForeignKey(e => e.SubscriptionTierId) .HasForeignKey(e => e.SubscriptionTierId)
.OnDelete(DeleteBehavior.SetNull); .OnDelete(DeleteBehavior.SetNull);
}); });
modelBuilder.Entity<PromptLikeModel>(entity =>
{
entity.HasKey(e => new { e.PromptId, e.UserId });
entity.HasOne(e => e.Prompt)
.WithMany(p => p.Likes)
.HasForeignKey(e => e.PromptId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasOne(e => e.User)
.WithMany()
.HasForeignKey(e => e.UserId)
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<PromptSaveModel>(entity =>
{
entity.HasKey(e => new { e.PromptId, e.UserId });
entity.HasOne(e => e.Prompt)
.WithMany(p => p.Saves)
.HasForeignKey(e => e.PromptId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasOne(e => e.User)
.WithMany()
.HasForeignKey(e => e.UserId)
.OnDelete(DeleteBehavior.Cascade);
});
} }
} }
} }
@@ -1,48 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace OnlyPrompt.Backend.Migrations
{
/// <inheritdoc />
public partial class PromptCreateDetails : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ExampleImageUrl",
table: "Prompts",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ExampleOutput",
table: "Prompts",
type: "text",
nullable: true);
migrationBuilder.AddColumn<decimal>(
name: "Price",
table: "Prompts",
type: "numeric",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ExampleImageUrl",
table: "Prompts");
migrationBuilder.DropColumn(
name: "ExampleOutput",
table: "Prompts");
migrationBuilder.DropColumn(
name: "Price",
table: "Prompts");
}
}
}
@@ -1,51 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace OnlyPrompt.Backend.Migrations
{
/// <inheritdoc />
public partial class PromptLikes : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "PromptLikes",
columns: table => new
{
PromptId = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PromptLikes", x => new { x.PromptId, x.UserId });
table.ForeignKey(
name: "FK_PromptLikes_Prompts_PromptId",
column: x => x.PromptId,
principalTable: "Prompts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_PromptLikes_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_PromptLikes_UserId",
table: "PromptLikes",
column: "UserId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "PromptLikes");
}
}
}
@@ -1,51 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace OnlyPrompt.Backend.Migrations
{
/// <inheritdoc />
public partial class PromptSaves : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "PromptSaves",
columns: table => new
{
PromptId = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PromptSaves", x => new { x.PromptId, x.UserId });
table.ForeignKey(
name: "FK_PromptSaves_Prompts_PromptId",
column: x => x.PromptId,
principalTable: "Prompts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_PromptSaves_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_PromptSaves_UserId",
table: "PromptSaves",
column: "UserId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "PromptSaves");
}
}
}
@@ -79,18 +79,10 @@ namespace OnlyPrompt.Backend.Migrations
.HasMaxLength(1000) .HasMaxLength(1000)
.HasColumnType("character varying(1000)"); .HasColumnType("character varying(1000)");
b.Property<string>("ExampleImageUrl")
.HasColumnType("text");
b.Property<string>("ExampleOutput")
.HasColumnType("text");
b.Property<decimal?>("Price")
.HasColumnType("numeric");
b.Property<string>("Prompt") b.Property<string>("Prompt")
.IsRequired() .IsRequired()
.HasColumnType("text"); .HasMaxLength(4000)
.HasColumnType("character varying(4000)");
b.Property<string>("Slug") b.Property<string>("Slug")
.IsRequired() .IsRequired()
-106
View File
@@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Rewrite; using Microsoft.AspNetCore.Rewrite;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.Identity.Web; using Microsoft.Identity.Web;
@@ -25,8 +24,6 @@ builder.Services.AddDbContext<OnlyPromptContext>(opts =>
{ {
opts.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")); opts.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"));
opts.UseLazyLoadingProxies(); opts.UseLazyLoadingProxies();
opts.ConfigureWarnings(warnings =>
warnings.Ignore(RelationalEventId.PendingModelChangesWarning));
}); });
builder.Services.AddSingleton<IPasswordHasher<UserModel>, PasswordHasher<UserModel>>(); builder.Services.AddSingleton<IPasswordHasher<UserModel>, PasswordHasher<UserModel>>();
@@ -83,7 +80,6 @@ var rewrite = new RewriteOptions()
.AddRewrite(@"^(?!scalar\/?|api\/?)([^.]+)$", "$1.html", skipRemainingRules: true); .AddRewrite(@"^(?!scalar\/?|api\/?)([^.]+)$", "$1.html", skipRemainingRules: true);
app.UseRewriter(rewrite); app.UseRewriter(rewrite);
app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {
@@ -101,111 +97,9 @@ else
} }
app.MapControllers(); app.MapControllers();
app.MapGet("/", async (HttpContext context) =>
{
var authResult = await context.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
return authResult.Succeeded
? Results.Redirect("/dashboard")
: Results.Redirect("/login");
});
app.MapFallbackToFile("/login.html"); app.MapFallbackToFile("/login.html");
using var scope = app.Services.CreateScope(); using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OnlyPromptContext>(); var db = scope.ServiceProvider.GetRequiredService<OnlyPromptContext>();
await db.Database.MigrateAsync(); await db.Database.MigrateAsync();
await EnsurePromptDetailColumnsAsync(db);
await EnsurePromptLikesTableAsync(db);
await EnsurePromptSavesTableAsync(db);
await SeedDefaultCategoriesAsync(db);
app.Run(); app.Run();
static async Task EnsurePromptDetailColumnsAsync(OnlyPromptContext db)
{
await db.Database.ExecuteSqlRawAsync("""
ALTER TABLE "Prompts"
ADD COLUMN IF NOT EXISTS "ExampleImageUrl" text;
""");
await db.Database.ExecuteSqlRawAsync("""
ALTER TABLE "Prompts"
ADD COLUMN IF NOT EXISTS "ExampleOutput" text;
""");
await db.Database.ExecuteSqlRawAsync("""
ALTER TABLE "Prompts"
ADD COLUMN IF NOT EXISTS "Price" numeric;
""");
await db.Database.ExecuteSqlRawAsync("""
ALTER TABLE "Prompts"
ALTER COLUMN "Prompt" TYPE text;
""");
await db.Database.ExecuteSqlRawAsync("""
ALTER TABLE "Prompts"
ALTER COLUMN "ExampleOutput" TYPE text;
""");
}
static async Task EnsurePromptLikesTableAsync(OnlyPromptContext db)
{
await db.Database.ExecuteSqlRawAsync("""
CREATE TABLE IF NOT EXISTS "PromptLikes" (
"PromptId" uuid NOT NULL,
"UserId" uuid NOT NULL,
CONSTRAINT "PK_PromptLikes" PRIMARY KEY ("PromptId", "UserId"),
CONSTRAINT "FK_PromptLikes_Prompts_PromptId" FOREIGN KEY ("PromptId") REFERENCES "Prompts" ("Id") ON DELETE CASCADE,
CONSTRAINT "FK_PromptLikes_Users_UserId" FOREIGN KEY ("UserId") REFERENCES "Users" ("Id") ON DELETE CASCADE
);
""");
await db.Database.ExecuteSqlRawAsync("""
CREATE INDEX IF NOT EXISTS "IX_PromptLikes_UserId" ON "PromptLikes" ("UserId");
""");
}
static async Task EnsurePromptSavesTableAsync(OnlyPromptContext db)
{
await db.Database.ExecuteSqlRawAsync("""
CREATE TABLE IF NOT EXISTS "PromptSaves" (
"PromptId" uuid NOT NULL,
"UserId" uuid NOT NULL,
CONSTRAINT "PK_PromptSaves" PRIMARY KEY ("PromptId", "UserId"),
CONSTRAINT "FK_PromptSaves_Prompts_PromptId" FOREIGN KEY ("PromptId") REFERENCES "Prompts" ("Id") ON DELETE CASCADE,
CONSTRAINT "FK_PromptSaves_Users_UserId" FOREIGN KEY ("UserId") REFERENCES "Users" ("Id") ON DELETE CASCADE
);
""");
await db.Database.ExecuteSqlRawAsync("""
CREATE INDEX IF NOT EXISTS "IX_PromptSaves_UserId" ON "PromptSaves" ("UserId");
""");
}
static async Task SeedDefaultCategoriesAsync(OnlyPromptContext db)
{
var defaults = new[]
{
("creative-writing", "Creative Writing"),
("coding", "Coding"),
("art", "Art"),
("marketing", "Marketing"),
("video", "Video"),
("data", "Data")
};
foreach (var (slug, name) in defaults)
{
if (await db.Categories.AnyAsync(c => c.Slug == slug))
continue;
db.Categories.Add(new CategoryModel
{
Id = Guid.CreateVersion7(),
Slug = slug,
Name = name,
Description = $"{name} prompts"
});
}
await db.SaveChangesAsync();
}
+1 -19
View File
@@ -33,36 +33,18 @@ namespace OnlyPrompt.Backend.Utils
.MapCtorParamFrom(x => x.Description, x => x.Description) .MapCtorParamFrom(x => x.Description, x => x.Description)
.MapCtorParamFrom(x => x.Content, x => x.Prompt) .MapCtorParamFrom(x => x.Content, x => x.Prompt)
.MapCtorParamFrom(x => x.TimeStamp, x => x.UpdatedAt) .MapCtorParamFrom(x => x.TimeStamp, x => x.UpdatedAt)
.MapCtorParamFrom(x => x.CategoryName, x => x.Category.Name)
.MapCtorParamFrom(x => x.CategorySlug, x => x.Category.Slug)
.MapCtorParamFrom(x => x.ExampleOutput, x => x.ExampleOutput)
.MapCtorParamFrom(x => x.ExampleImageUrl, x => x.ExampleImageUrl)
.MapCtorParamFrom(x => x.Price, x => x.Price)
.MapCtorParamFrom(x => x.LikeCount, x => x.Likes.Count)
.MapCtorParamFrom(x => x.IsLiked, x => false)
.MapCtorParamFrom(x => x.SaveCount, x => x.Saves.Count)
.MapCtorParamFrom(x => x.IsSaved, x => false)
.MapCtorParamFrom(x => x.TierLevel, x => x.SubscriptionTier == null ? (int?)null : x.SubscriptionTier.Level) .MapCtorParamFrom(x => x.TierLevel, x => x.SubscriptionTier == null ? (int?)null : x.SubscriptionTier.Level)
.MapCtorParamFrom(x => x.TierName, x => x.SubscriptionTier == null ? null : x.SubscriptionTier.Name) .MapCtorParamFrom(x => x.TierName, x => x.SubscriptionTier == null ? null : x.SubscriptionTier.Name)
.MapCtorParamFrom(x => x.CreatorName, x => x.Creator.Profile.DisplayName) .MapCtorParamFrom(x => x.CreatorName, x => x.Creator.Profile.DisplayName)
.MapCtorParamFrom(x => x.CreatorId, x => x.CreatorId) .MapCtorParamFrom(x => x.CreatorId, x => x.CreatorId)
.MapCtorParamFrom(x => x.AverageRating, x => x.Reviews.Average(r => (double?)r.Rating)) .MapCtorParamFrom(x => x.AverageRating, x => x.Reviews.Average(r => (double?)r.Rating));
.MapCtorParamFrom(x => x.CanAccess, x => false);
config.CreateMap<PromptModel, ApiMinimalPrompt>() config.CreateMap<PromptModel, ApiMinimalPrompt>()
.MapCtorParamFrom(x => x.Id, x => x.Id) .MapCtorParamFrom(x => x.Id, x => x.Id)
.MapCtorParamFrom(x => x.Title, x => x.Title) .MapCtorParamFrom(x => x.Title, x => x.Title)
.MapCtorParamFrom(x => x.Description, x => x.Description)
.MapCtorParamFrom(x => x.CreatorName, x => x.Creator.Profile.DisplayName) .MapCtorParamFrom(x => x.CreatorName, x => x.Creator.Profile.DisplayName)
.MapCtorParamFrom(x => x.CreatorAvatarUrl, x => x.Creator.Profile.AvatarUrl)
.MapCtorParamFrom(x => x.TimeStamp, x => x.UpdatedAt) .MapCtorParamFrom(x => x.TimeStamp, x => x.UpdatedAt)
.MapCtorParamFrom(x => x.CreatorId, x => x.CreatorId) .MapCtorParamFrom(x => x.CreatorId, x => x.CreatorId)
.MapCtorParamFrom(x => x.ExampleImageUrl, x => x.ExampleImageUrl)
.MapCtorParamFrom(x => x.Price, x => x.Price)
.MapCtorParamFrom(x => x.LikeCount, x => x.Likes.Count)
.MapCtorParamFrom(x => x.IsLiked, x => false)
.MapCtorParamFrom(x => x.SaveCount, x => x.Saves.Count)
.MapCtorParamFrom(x => x.IsSaved, x => false)
.MapCtorParamFrom(x => x.TierLevel, x => x.SubscriptionTier == null ? (int?)null : x.SubscriptionTier.Level) .MapCtorParamFrom(x => x.TierLevel, x => x.SubscriptionTier == null ? (int?)null : x.SubscriptionTier.Level)
.MapCtorParamFrom(x => x.TierName, x => x.SubscriptionTier == null ? null : x.SubscriptionTier.Name) .MapCtorParamFrom(x => x.TierName, x => x.SubscriptionTier == null ? null : x.SubscriptionTier.Name)
.MapCtorParamFrom(x => x.AverageRating, x => x.Reviews.Average(r => (double?)r.Rating)) .MapCtorParamFrom(x => x.AverageRating, x => x.Reviews.Average(r => (double?)r.Rating))
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Include Error Detail=true;User ID=onlyprompt;Password=onlyprompt;Host=localhost;Port=2803;Database=onlyprompt;Pooling=true;MinPoolSize=0;MaxPoolSize=100;Connection Lifetime=0;" "DefaultConnection": "Include Error Detail=true;User ID=onlyprompt;Password=onlyprompt;Host=localhost;Port=1803;Database=onlyprompt;Pooling=true;MinPoolSize=0;MaxPoolSize=100;Connection Lifetime=0;"
}, },
"Jwt": { "Jwt": {
"Issuer": "https://onlyprompts.com", "Issuer": "https://onlyprompts.com",
+2 -3
View File
@@ -13,7 +13,6 @@
<link rel="stylesheet" href="../css/login.css"> <link rel="stylesheet" href="../css/login.css">
<link rel="stylesheet" href="../css/topbar.css"> <link rel="stylesheet" href="../css/topbar.css">
<link rel="stylesheet" href="../css/chats.css"> <link rel="stylesheet" href="../css/chats.css">
<script src="../js/profile-shared.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
</head> </head>
<body> <body>
@@ -109,7 +108,7 @@
</div> </div>
<script> <script>
fetch('/sidebar.html') fetch('../html/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
@@ -122,7 +121,7 @@
if (chatsLink) chatsLink.classList.add('active'); if (chatsLink) chatsLink.classList.add('active');
}); });
fetch('/topbar.html') fetch('../html/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
</script> </script>
+108 -151
View File
@@ -1,5 +1,5 @@
<!-- OnlyPrompt - Community page: <!-- OnlyPrompt - Marketplace page:
- Discover creators, follow/unfollow, dynamic via API --> - Browse and filter AI prompts with buy/view details buttons and pricing -->
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
@@ -13,7 +13,6 @@
<link rel="stylesheet" href="../css/login.css"> <link rel="stylesheet" href="../css/login.css">
<link rel="stylesheet" href="../css/topbar.css"> <link rel="stylesheet" href="../css/topbar.css">
<link rel="stylesheet" href="../css/community.css"> <link rel="stylesheet" href="../css/community.css">
<script src="../js/profile-shared.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
</head> </head>
<body> <body>
@@ -27,178 +26,136 @@
<main class="creators-main"> <main class="creators-main">
<!-- Header / Titel -->
<div class="creators-header"> <div class="creators-header">
<h1>Discover Creators</h1> <h1>Discover Creators</h1>
<p>Follow your favorite prompt artists and get inspired.</p> <p>Follow your favorite prompt artists and get inspired.</p>
</div> </div>
<!-- Filter Buttons -->
<div class="filter-buttons"> <div class="filter-buttons">
<button class="filter-btn active" data-sort="popular">Popular</button> <button class="filter-btn active">Popular</button>
<button class="filter-btn" data-sort="prompts">Rising</button> <button class="filter-btn">Rising</button>
<button class="filter-btn" data-sort="new">New</button> <button class="filter-btn">New</button>
<button class="filter-btn" data-sort="rating">Top Rated</button> <button class="filter-btn">Top Rated</button>
</div> </div>
<div class="creators-grid" id="creators-grid"></div> <!-- Creators Grid -->
<div class="creators-grid">
<div id="creators-empty" style="display:none; text-align:center; padding:60px 20px; color:#64748b;"> <!-- Creator Card 1 -->
<i class="bi bi-people" style="font-size:3rem; display:block; margin-bottom:16px;"></i> <div class="creator-card">
<h3 id="creators-empty-title" style="margin-bottom:8px;">No creators found</h3> <img src="../images/content/creator1.png" alt="Sarah Jenkins" class="creator-avatar">
<p id="creators-empty-text">Check back later for new creators to follow.</p> <div class="creator-info">
</div> <h3 class="creator-name">Sarah Jenkins</h3>
<div class="creator-handle">@sarahj</div>
<p class="creator-bio">AI Explorer | Prompt Curator | Exploring creativity through generative AI.</p>
<div class="creator-stats">
<span><i class="bi bi-puzzle"></i> 42 prompts</span>
<span><i class="bi bi-star-fill"></i> 4.9</span>
</div>
<button class="follow-btn">Follow</button>
</div>
</div>
<!-- Creator Card 2 -->
<div class="creator-card">
<img src="../images/content/creator2.png" alt="Alex Chen" class="creator-avatar">
<div class="creator-info">
<h3 class="creator-name">Alex Chen</h3>
<div class="creator-handle">@alexchen</div>
<p class="creator-bio">Digital artist & prompt engineer. Creating surreal landscapes.</p>
<div class="creator-stats">
<span><i class="bi bi-puzzle"></i> 87 prompts</span>
<span><i class="bi bi-star-fill"></i> 4.8</span>
</div>
<button class="follow-btn">Follow</button>
</div>
</div>
<!-- Creator Card 3 -->
<div class="creator-card">
<img src="../images/content/creator3.png" alt="Mia Wong" class="creator-avatar">
<div class="creator-info">
<h3 class="creator-name">Mia Wong</h3>
<div class="creator-handle">@miawong</div>
<p class="creator-bio">Midjourney master | UI/UX prompts | Design systems.</p>
<div class="creator-stats">
<span><i class="bi bi-puzzle"></i> 124 prompts</span>
<span><i class="bi bi-star-fill"></i> 5.0</span>
</div>
<button class="follow-btn">Follow</button>
</div>
</div>
<!-- Creator Card 4 -->
<div class="creator-card">
<img src="../images/content/creator4.png" alt="Tom Rivera" class="creator-avatar">
<div class="creator-info">
<h3 class="creator-name">Tom Rivera</h3>
<div class="creator-handle">@tomrivera</div>
<p class="creator-bio">3D artist | Character design | Sci-fi & fantasy prompts.</p>
<div class="creator-stats">
<span><i class="bi bi-puzzle"></i> 33 prompts</span>
<span><i class="bi bi-star-fill"></i> 4.7</span>
</div>
<button class="follow-btn">Follow</button>
</div>
</div>
<!-- Creator Card 5 -->
<div class="creator-card">
<img src="../images/content/creator5.png" alt="Emma Watson" class="creator-avatar">
<div class="creator-info">
<h3 class="creator-name">Emma Watson</h3>
<div class="creator-handle">@emmawatson</div>
<p class="creator-bio">Watercolor & pet portraits | Whimsical art prompts.</p>
<div class="creator-stats">
<span><i class="bi bi-puzzle"></i> 56 prompts</span>
<span><i class="bi bi-star-fill"></i> 4.9</span>
</div>
<button class="follow-btn">Follow</button>
</div>
</div>
<!-- Creator Card 6 -->
<div class="creator-card">
<img src="../images/content/creator6.png" alt="Liam O'Brien" class="creator-avatar">
<div class="creator-info">
<h3 class="creator-name">Liam O'Brien</h3>
<div class="creator-handle">@liamob</div>
<p class="creator-bio">Minimalist logo designer | Brand identity prompts.</p>
<div class="creator-stats">
<span><i class="bi bi-puzzle"></i> 28 prompts</span>
<span><i class="bi bi-star-fill"></i> 4.6</span>
</div>
<button class="follow-btn">Follow</button>
</div>
</div>
<div id="creators-error" style="display:none; text-align:center; padding:60px 20px; color:#ef4444;">
<i class="bi bi-exclamation-circle" style="font-size:3rem; display:block; margin-bottom:16px;"></i>
<h3 style="margin-bottom:8px;">Could not load creators</h3>
<p id="creators-error-msg"></p>
</div> </div>
</main> </main>
</div> </div>
</div> </div>
<script type="module"> <script>
// ── Sidebar & Topbar ───────────────────────────────────────────── fetch('../html/sidebar.html')
fetch('/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
document.querySelectorAll('#sidebar-container .sidebar a').forEach(l => l.classList.remove('active')); // Remove 'active' from all sidebar links
document.querySelectorAll('#sidebar-container .sidebar a').forEach(link => {
link.classList.remove('active');
});
// Set 'active' on the third link (Community)
const thirdLink = document.querySelectorAll('#sidebar-container .sidebar li a')[2]; const thirdLink = document.querySelectorAll('#sidebar-container .sidebar li a')[2];
if (thirdLink) thirdLink.classList.add('active'); if (thirdLink) thirdLink.classList.add('active');
}); });
fetch('/topbar.html')
fetch('../html/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
// ── Helpers ──────────────────────────────────────────────────────
function renderStars(rating) {
if (!rating) return '';
const stars = Math.round(rating);
return `<span style="color:#f59e0b">${'★'.repeat(stars)}${'☆'.repeat(5 - stars)}</span> <span style="color:#64748b;font-size:0.8rem">${rating.toFixed(1)}</span>`;
}
function renderCard(c) {
return `
<div class="creator-card">
<img class="creator-avatar"
src="${c.avatarUrl || '../images/content/cat.png'}"
alt="${c.displayName}"
style="cursor:pointer"
onclick="location.href='/profile?id=${c.userId}'">
<div class="creator-info">
<h3 class="creator-name"
style="cursor:pointer"
onclick="location.href='/profile?id=${c.userId}'">${c.displayName}</h3>
<div class="creator-handle">@${c.slug}</div>
<p class="creator-bio">${c.bio ?? 'No bio yet.'}</p>
<div class="creator-stats">
<span><i class="bi bi-puzzle"></i> ${c.promptCount} prompts</span>
<span><i class="bi bi-people"></i> ${c.subscribers}</span>
${c.averageRating > 0 ? `<span>${renderStars(c.averageRating)}</span>` : ''}
</div>
<button class="follow-btn ${c.isFollowing ? 'following' : ''}"
data-userid="${c.userId}"
data-following="${c.isFollowing}">
${c.isFollowing ? 'Following' : 'Follow'}
</button>
</div>
</div>`;
}
// ── Follow / Unfollow ────────────────────────────────────────────
async function toggleFollow(btn) {
const userId = btn.dataset.userid;
const isFollowing = btn.dataset.following === 'true';
btn.disabled = true;
const res = await fetch(`/api/v1/subscriptions/${userId}`, {
method: isFollowing ? 'DELETE' : 'PUT',
credentials: 'same-origin'
});
if (res.status === 401) { location.href = '/login'; return; }
if (res.ok) {
const nowFollowing = !isFollowing;
btn.dataset.following = nowFollowing;
btn.textContent = nowFollowing ? 'Following' : 'Follow';
btn.classList.toggle('following', nowFollowing);
}
btn.disabled = false;
}
// ── Load Creators ────────────────────────────────────────────────
const grid = document.getElementById('creators-grid');
const emptyEl = document.getElementById('creators-empty');
const emptyTitle = document.getElementById('creators-empty-title');
const emptyText = document.getElementById('creators-empty-text');
const errorEl = document.getElementById('creators-error');
const errorMsg = document.getElementById('creators-error-msg');
let activeSort = 'popular';
let currentSearch = new URLSearchParams(location.search).get('search') || '';
function getSearchTerm() {
return currentSearch.trim();
}
async function loadCreators(sort = activeSort) {
activeSort = sort;
grid.innerHTML = '';
emptyEl.style.display = 'none';
errorEl.style.display = 'none';
try {
const params = new URLSearchParams({
sort,
limit: '50'
});
const search = getSearchTerm();
if (search) params.set('search', search);
const res = await fetch(`/api/v1/profiles?${params}`);
if (res.status === 401) { location.href = '/login'; return; }
if (!res.ok) throw new Error(`Server error ${res.status}`);
const creators = await res.json();
if (creators.length === 0) {
const search = getSearchTerm();
emptyTitle.textContent = search ? 'No matching creators' : 'No creators found';
emptyText.textContent = search
? `No creator matches "${search}". Try another name or clear the search.`
: 'Create another local user to see creators here.';
emptyEl.style.display = 'block';
return;
}
grid.innerHTML = creators.map(renderCard).join('');
grid.querySelectorAll('.follow-btn').forEach(btn => {
btn.addEventListener('click', () => toggleFollow(btn));
});
} catch (e) {
errorEl.style.display = 'block';
errorMsg.textContent = e.message;
}
}
// ── Filter buttons ───────────────────────────────────────────────
document.querySelectorAll('.filter-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
loadCreators(btn.dataset.sort);
});
});
window.applyCreatorSearch = (value) => {
currentSearch = value.trim();
loadCreators(activeSort);
};
loadCreators();
</script> </script>
</body> </body>
</html> </html>
+10 -135
View File
@@ -13,7 +13,6 @@
<link rel="stylesheet" href="../css/login.css"> <link rel="stylesheet" href="../css/login.css">
<link rel="stylesheet" href="../css/topbar.css"> <link rel="stylesheet" href="../css/topbar.css">
<link rel="stylesheet" href="../css/create.css"> <link rel="stylesheet" href="../css/create.css">
<script src="../js/profile-shared.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
</head> </head>
<body> <body>
@@ -28,8 +27,8 @@
<main class="create-main"> <main class="create-main">
<div class="create-container"> <div class="create-container">
<div class="create-header"> <div class="create-header">
<h1 id="create-title">Create AI Prompt</h1> <h1>Create AI Prompt</h1>
<p id="create-subtitle">Design and save custom prompts for your AI workflows.</p> <p>Design and save custom prompts for your AI workflows.</p>
</div> </div>
<form id="createPromptForm" class="create-form" enctype="multipart/form-data"> <form id="createPromptForm" class="create-form" enctype="multipart/form-data">
@@ -96,10 +95,9 @@
<!-- Submit Button --> <!-- Submit Button -->
<div class="form-actions"> <div class="form-actions">
<button type="submit" class="submit-btn" id="submitPromptBtn">Publish Prompt</button> <button type="submit" class="submit-btn">Publish Prompt</button>
<button type="button" class="cancel-btn">Cancel</button> <button type="button" class="cancel-btn">Cancel</button>
</div> </div>
<p id="create-status" style="text-align:center;color:#64748b;margin:0;"></p>
</form> </form>
</div> </div>
</main> </main>
@@ -112,8 +110,6 @@
const paidBtn = document.getElementById('paidBtn'); const paidBtn = document.getElementById('paidBtn');
const priceField = document.getElementById('priceField'); const priceField = document.getElementById('priceField');
const priceInput = document.getElementById('price'); const priceInput = document.getElementById('price');
const editPromptId = new URLSearchParams(location.search).get('id');
const submitPromptBtn = document.getElementById('submitPromptBtn');
freeBtn.addEventListener('click', () => { freeBtn.addEventListener('click', () => {
freeBtn.classList.add('active'); freeBtn.classList.add('active');
@@ -132,7 +128,6 @@
const imageInput = document.getElementById('exampleImage'); const imageInput = document.getElementById('exampleImage');
const imagePreview = document.getElementById('imagePreview'); const imagePreview = document.getElementById('imagePreview');
const previewImg = document.getElementById('previewImg'); const previewImg = document.getElementById('previewImg');
let exampleImageUrl = '';
if (imageInput) { if (imageInput) {
imageInput.addEventListener('change', function(event) { imageInput.addEventListener('change', function(event) {
@@ -140,150 +135,32 @@
if (file && (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg')) { if (file && (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg')) {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = function(e) { reader.onload = function(e) {
exampleImageUrl = e.target.result; previewImg.src = e.target.result;
previewImg.src = exampleImageUrl;
imagePreview.style.display = 'block'; imagePreview.style.display = 'block';
}; };
reader.readAsDataURL(file); reader.readAsDataURL(file);
} else { } else {
imagePreview.style.display = 'none'; imagePreview.style.display = 'none';
previewImg.src = '#'; previewImg.src = '#';
exampleImageUrl = '';
if (file) alert('Please upload a PNG or JPG image.'); if (file) alert('Please upload a PNG or JPG image.');
} }
}); });
} }
async function loadCategories() { // Handle form submission (demo only)
const categorySelect = document.getElementById('category'); document.getElementById('createPromptForm').addEventListener('submit', (e) => {
try {
const response = await fetch('/api/v1/categories/minimal');
if (!response.ok) return;
const categories = await response.json();
if (!categories.length) return;
categorySelect.innerHTML = categories
.map((category) => `<option value="${category.slug}">${category.name}</option>`)
.join('');
} catch {
// Keep the static fallback categories.
}
}
async function loadPromptForEdit() {
if (!editPromptId) return;
document.getElementById('create-title').textContent = 'Edit AI Prompt';
document.getElementById('create-subtitle').textContent = 'Update your published prompt.';
submitPromptBtn.textContent = 'Save Changes';
const status = document.getElementById('create-status');
status.textContent = 'Loading prompt...';
try {
const response = await fetch(`/api/v1/prompts/${editPromptId}`);
if (response.status === 401) {
location.href = '/login';
return;
}
if (!response.ok) throw new Error('Prompt could not be loaded.');
const prompt = await response.json();
document.getElementById('title').value = prompt.title || '';
document.getElementById('description').value = prompt.description || '';
document.getElementById('category').value = prompt.categorySlug || document.getElementById('category').value;
document.getElementById('promptContent').value = prompt.content || '';
document.getElementById('exampleOutput').value = prompt.exampleOutput || '';
exampleImageUrl = prompt.exampleImageUrl || '';
if (exampleImageUrl) {
previewImg.src = exampleImageUrl;
imagePreview.style.display = 'block';
}
if (prompt.price != null && Number(prompt.price) > 0) {
paidBtn.click();
priceInput.value = Number(prompt.price);
} else {
freeBtn.click();
}
status.textContent = '';
} catch (error) {
status.textContent = error.message;
}
}
// Handle form submission
document.getElementById('createPromptForm').addEventListener('submit', async (e) => {
e.preventDefault(); e.preventDefault();
const status = document.getElementById('create-status'); alert('Prompt published! (Demo)');
const submitBtn = document.querySelector('.submit-btn'); // Here you would normally send data to a backend (including the image file)
status.textContent = editPromptId ? 'Saving...' : 'Publishing...';
submitBtn.disabled = true;
try {
const isPaid = paidBtn.classList.contains('active');
const price = isPaid ? Number(priceInput.value || 0) : null;
const payload = {
title: document.getElementById('title').value.trim(),
description: document.getElementById('description').value.trim(),
category: document.getElementById('category').value,
content: document.getElementById('promptContent').value.trim(),
exampleOutput: document.getElementById('exampleOutput').value.trim() || null,
exampleImageUrl: exampleImageUrl || null,
price,
subscriptionTier: null,
slug: null
};
const response = await fetch(editPromptId ? `/api/v1/prompts/${editPromptId}` : '/api/v1/prompts', {
method: editPromptId ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify(payload)
});
if (response.status === 401) {
location.href = '/login';
return;
}
if (!response.ok) {
const error = await response.text();
throw new Error(getCreateErrorMessage(error, response.status));
}
const prompt = await response.json();
location.href = `/post-detail?id=${prompt.id}`;
} catch (error) {
status.textContent = error.message;
submitBtn.disabled = false;
}
}); });
function getCreateErrorMessage(errorText, status) {
if (!errorText) return `Server error ${status}`;
try {
const error = JSON.parse(errorText);
const messages = error.errors
? Object.values(error.errors).flat()
: [error.title || errorText];
return messages.join(' ');
} catch {
return errorText;
}
}
// Cancel button (go back) // Cancel button (go back)
document.querySelector('.cancel-btn').addEventListener('click', () => { document.querySelector('.cancel-btn').addEventListener('click', () => {
window.history.back(); window.history.back();
}); });
// Fetch sidebar and topbar // Fetch sidebar and topbar
fetch('/sidebar.html') fetch('../html/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
@@ -296,11 +173,9 @@
if (createLink) createLink.classList.add('active'); if (createLink) createLink.classList.add('active');
}); });
fetch('/topbar.html') fetch('../html/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
loadCategories().then(loadPromptForEdit);
</script> </script>
</body> </body>
</html> </html>
-10
View File
@@ -137,16 +137,6 @@
.follow-btn:hover { .follow-btn:hover {
opacity: 0.85; opacity: 0.85;
} }
.follow-btn.following {
background: transparent;
border: 2px solid #94a3b8;
color: #64748b;
}
.follow-btn.following:hover {
border-color: #ef4444;
color: #ef4444;
opacity: 1;
}
/* Responsive */ /* Responsive */
@media (max-width: 768px) { @media (max-width: 768px) {
+3 -57
View File
@@ -71,18 +71,16 @@
.post-card { .post-card {
background: #fff; background: #fff;
border-radius: 18px; border-radius: 18px;
box-shadow: 0 2px 8px rgba(59, 130, 246, 0.06); box-shadow: 0 2px 8px rgba(59,130,246,0.06);
overflow: hidden; overflow: hidden;
transition: transition: transform 0.2s, box-shadow 0.2s;
transform 0.2s,
box-shadow 0.2s;
cursor: pointer; cursor: pointer;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
.post-card:hover { .post-card:hover {
transform: translateY(-2px); transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(59, 130, 246, 0.12); box-shadow: 0 8px 20px rgba(59,130,246,0.12);
} }
/* Post Header */ /* Post Header */
@@ -167,15 +165,6 @@
.action-btn i { .action-btn i {
font-size: 1.1rem; font-size: 1.1rem;
} }
.action-btn.active {
font-weight: 700;
}
.like-btn.active {
color: #ef4444;
}
.save-btn.active {
color: #f59e0b;
}
.like-btn:hover { .like-btn:hover {
color: #ef4444; color: #ef4444;
} }
@@ -209,49 +198,6 @@
} }
} }
/* Avatar initials fallback */
.post-avatar-initials {
width: 40px;
height: 40px;
border-radius: 50%;
background: var(--primary, #6366f1);
color: #fff;
font-weight: 700;
font-size: 1rem;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
/* Locked post */
.post-locked {
opacity: 0.75;
}
.post-image-locked {
filter: blur(6px);
pointer-events: none;
}
.post-locked-msg {
color: #94a3b8;
font-size: 0.85rem;
margin: 6px 0 0;
}
/* Star rating */
.post-rating {
display: flex;
align-items: center;
gap: 3px;
color: #f59e0b;
font-size: 0.85rem;
margin-top: 6px;
}
.post-rating span {
color: #64748b;
margin-left: 4px;
}
@media (max-width: 480px) { @media (max-width: 480px) {
.feed-main { .feed-main {
padding: 12px !important; padding: 12px !important;
+5 -33
View File
@@ -99,17 +99,15 @@
.prompt-card { .prompt-card {
background: #fff; background: #fff;
border-radius: 18px; border-radius: 18px;
box-shadow: 0 2px 8px rgba(59, 130, 246, 0.06); box-shadow: 0 2px 8px rgba(59,130,246,0.06);
overflow: hidden; overflow: hidden;
transition: transition: transform 0.2s, box-shadow 0.2s;
transform 0.2s,
box-shadow 0.2s;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
.prompt-card:hover { .prompt-card:hover {
transform: translateY(-2px); transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(59, 130, 246, 0.12); box-shadow: 0 8px 20px rgba(59,130,246,0.12);
} }
.prompt-img { .prompt-img {
@@ -173,8 +171,7 @@
gap: 12px; gap: 12px;
margin-top: 8px; margin-top: 8px;
} }
.buy-btn, .buy-btn, .details-btn {
.details-btn {
flex: 1; flex: 1;
border: none; border: none;
border-radius: 14px; border-radius: 14px;
@@ -192,8 +189,7 @@
background: #f1f5f9; background: #f1f5f9;
color: #334155; color: #334155;
} }
.buy-btn:hover, .buy-btn:hover, .details-btn:hover {
.details-btn:hover {
opacity: 0.85; opacity: 0.85;
} }
@@ -227,27 +223,3 @@
flex-direction: column; flex-direction: column;
} }
} }
/* Payment method buttons */
.pay-method-btn {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
padding: 14px 16px;
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 12px;
font-size: 0.95rem;
font-weight: 600;
color: #1e293b;
cursor: pointer;
transition:
border-color 0.2s,
background 0.2s;
text-align: left;
}
.pay-method-btn:hover {
border-color: #6366f1;
background: #f5f3ff;
}
-21
View File
@@ -40,27 +40,6 @@
border-radius: 14px !important; border-radius: 14px !important;
} }
.profile-tab {
border: none;
background: transparent;
color: #64748b;
cursor: pointer;
font: inherit;
font-weight: 600;
padding: 10px 0;
border-bottom: 2px solid transparent;
font-size: 1rem;
}
.profile-tab.active {
color: #3b82f6;
border-bottom-color: #3b82f6;
}
.profile-tab:hover:not(.active) {
color: #334155;
}
/* Prompt cards: rounded corners */ /* Prompt cards: rounded corners */
.profile-main section > div { .profile-main section > div {
border-radius: 18px !important; border-radius: 18px !important;
-9
View File
@@ -100,22 +100,13 @@
padding-top: 16px; padding-top: 16px;
} }
.sidebar-bottom form {
margin: 0;
}
.sidebar-logout { .sidebar-logout {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
width: 100%;
padding: 12px 16px; padding: 12px 16px;
border: 0;
background: transparent;
cursor: pointer;
text-decoration: none; text-decoration: none;
color: #64748b; color: #64748b;
font: inherit;
font-weight: 600; font-weight: 600;
transition: background 0.2s ease; transition: background 0.2s ease;
} }
+145 -263
View File
@@ -1,284 +1,166 @@
<!-- OnlyPrompt - Feed page: <!-- OnlyPrompt - Feed page:
- Social media style post feed with likes, comments, saves, and share actions (following/foryou tabs) --> - Social media style post feed with likes, comments, saves, and share actions (following/foryou tabs) -->
<!doctype html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OnlyPrompt - Feed</title> <title>OnlyPrompt - Feed</title>
<link rel="stylesheet" href="../css/variables.css" /> <link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/base.css" /> <link rel="stylesheet" href="../css/base.css">
<link rel="stylesheet" href="../css/sidebar.css" /> <link rel="stylesheet" href="../css/sidebar.css">
<link rel="stylesheet" href="../css/login.css" /> <link rel="stylesheet" href="../css/login.css">
<link rel="stylesheet" href="../css/topbar.css" /> <link rel="stylesheet" href="../css/topbar.css">
<link rel="stylesheet" href="../css/dashboard.css" /> <link rel="stylesheet" href="../css/dashboard.css">
<script src="../js/profile-shared.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<link </head>
rel="stylesheet" <body>
href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" <div class="layout" style="display: flex; min-height: 100vh; background: var(--bg);">
/>
</head>
<body>
<div
class="layout"
style="display: flex; min-height: 100vh; background: var(--bg)"
>
<div id="sidebar-container"></div>
<div style="flex: 1; display: flex; flex-direction: column"> <div id="sidebar-container"></div>
<div id="topbar-container"></div>
<main class="feed-main"> <div style="flex:1; margin:40px auto; max-width:950px;">
<!-- Optional: Feed Header -->
<div class="feed-header">
<h1>Feed</h1>
<p>Latest prompts and inspiration from creators you follow</p>
</div>
<!-- Filter Buttons --> <div id="topbar-container"></div>
<div class="filter-buttons">
<button
class="filter-btn active"
data-sort="date"
data-ascending="false"
>
Recent
</button>
<button
class="filter-btn"
data-sort="rating"
data-ascending="false"
>
Top Rated
</button>
<button class="filter-btn" data-sort="date" data-ascending="true">
Oldest
</button>
</div>
<!-- Posts Grid --> <main class="feed-main">
<div class="posts-grid" id="posts-grid"></div>
<!-- Empty State --> <!-- Optional: Feed Header -->
<div <div class="feed-header">
id="feed-empty" <h1>Feed</h1>
style=" <p>Latest prompts and inspiration from creators you follow</p>
display: none; </div>
text-align: center;
padding: 60px 20px;
color: #64748b;
"
>
<i
class="bi bi-inbox"
style="font-size: 3rem; display: block; margin-bottom: 16px"
></i>
<h3 style="margin-bottom: 8px">No posts yet</h3>
<p>Follow some creators to see their prompts here.</p>
</div>
<!-- Error State --> <!-- Filter Buttons (optional) -->
<div <div class="filter-buttons">
id="feed-error" <button class="filter-btn active">For You</button>
style=" <button class="filter-btn">Following</button>
display: none; <button class="filter-btn">Trending</button>
text-align: center; <button class="filter-btn">Recent</button>
padding: 60px 20px; </div>
color: #ef4444;
"
>
<i
class="bi bi-exclamation-circle"
style="font-size: 3rem; display: block; margin-bottom: 16px"
></i>
<h3 style="margin-bottom: 8px">Could not load feed</h3>
<p id="feed-error-msg"></p>
</div>
</main>
</div>
</div>
<script type="module"> <!-- Posts Grid (einfach als Liste / Grid – hier als Grid wie Marketplace) -->
// ── Sidebar & Topbar ────────────────────────────────────────────── <div class="posts-grid">
fetch("/sidebar.html")
.then((r) => r.text())
.then((data) => {
document.getElementById("sidebar-container").innerHTML = data;
document
.querySelectorAll("#sidebar-container .sidebar a")
.forEach((link) => link.classList.remove("active"));
const firstLink = document.querySelectorAll(
"#sidebar-container .sidebar li a",
)[0];
if (firstLink) firstLink.classList.add("active");
});
fetch("/topbar.html") <!-- Post 1 -->
.then((r) => r.text()) <div class="post-card" onclick="location.href='post-detail.html?id=1'">
.then( <div class="post-header">
(data) => <img src="../images/content/creator1.png" alt="Sarah Jenkins" class="post-avatar">
(document.getElementById("topbar-container").innerHTML = data), <div class="post-author">
); <span class="post-name">Sarah Jenkins</span>
<span class="post-handle">@sarahj</span>
// ── Feed ────────────────────────────────────────────────────────── </div>
const grid = document.getElementById("posts-grid"); <span class="post-date">2 hours ago</span>
const emptyEl = document.getElementById("feed-empty"); </div>
const errorEl = document.getElementById("feed-error"); <div class="post-content">
const errorMsg = document.getElementById("feed-error-msg"); <h3 class="post-title">Conceptual Landscape Art</h3>
<p class="post-description">Enchanting, vintage, antique vibes. A journey through surreal landscapes.</p>
function timeAgo(dateStr) { <img src="../images/content/feed1.png" alt="Conceptual Landscape" class="post-image">
const diff = Date.now() - new Date(dateStr).getTime(); </div>
const m = Math.floor(diff / 60000); <!-- Like, Comment, Share, Save Buttons -->
if (m < 1) return "just now"; <div class="post-actions">
if (m < 60) return `${m}m ago`; <button class="action-btn like-btn"><i class="bi bi-heart"></i> <span>128</span></button>
const h = Math.floor(m / 60); <button class="action-btn comment-btn"><i class="bi bi-chat"></i> <span>15</span></button>
if (h < 24) return `${h}h ago`; <button class="action-btn share-btn"><i class="bi bi-share"></i></button>
const d = Math.floor(h / 24); <button class="action-btn save-btn"><i class="bi bi-bookmark"></i></button>
if (d < 7) return `${d}d ago`;
return new Date(dateStr).toLocaleDateString();
}
function renderStars(rating) {
if (rating == null) return "";
const stars = Math.round(rating);
return `<span class="post-rating" title="${rating.toFixed(1)} / 5">
${'<i class="bi bi-star-fill"></i>'.repeat(stars)}${'<i class="bi bi-star"></i>'.repeat(5 - stars)}
<span>${rating.toFixed(1)}</span>
</span>`;
}
function feedImg(id) {
return `/images/content/feed${(parseInt(id.slice(-1), 16) % 4) + 1}.png`;
}
function profileUrl(userId) {
return `/profile.html?id=${encodeURIComponent(userId)}`;
}
function renderCard(prompt) {
const locked = !prompt.canAccess;
const liked = prompt.isLiked;
const saved = prompt.isSaved;
return `
<div class="post-card${locked ? " post-locked" : ""}" onclick="location.href='${profileUrl(prompt.creatorId)}'">
<div class="post-header">
<img class="post-avatar" src="${prompt.creatorAvatarUrl || '../images/content/cat.png'}" alt="${prompt.creatorName}">
<div class="post-author">
<span class="post-name">${prompt.creatorName}</span>
</div> </div>
<span class="post-date">${timeAgo(prompt.timeStamp)}</span>
</div> </div>
<div class="post-content">
${prompt.exampleImageUrl ? `<img class="post-image${locked ? ' post-image-locked' : ''}" src="${prompt.exampleImageUrl}" alt="${prompt.title}">` : `<img class="post-image${locked ? ' post-image-locked' : ''}" src="${feedImg(prompt.id)}" alt="${prompt.title}">`} <!-- Post 2 -->
<h3 class="post-title" style="margin-top:10px">${prompt.title}</h3> <div class="post-card" onclick="location.href='post-detail.html?id=2'">
<p class="post-description">${prompt.description || ''}</p> <div class="post-header">
${locked ? `<p class="post-locked-msg"><i class="bi bi-lock-fill"></i> ${prompt.tierName ?? 'Paid'} tier required</p>` : ''} <img src="../images/content/creator2.png" alt="Alex Chen" class="post-avatar">
${renderStars(prompt.averageRating)} <div class="post-author">
<span class="post-name">Alex Chen</span>
<span class="post-handle">@alexchen</span>
</div>
<span class="post-date">Yesterday</span>
</div>
<div class="post-content">
<h3 class="post-title">Minimalist Logo Design</h3>
<p class="post-description">Clean, modern, minimalist logo for tech startups.</p>
<img src="../images/content/feed2.png" alt="Minimalist Logo" class="post-image">
</div>
<!-- Like, Comment, Share, Save Buttons -->
<div class="post-actions">
<button class="action-btn like-btn"><i class="bi bi-heart"></i> <span>128</span></button>
<button class="action-btn comment-btn"><i class="bi bi-chat"></i> <span>15</span></button>
<button class="action-btn share-btn"><i class="bi bi-share"></i></button>
<button class="action-btn save-btn"><i class="bi bi-bookmark"></i></button>
</div>
</div> </div>
<div class="post-actions">
<button class="action-btn like-btn ${liked ? 'active' : ''}" onclick="toggleLike(event, '${prompt.id}', ${liked})"><i class="bi ${liked ? 'bi-heart-fill' : 'bi-heart'}"></i> <span>Like (${prompt.likeCount || 0})</span></button> <!-- Post 3 -->
<button class="action-btn comment-btn" onclick="event.stopPropagation(); location.href='/post-detail?id=${prompt.id}#rating-section'"><i class="bi bi-chat"></i> <span>Review</span></button> <div class="post-card" onclick="location.href='post-detail.html?id=3'">
<button class="action-btn share-btn" onclick="sharePrompt(event, '${prompt.id}')"><i class="bi bi-share"></i> <span>Share</span></button> <div class="post-header">
<button class="action-btn save-btn ${saved ? 'active' : ''}" onclick="toggleSave(event, '${prompt.id}', ${saved})"><i class="bi ${saved ? 'bi-bookmark-fill' : 'bi-bookmark'}"></i> <span>Save (${prompt.saveCount || 0})</span></button> <img src="../images/content/creator3.png" alt="Mia Wong" class="post-avatar">
<div class="post-author">
<span class="post-name">Mia Wong</span>
<span class="post-handle">@miawong</span>
</div>
<span class="post-date">3 days ago</span>
</div>
<div class="post-content">
<h3 class="post-title">Futuristic Cityscape</h3>
<p class="post-description">Cyberpunk neon city with flying cars and rain.</p>
<img src="../images/content/feed3.png" alt="Cityscape" class="post-image">
</div>
<!-- Like, Comment, Share, Save Buttons -->
<div class="post-actions">
<button class="action-btn like-btn"><i class="bi bi-heart"></i> <span>128</span></button>
<button class="action-btn comment-btn"><i class="bi bi-chat"></i> <span>15</span></button>
<button class="action-btn share-btn"><i class="bi bi-share"></i></button>
<button class="action-btn save-btn"><i class="bi bi-bookmark"></i></button>
</div>
</div> </div>
</div>`;
}
window.toggleLike = async function(event, id, isLiked) { <!-- Post 4 -->
event.stopPropagation(); <div class="post-card" onclick="location.href='post-detail.html?id=4'">
const response = await fetch(`/api/v1/prompts/${id}/likes`, { <div class="post-header">
method: isLiked ? "DELETE" : "PUT", <img src="../images/content/creator4.png" alt="Tom Rivera" class="post-avatar">
credentials: "same-origin" <div class="post-author">
}); <span class="post-name">Tom Rivera</span>
<span class="post-handle">@tomrivera</span>
if (response.status === 401) { </div>
location.href = "/login"; <span class="post-date">5 days ago</span>
return; </div>
} <div class="post-content">
<h3 class="post-title">Watercolor Pet Portrait</h3>
if (!response.ok) return; <p class="post-description">Soft watercolor style, cute pet portrait.</p>
loadFeed( <img src="../images/content/feed4.png" alt="Watercolor Pet" class="post-image">
document.querySelector(".filter-btn.active")?.dataset.sort || "date", </div>
document.querySelector(".filter-btn.active")?.dataset.ascending === "true" <!-- Like, Comment, Share, Save Buttons -->
); <div class="post-actions">
}; <button class="action-btn like-btn"><i class="bi bi-heart"></i> <span>128</span></button>
<button class="action-btn comment-btn"><i class="bi bi-chat"></i> <span>15</span></button>
window.toggleFeedState = function(event, type, id) { <button class="action-btn share-btn"><i class="bi bi-share"></i></button>
event.stopPropagation(); <button class="action-btn save-btn"><i class="bi bi-bookmark"></i></button>
const key = `prompt-${type}-${id}`; </div>
const next = localStorage.getItem(key) !== "true"; </div>
localStorage.setItem(key, next);
loadFeed( </div>
document.querySelector(".filter-btn.active")?.dataset.sort || "date", </main>
document.querySelector(".filter-btn.active")?.dataset.ascending === "true" </div>
); </div>
};
<script>
window.toggleSave = async function(event, id, isSaved) { fetch('../html/sidebar.html')
event.stopPropagation(); .then(r => r.text())
const response = await fetch(`/api/v1/prompts/${id}/saves`, { .then(data => {
method: isSaved ? "DELETE" : "PUT", document.getElementById('sidebar-container').innerHTML = data;
credentials: "same-origin" // Remove 'active' from all sidebar links
}); document.querySelectorAll('#sidebar-container .sidebar a').forEach(link => {
link.classList.remove('active');
if (response.status === 401) {
location.href = "/login";
return;
}
if (!response.ok) return;
loadFeed(
document.querySelector(".filter-btn.active")?.dataset.sort || "date",
document.querySelector(".filter-btn.active")?.dataset.ascending === "true"
);
};
window.sharePrompt = function(event, id) {
event.stopPropagation();
navigator.clipboard.writeText(`${location.origin}/post-detail?id=${id}`);
};
async function loadFeed(sortBy = "date", ascending = false) {
grid.innerHTML = "";
emptyEl.style.display = "none";
errorEl.style.display = "none";
try {
const res = await fetch(
`/api/v1/feed?sortBy=${sortBy}&ascending=${ascending}&limit=20`,
);
if (res.status === 401) {
location.href = "/login";
return;
}
if (!res.ok) throw new Error(`Server error ${res.status}`);
const prompts = await res.json();
if (prompts.length === 0) {
emptyEl.style.display = "block";
return;
}
grid.innerHTML = prompts.map(renderCard).join("");
} catch (e) {
errorEl.style.display = "block";
errorMsg.textContent = e.message;
}
}
// ── Filter buttons ────────────────────────────────────────────────
document.querySelectorAll(".filter-btn").forEach((btn) => {
btn.addEventListener("click", () => {
document
.querySelectorAll(".filter-btn")
.forEach((b) => b.classList.remove("active"));
btn.classList.add("active");
loadFeed(btn.dataset.sort, btn.dataset.ascending === "true");
}); });
// Set 'active' on the first link (Dashboard) - index 0
const firstLink = document.querySelectorAll('#sidebar-container .sidebar li a')[0];
if (firstLink) firstLink.classList.add('active');
}); });
// Initial load fetch('../html/topbar.html')
loadFeed(); .then(r => r.text())
</script> .then(data => document.getElementById('topbar-container').innerHTML = data);
</body> </script>
</body>
</html> </html>
+128 -138
View File
@@ -1,150 +1,140 @@
// LINQ-like Enumerable class wrapping lazy generator chains // LINQ-like Enumerable class wrapping lazy generator chains
class Enumerable { class Enumerable {
constructor(iteratorFn) { constructor(iteratorFn) {
this._iteratorFn = iteratorFn; this._iteratorFn = iteratorFn;
}
[Symbol.iterator]() {
return this._iteratorFn();
}
_chain(generatorFn) {
const source = this;
return new Enumerable(function* () {
yield* generatorFn(source);
});
}
where(predicate) {
return this._chain(function* (source) {
for (const item of source) if (predicate(item)) yield item;
});
}
select(selector) {
return this._chain(function* (source) {
for (const item of source) yield selector(item);
});
}
take(count) {
count = Math.max(0, count);
return this._chain(function* (source) {
for (const item of source) {
if (count-- <= 0) break;
yield item;
}
});
}
skip(count) {
count = Math.max(0, count);
return this._chain(function* (source) {
for (const item of source) {
if (count-- > 0) continue;
yield item;
}
});
}
isLast() {
return this._chain(function* (source) {
const iter = source[Symbol.iterator]();
let current = iter.next();
let index = 0;
while (!current.done) {
const next = iter.next();
yield [current.value, next.done, index];
current = next;
index++;
}
});
}
forEach(action) {
for (const item of this) {
if (Array.isArray(item)) {
action(...item);
} else {
action(item);
}
} }
}
toArray() { [Symbol.iterator]() {
return Array.from(this); return this._iteratorFn();
}
orderByDescending(keySelector) {
return this._chain(function* (source) {
const items = Array.from(source);
items.sort((a, b) => keySelector(b) - keySelector(a));
yield* items;
});
}
orderBy(keySelector) {
return this._chain(function* (source) {
const items = Array.from(source);
items.sort((a, b) => keySelector(a) - keySelector(b));
yield* items;
});
}
firstOrDefault(predicate) {
const source = predicate ? this.where(predicate) : this;
for (const item of source) return item;
return undefined;
}
first(predicate) {
const source = predicate ? this.where(predicate) : this;
for (const item of source) return item;
throw new Error("No elements in sequence.");
}
lastOrDefault(predicate) {
const source = predicate ? this.where(predicate) : this;
let lastValue = undefined;
for (const item of source) lastValue = item;
return lastValue;
}
last(predicate) {
const source = predicate ? this.where(predicate) : this;
let lastValue = undefined;
let found = false;
for (const item of source) {
lastValue = item;
found = true;
} }
if (!found) throw new Error("No elements in sequence.");
return lastValue;
}
any(predicate) { _chain(generatorFn) {
const source = predicate ? this.where(predicate) : this; const source = this;
for (const _ of source) return true; return new Enumerable(function* () {
return false; yield* generatorFn(source);
} });
}
all(predicate) { where(predicate) {
for (const item of this) if (!predicate(item)) return false; return this._chain(function* (source) {
return true; for (const item of source)
} if (predicate(item))
yield item;
});
}
count(predicate) { select(selector) {
let count = 0; return this._chain(function* (source) {
const source = predicate ? this.where(predicate) : this; for (const item of source)
for (const _ of source) count++; yield selector(item);
return count; });
} }
take(count) {
count = Math.max(0, count);
return this._chain(function* (source) {
for (const item of source) {
if (count-- <= 0) break;
yield item;
}
});
}
skip(count) {
count = Math.max(0, count);
return this._chain(function* (source) {
for (const item of source) {
if (count-- > 0) continue;
yield item;
}
});
}
isLast() {
return this._chain(function* (source) {
const iter = source[Symbol.iterator]();
let current = iter.next();
let index = 0;
while (!current.done) {
const next = iter.next();
yield [current.value, next.done, index];
current = next;
index++;
}
});
}
forEach(action) {
for (const item of this) {
if (Array.isArray(item)) {
action(...item);
} else {
action(item);
}
}
}
toArray() {
return Array.from(this);
}
firstOrDefault(predicate) {
const source = predicate ? this.where(predicate) : this;
for (const item of source) return item;
return undefined;
}
first(predicate) {
const source = predicate ? this.where(predicate) : this;
for (const item of source) return item;
throw new Error("No elements in sequence.");
}
lastOrDefault(predicate) {
const source = predicate ? this.where(predicate) : this;
let lastValue = undefined;
for (const item of source) lastValue = item;
return lastValue;
}
last(predicate) {
const source = predicate ? this.where(predicate) : this;
let lastValue = undefined;
let found = false;
for (const item of source) {
lastValue = item;
found = true;
}
if (!found) throw new Error("No elements in sequence.");
return lastValue;
}
any(predicate) {
const source = predicate ? this.where(predicate) : this;
for (const _ of source) return true;
return false;
}
all(predicate) {
for (const item of this)
if (!predicate(item))
return false;
return true;
}
count(predicate) {
let count = 0;
const source = predicate ? this.where(predicate) : this;
for (const _ of source) count++;
return count;
}
} }
Array.prototype.asEnumerable = function () { Array.prototype.asEnumerable = function () {
const arr = this; const arr = this;
return new Enumerable(function* () { return new Enumerable(function* () {
for (const item of arr) yield item; for (const item of arr)
}); yield item;
}; });
}
-13
View File
@@ -1,16 +1,5 @@
import { sendFormAsync } from "./shared.js"; import { sendFormAsync } from "./shared.js";
async function redirectIfAlreadySignedIn() {
const response = await fetch('/api/v1/auth/me', {
method: 'GET',
credentials: 'same-origin'
});
if (response.ok) {
window.location.replace('/dashboard');
}
}
function togglePassword() { function togglePassword() {
const passwordInput = document.getElementById('password'); const passwordInput = document.getElementById('password');
const newInputType = passwordInput.type === 'password' ? 'text' : 'password'; const newInputType = passwordInput.type === 'password' ? 'text' : 'password';
@@ -30,5 +19,3 @@ loginForm.addEventListener('submit', async (event) => {
event.preventDefault(); // Prevent the default form submission event.preventDefault(); // Prevent the default form submission
await submitLoginForm(); await submitLoginForm();
}); });
await redirectIfAlreadySignedIn();
-556
View File
@@ -1,556 +0,0 @@
import "./linq.js";
import { NodeTemplate } from "./node-template.js";
// ─── Route matching ───
class RouteMatch {
constructor(route, path, params) {
this.route = route;
this.path = path;
this.params = params;
this.segmentCount = route.fragments.length;
}
}
export class Route {
constructor(pattern, componentClass) {
this.id = crypto.randomUUID();
this.componentClass = componentClass;
this.componentDefinition = componentClass.definition;
this.fragments = pattern.split("/");
}
match(path) {
const parsedUrl = new URL(path, window.location.origin);
const params = {};
parsedUrl.searchParams.forEach((value, key) => {
params[key] = value;
});
const pathFragments = parsedUrl.pathname.split("/");
for (let i = 0; i < this.fragments.length; i++) {
const fragment = this.fragments[i];
const pathFragment = pathFragments[i];
if (fragment.startsWith(":")) {
params[fragment.substring(1)] = pathFragment;
continue;
} else if (fragment === "*") {
continue;
} else if (fragment === "**") {
return new RouteMatch(this, path, params);
} else if (fragment !== pathFragment) {
return null;
}
}
return new RouteMatch(this, path, params);
}
}
// ─── ComponentInput (signal-like) ───
export class ComponentInput {
constructor(defaultValue, options = {}) {
this._value = defaultValue;
this.transform = options.transform || ((v) => v);
this.validate = options.validate || (() => true);
this.alias = options.alias || null;
this._isComponentInput = true;
this._owner = null;
const self = this;
const fn = function () {
return self._value;
};
return new Proxy(fn, {
get(target, prop) {
if (prop === "set") return (v) => self._set(v);
if (prop === "_isComponentInput") return true;
if (prop === "_self") return self;
if (prop === "alias") return self.alias;
if (prop === Symbol.toPrimitive) return () => self._value;
if (prop === "valueOf") return () => self._value;
if (prop === "toString") return () => String(self._value);
const inner = self._value;
if (inner == null) return undefined;
const val = inner[prop];
return typeof val === "function" ? val.bind(inner) : val;
},
set(target, prop, value) {
if (self._value != null) {
self._value[prop] = value;
if (self._owner) self._owner.requestUpdate();
}
return true;
},
apply(target, thisArg, args) {
return self._value;
},
});
}
_set(newValue) {
const transformed = this.transform(newValue);
if (!this.validate(transformed)) {
throw new Error("Invalid value");
}
this._value = transformed;
if (this._owner) this._owner.requestUpdate();
}
static [Symbol.hasInstance](instance) {
return instance?._isComponentInput === true;
}
}
// ─── ViewChild ───
export class ViewChild {
constructor(options = { selector: null, id: null, multiple: false }) {
this._selector = options.selector;
this._id = options.id;
this._multiple = options.multiple;
this._element = null;
this._isViewChild = true;
return new Proxy(this, {
get(target, prop) {
if (prop in target) return target[prop];
if (target._element) {
const value = target._element[prop];
return typeof value === "function"
? value.bind(target._element)
: value;
}
},
});
}
_setValue(element) {
this._element = element;
}
static [Symbol.hasInstance](instance) {
return instance?._isViewChild === true;
}
}
// ─── ComponentDefinition ───
export class ComponentDefinition {
constructor(
options = {
templatesPath: null,
template: null,
stylesPath: null,
style: null,
scriptsPath: null,
},
) {
this.templatesPath = options.templatesPath;
this.template = options.template;
this.stylesPath = options.stylesPath;
this.style = options.style;
this.scriptsPath = options.scriptsPath;
}
}
// ─── EventListener ───
class EventBinding {
constructor(event, element, handler) {
this.event = event;
this.element = element;
this.handler = handler;
}
attach() {
this.element.addEventListener(this.event, this.handler);
}
detach() {
this.element.removeEventListener(this.event, this.handler);
}
}
// ─── Component ───
export class Component extends EventTarget {
constructor() {
super();
this._eventBindings = [];
return new Proxy(this, {
get(target, prop, receiver) {
const value = Reflect.get(target, prop, target);
if (typeof value === "function" && typeof value.bind === "function") {
return prop in EventTarget.prototype
? value.bind(target)
: value.bind(receiver);
}
return value;
},
set(target, prop, value) {
if (target[prop] instanceof ComponentInput) {
target[prop].set(value);
return true;
} else if (target[prop] instanceof ViewChild) {
target[prop]._setValue(value);
} else {
target[prop] = value;
}
target.requestUpdate();
return true;
},
});
}
requestUpdate() {
this.dispatchEvent(new Event("requestUpdate"));
}
static get definition() {
throw new Error("Component definition is not defined");
}
onInit() { }
onBeforeRender() { }
onAfterRender() { }
onDestroy() {
this._eventBindings.forEach((b) => b.detach());
}
}
// ─── Router init ───
export function initRouter(outletId, routes) {
const outletRef = document.getElementById(outletId);
if (!outletRef) {
console.error(`Outlet element with id '${outletId}' not found`);
return null;
}
return new Router(outletRef, routes);
}
// ─── Router ───
export class Router {
constructor(outletRef, routes) {
this.outletRef = outletRef;
this.shadowRoot = outletRef.attachShadow({ mode: "open" });
this.routes = routes;
this.templateCache = new Map();
this.activeController = null;
this.activeRenderResult = null;
this._boundUpdateHandler = null;
this._rendering = false;
this._pendingUpdate = false;
this.shadowRoot.textContent = "Loading...";
navigation.addEventListener("navigate", this.handleNavigate.bind(this));
}
findMatchingRoute(path) {
return this.routes
.asEnumerable()
.select((route) => route.match(path))
.where((match) => match !== null)
.orderByDescending((match) => match.segmentCount)
.firstOrDefault();
}
async handleNavigate(event) {
if (event.navigationType === 'replace' && event.destination.url === this.activeRoute) return;
const routeMatch = this.findMatchingRoute(event.destination.url);
if (!routeMatch) return;
event.preventDefault();
const template = await this.getCachedTemplate(routeMatch.route);
const controller = this.createComponentInstance(
routeMatch.route.componentClass,
routeMatch.params,
);
this.destroyCurrent();
this.activeController = controller;
this.activeTemplate = template;
this.activeRoute = event.destination.url;
this.insertIncludes(routeMatch.route);
this._boundUpdateHandler = this.handleUpdateRequest.bind(this);
this.activeController.addEventListener(
"requestUpdate",
this._boundUpdateHandler,
);
this.renderActiveComponent();
history.replaceState({}, "", event.destination.url);
}
destroyCurrent() {
if (this.activeController) {
this.activeController.removeEventListener(
"requestUpdate",
this._boundUpdateHandler,
);
this.activeController.onDestroy();
this.activeController = null;
}
if (this.activeRenderResult) {
this.activeRenderResult.destroy();
this.activeRenderResult = null;
}
}
handleUpdateRequest() {
if (this._rendering) {
this._pendingUpdate = true;
return;
}
this.updateActiveComponent();
}
insertIncludes(route) {
// Remove previous component styles from shadow root
this.shadowRoot
.querySelectorAll("link[data-component-style], style[data-component-style]")
.forEach((l) => l.remove());
if (route.componentDefinition.style) {
const styleEl = document.createElement("style");
styleEl.textContent = route.componentDefinition.style;
styleEl.setAttribute("data-component-style", "");
this.shadowRoot.appendChild(styleEl);
}
const paths = route.componentDefinition.stylesPath;
if (!paths) return;
const list = Array.isArray(paths) ? paths : [paths];
for (const p of list) {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = p;
link.setAttribute("data-component-style", "");
this.shadowRoot.appendChild(link);
}
}
// ─── First render: build DOM from scratch ───
renderActiveComponent() {
this._rendering = true;
this._pendingUpdate = false;
this.activeController.onBeforeRender();
const result = this.activeTemplate.render(this.activeController);
this.activeRenderResult = result;
// Clear shadow root content (keep style links), append fragment
for (const child of Array.from(this.shadowRoot.childNodes)) {
if (
child.nodeType !== Node.ELEMENT_NODE ||
!child.hasAttribute("data-component-style")
) {
child.remove();
}
}
this.shadowRoot.appendChild(result.fragment);
// Wire events + two-way bindings on the live shadow DOM
this.wireEvents(this.activeController, this.shadowRoot);
this.wireViewChildren(this.activeController, this.shadowRoot);
this.activeController.onAfterRender();
this._rendering = false;
if (this._pendingUpdate) {
this.updateActiveComponent();
}
}
// ─── Subsequent updates: patch bindings only ───
updateActiveComponent() {
this._rendering = true;
this._pendingUpdate = false;
this.activeController.onBeforeRender();
this.activeRenderResult.update(this.activeController);
this.activeController.onAfterRender();
this._rendering = false;
if (this._pendingUpdate) {
this.updateActiveComponent();
}
}
// ─── ViewChild wiring ───
wireViewChildren(controller, root) {
Object.entries(controller)
.filter(([_, value]) => value instanceof ViewChild)
.forEach(([key, viewChild]) => {
if (viewChild._id) {
const el = root.querySelector(`#${viewChild._id}`);
if (el) viewChild._setValue(el);
} else if (viewChild._selector) {
const el = root.querySelector(viewChild._selector);
if (el) viewChild._setValue(el);
} else {
console.warn(`ViewChild ${key}: no selector or id`);
}
});
}
// ─── Event wiring ───
// Supports:
// (click)="methodName()" — event binding
// [(value)]="propName" — two-way binding (banana-in-a-box)
wireEvents(controller, root) {
const allElements = root.querySelectorAll("*");
allElements.forEach((element) => {
// ─── Two-way bindings from __templateMeta ───
if (element.__templateMeta) {
for (const meta of element.__templateMeta) {
if (meta.bracket === "[()]" && meta.expression) {
const domProp = meta.name.replace(/^\(|\)$/g, ""); // strip parens
this._bindTwoWay(controller, element, domProp, meta.expression);
}
}
}
// ─── Event bindings from DOM attributes ───
for (const attr of Array.from(element.attributes)) {
const name = attr.name;
const eventMatch = name.match(/^\((\w+)\)$/);
if (eventMatch) {
const eventName = eventMatch[1];
const attrValue = attr.value.trim();
const methodName = attrValue.endsWith("()")
? attrValue.slice(0, -2)
: attrValue;
let binding;
if (typeof controller[methodName] === "function") {
const handler = controller[methodName].bind(controller);
binding = new EventBinding(eventName, element, handler);
} else {
const fn = new Function("event", attrValue).bind(controller);
binding = new EventBinding(eventName, element, fn);
}
binding.attach();
controller._eventBindings.push(binding);
}
}
});
}
// ─── Two-way bind: DOM property ↔ controller field ───
// Sets DOM prop from controller on each update.
// Listens for input/change events to write back to controller.
_bindTwoWay(controller, element, domProp, field) {
// Controller → DOM: set initial value
const getValue = () => {
const v = controller[field];
return typeof v === "function" ? v() : v;
};
element[domProp] = getValue() ?? "";
// DOM → Controller: on input (for text) + change (for select/checkbox)
const writeBack = () => {
const domValue = element[domProp];
if (controller[field] instanceof ComponentInput) {
controller[field].set(domValue);
} else {
controller[field] = domValue;
}
};
const inputBinding = new EventBinding("input", element, writeBack);
const changeBinding = new EventBinding("change", element, writeBack);
inputBinding.attach();
changeBinding.attach();
controller._eventBindings.push(inputBinding, changeBinding);
// Controller → DOM: patch on every update via RenderResult hook
// We piggyback on requestUpdate listener — the attr binding in
// node-template handles {{expr}} attrs, but for [(prop)] we need
// to sync the DOM *property* (not attribute) on update.
const updateBinding = new EventBinding("requestUpdate", controller, () => {
const val = getValue() ?? "";
if (element[domProp] !== val) element[domProp] = val;
});
updateBinding.attach();
controller._eventBindings.push(updateBinding);
}
// ─── Component instance creation ───
createComponentInstance(component, params) {
const instance = new component();
// Wire _owner for ComponentInput reactivity
for (const key of Object.keys(instance)) {
const val = instance[key];
if (val instanceof ComponentInput) {
val._self._owner = instance;
}
}
instance.onInit();
// Bind route/query params → ComponentInputs (by name or alias)
for (const [paramKey, paramValue] of Object.entries(params)) {
if (instance[paramKey] instanceof ComponentInput) {
instance[paramKey].set(paramValue);
continue;
}
for (const key of Object.keys(instance)) {
const val = instance[key];
if (val instanceof ComponentInput && val.alias === paramKey) {
val.set(paramValue);
break;
}
}
}
return instance;
}
// ─── Template caching ───
async getCachedTemplate(route) {
if (this.templateCache.has(route.id)) {
return this.templateCache.get(route.id);
}
let templateContent = route.componentClass.definition.template;
if (!templateContent && route.componentClass.definition.templatesPath) {
const response = await fetch(
route.componentClass.definition.templatesPath,
);
if (!response.ok) {
return new NodeTemplate(
`<div class="error"><h1>Failed to load template</h1><p>${response.status} ${response.statusText}</p></div>`,
);
}
templateContent = await response.text();
}
try {
const template = new NodeTemplate(templateContent);
this.templateCache.set(route.id, template);
return template;
} catch (error) {
return new NodeTemplate(
`<div class="error"><h1>Failed to compile template</h1><p>${error.message}</p></div>`,
);
}
}
}
File diff suppressed because it is too large. Load diff
-65
View File
@@ -1,65 +0,0 @@
import { initRouter, Route, ViewChild, Component, ComponentInput, ComponentDefinition } from "./node-pwa.js";
import { IntInput } from "./utils.js";
class TestComponent extends Component {
static get definition() {
return new ComponentDefinition({
name: "test-component",
template: `<div>
<h1>Test Component</h1>
<p>This is a test component.</p>
<button
id="test-button"
[class.red-button]="count() % 2 === 0"
[class.green-button]="count() % 2 !== 0"
class="counter-button"
(click)="incrementCount()"
>Count: {{count()}}</button>
<input type="text" [(value)]="name" placeholder="Enter your name" />
<p>Hello, {{name()}}! Counter is {{count()}}</p>
</div>`,
style: `
.red-button {
background-color: red;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
.green-button {
background-color: green;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
.counter-button {
border-radius: 10px;
margin: 15px 30px;
font-size: 18px;
transition: opacity 0.3s ease;
}
.counter-button:hover {
opacity: 0.8;
}
`
});
}
count = new ComponentInput(0, IntInput);
name = new ComponentInput("World");
incrementCount() {
const currentCount = this.count();
this.count.set(currentCount + 1);
}
}
const route1 = new Route("/counter", TestComponent);
const route2 = new Route("/counter/:count", TestComponent);
initRouter("routerOutlet", [route1, route2]);
-101
View File
@@ -1,101 +0,0 @@
(function () {
let currentProfilePromise = null;
let currentProfile = null;
async function fetchJson(url) {
const response = await fetch(url, { credentials: "same-origin" });
if (response.status === 401) {
location.href = "/login";
return null;
}
if (!response.ok) throw new Error(`${url} returned ${response.status}`);
return response.json();
}
async function loadCurrentProfile(force = false) {
if (!force && currentProfilePromise) return currentProfilePromise;
currentProfilePromise = Promise.all([
fetchJson("/api/v1/profiles/self"),
fetchJson("/api/v1/auth/me"),
]).then(([profile, user]) => {
currentProfile = { ...profile, user };
return currentProfile;
});
return currentProfilePromise;
}
function applyTopbarProfile(profile) {
const avatar = document.getElementById("topbarAvatar");
if (!avatar || !profile) return;
if (profile.avatarUrl) avatar.src = profile.avatarUrl;
avatar.alt = profile.displayName || profile.user?.userName || "Profile";
avatar.title = profile.displayName || profile.user?.userName || "Profile";
}
function wireTopbarSearch() {
const input = document.getElementById("topbarSearchInput");
if (!input || input.dataset.searchReady === "true") return;
input.dataset.searchReady = "true";
const params = new URLSearchParams(location.search);
if (location.pathname.includes("community") && params.has("search")) {
input.value = params.get("search") || "";
}
let searchTimeout;
input.addEventListener("input", () => {
if (!location.pathname.includes("community")) return;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
if (typeof window.applyCreatorSearch === "function") {
window.applyCreatorSearch(input.value);
}
}, 300);
});
input.addEventListener("keydown", (event) => {
if (event.key !== "Enter") return;
const search = input.value.trim();
location.href = search
? `/community?search=${encodeURIComponent(search)}`
: "/community";
});
}
async function hydrateTopbarProfile() {
try {
const profile = currentProfile || (await loadCurrentProfile());
applyTopbarProfile(profile);
} catch {
// Keep the fallback avatar if the profile cannot be loaded.
}
}
function setCurrentProfile(profile) {
currentProfile = profile;
currentProfilePromise = Promise.resolve(profile);
applyTopbarProfile(profile);
}
window.loadCurrentProfile = loadCurrentProfile;
window.hydrateTopbarProfile = hydrateTopbarProfile;
window.setCurrentProfile = setCurrentProfile;
const observer = new MutationObserver(() => {
if (document.getElementById("topbarAvatar")) hydrateTopbarProfile();
wireTopbarSearch();
});
if (document.body) {
observer.observe(document.body, { childList: true, subtree: true });
} else {
document.addEventListener("DOMContentLoaded", () => {
observer.observe(document.body, { childList: true, subtree: true });
});
}
})();
-432
View File
@@ -1,432 +0,0 @@
import "./linq.js";
import { Template } from "./template.js";
class RouteMatch {
constructor(route, path, params) {
this.route = route;
this.path = path;
this.params = params;
this.segmentCount = route.fragments.length;
}
}
export class Route {
constructor(pattern, componentClass) {
this.id = crypto.randomUUID();
this.componentClass = componentClass;
this.ComponentDefinition = componentClass.definition;
this.fragments = pattern.split("/");
}
match(path) {
const parsedUrl = new URL(path, window.location.origin);
const params = {};
parsedUrl.searchParams.forEach((value, key) => {
params[key] = value;
});
const pathFragments = parsedUrl.pathname
.split("/")
.filter((f) => f.length > 0);
for (let i = 0; i < this.fragments.length; i++) {
const fragment = this.fragments[i];
const pathFragment = pathFragments[i];
if (fragment.startsWith(":")) {
params[fragment.substring(1)] = pathFragment;
continue;
} else if (fragment === "*") {
continue;
} else if (fragment === "**") {
return new RouteMatch(this, path, params);
} else if (fragment !== pathFragment) {
return null;
}
}
return new RouteMatch(this, path, params);
}
}
export class ComponentInput {
constructor(defaultValue, options = {}) {
this._value = defaultValue;
this.transform = options.transform || ((v) => v);
this.validate = options.validate || (() => true);
this.alias = options.alias || null;
this._isComponentInput = true;
this._owner = null;
const self = this;
const fn = function () {
return self._value;
};
return new Proxy(fn, {
get(target, prop) {
if (prop === "set") return (v) => self._set(v);
if (prop === "_isComponentInput") return true;
if (prop === "_self") return self;
if (prop === "alias") return self.alias;
if (prop === Symbol.toPrimitive) return () => self._value;
if (prop === "valueOf") return () => self._value;
if (prop === "toString") return () => String(self._value);
const inner = self._value;
if (inner == null) return undefined;
const val = inner[prop];
return typeof val === "function" ? val.bind(inner) : val;
},
set(target, prop, value) {
if (self._value != null) {
self._value[prop] = value;
if (self._owner) self._owner.requestUpdate();
}
return true;
},
apply(target, thisArg, args) {
return self._value;
},
});
}
_set(newValue) {
const transformed = this.transform(newValue);
if (!this.validate(transformed)) {
throw new Error("Invalid value");
}
this._value = transformed;
if (this._owner) this._owner.requestUpdate();
}
static [Symbol.hasInstance](instance) {
return instance?._isComponentInput === true;
}
}
export class ViewChild {
constructor(options = { selector: null, id: null, multiple: false }) {
this._selector = options.selector;
this._id = options.id;
this._multiple = options.multiple;
this._element = null;
this._isViewChild = true;
return new Proxy(this, {
get(target, prop) {
if (prop in target) return target[prop];
if (target._element) {
const value = target._element[prop];
return typeof value === "function"
? value.bind(target._element)
: value;
}
},
});
}
_setValue(element) {
this._element = element;
}
static [Symbol.hasInstance](instance) {
return instance?._isViewChild === true;
}
}
export class ComponentDefinition {
constructor(
options = {
templatesPath: null,
template: null,
stylesPath: null,
style: null,
scriptsPath: null,
},
) {
this.templatesPath = options.templatesPath;
this.template = options.template;
this.stylesPath = options.stylesPath;
this.scriptsPath = options.scriptsPath;
}
}
class EventListener {
constructor(event, element, handler) {
this.event = event;
this.element = element;
this.handler = handler;
}
attach() {
this.element.addEventListener(this.event, this.handler);
}
detach() {
this.element.removeEventListener(this.event, this.handler);
}
}
export class Component extends EventTarget {
constructor() {
super();
this._eventListeners = [];
return new Proxy(this, {
get(target, prop, receiver) {
const value = Reflect.get(target, prop, target);
if (typeof value === "function" && typeof value.bind === "function") {
return prop in EventTarget.prototype
? value.bind(target)
: value.bind(receiver);
}
return value;
},
set(target, prop, value) {
if (target[prop] instanceof ComponentInput) {
target[prop].set(value);
return true;
} else if (target[prop] instanceof ViewChild) {
target[prop]._setValue(value);
} else {
target[prop] = value;
}
target.requestUpdate();
return true;
},
});
}
requestUpdate() {
this.dispatchEvent(new Event("requestUpdate", { component: this }));
}
static get definition() {
throw new Error("Component definition is not defined");
}
onInit() { }
onBeforeRender() { }
onAfterRender() { }
onDestroy() {
this._eventListeners.forEach((listener) => listener.detach());
}
}
export function initRouter(outletId, includeId, routes) {
const outletRef = document.getElementById(outletId);
const includeRef = document.getElementById(includeId);
if (!outletRef) {
console.error(`Outlet element with id '${outletId}' not found`);
return null;
}
if (!includeRef) {
console.error(`Include element with id '${includeId}' not found`);
return null;
}
return new Router(outletRef, includeRef, routes);
}
export class Router {
constructor(outletRef, includeRef, routes) {
this.outletRef = outletRef;
this.includeRef = includeRef;
this.routes = routes;
this.templateCache = new Map();
outletRef.innerHTML = "Loading...";
includeRef.innerHTML = "";
navigation.addEventListener("navigate", this.handleNavigate.bind(this));
}
findMatchingRoute(path) {
const routeMatch = this.routes
.asEnumerable()
.select((route) => route.match(path))
.where((match) => match !== null)
.orderByDescending((match) => match.segmentCount)
.firstOrDefault();
return routeMatch;
}
async handleNavigate(event) {
const routeMatch = this.findMatchingRoute(event.destination.url);
if (routeMatch) {
event.preventDefault();
const template = await this.getCachedTemplate(routeMatch.route);
const controller = this.createComponentInstance(
routeMatch.route.componentClass,
routeMatch.params,
);
this.destroyCurrent();
this.activeController = controller;
this.activeTemplate = template;
this.insertIncludes(routeMatch.route);
this._boundUpdateHandler = this.handleUpdateRequest.bind(this);
this.activeController.addEventListener(
"requestUpdate",
this._boundUpdateHandler,
);
this.renderActiveComponent();
history.pushState(null, "", routeMatch.path);
}
}
destroyCurrent() {
if (this.activeController) {
this.activeController.removeEventListener(
"requestUpdate",
this._boundUpdateHandler,
);
this.activeController.onDestroy();
this.activeController = null;
}
}
handleUpdateRequest(args) {
if (this._rendering) {
this._pendingUpdate = true;
return;
} else {
this.renderActiveComponent();
}
}
insertIncludes(route) {
if (Array.isArray(route.ComponentDefinition.stylesPath)) {
route.ComponentDefinition.stylesPath.forEach((path) => {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = path;
this.includeRef.appendChild(link);
});
} else if (route.ComponentDefinition.stylesPath) {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = route.ComponentDefinition.stylesPath;
this.includeRef.appendChild(link);
}
}
renderActiveComponent() {
this._rendering = true;
this._pendingUpdate = false;
this.activeController.onBeforeRender();
const renderedTemplate = this.activeTemplate.render(this.activeController);
this.outletRef.innerHTML = renderedTemplate;
this.wireEvents(this.activeController);
this.wireViewChildren(this.activeController);
this.activeController.onAfterRender();
this._rendering = false;
if (this._pendingUpdate) {
this.renderActiveComponent();
}
}
wireViewChildren(controller) {
const viewChildProps = Object.entries(controller)
.filter(([_, value]) => value instanceof ViewChild)
.forEach(([key, viewChild]) => {
if (viewChild._id) {
const element = this.outletRef.querySelector(`#${viewChild._id}`);
if (element) viewChild._setValue(element);
} else if (viewChild._selector) {
const element = this.outletRef.querySelector(viewChild._selector);
if (element) viewChild._setValue(element);
} else {
console.warn(`ViewChild ${key} has no selector or id defined`);
}
});
}
wireEvents(controller) {
const allElements = this.outletRef.querySelectorAll("*");
allElements.forEach((element) => {
element.getAttributeNames().forEach((attr) => {
const match = attr.match(/^\((\w+)\)$/);
if (!match) return;
const eventName = match[1];
const attrValue = element.getAttribute(attr).trim();
const methodName = attrValue.endsWith("()")
? attrValue.slice(0, -2)
: attrValue;
let listener;
if (typeof controller[methodName] === "function") {
// Named method — wire directly
const handler = controller[methodName].bind(controller);
listener = new EventListener(eventName, element, handler);
} else {
const fn = new Function("event", attrValue).bind(controller);
listener = new EventListener(eventName, element, fn);
}
listener.attach();
controller._eventListeners.push(listener);
});
});
}
createComponentInstance(component, params) {
const instance = new component();
for (const key of Object.keys(instance)) {
const val = instance[key];
if (val instanceof ComponentInput) {
val._self._owner = instance;
}
}
instance.onInit();
for (const [paramKey, paramValue] of Object.entries(params)) {
if (instance[paramKey] instanceof ComponentInput) {
instance[paramKey].set(paramValue);
continue;
}
for (const key of Object.keys(instance)) {
const val = instance[key];
if (val instanceof ComponentInput && val.alias === paramKey) {
val.set(paramValue);
break;
}
}
}
return instance;
}
async getCachedTemplate(route) {
if (this.templateCache.has(route.id)) {
return this.templateCache.get(route.id);
}
let templateContent = route.componentClass.definition.template;
if (!templateContent && route.componentClass.definition.templatesPath) {
const response = await fetch(
route.componentClass.definition.templatesPath,
);
if (response.ok === false) {
return new Template(`
<div class="error">
<h1>Failed to load template</h1>
<p>${response.status} ${response.statusText}</p>
</div>
`);
}
templateContent = await response.text();
}
try {
const template = new Template(templateContent);
this.templateCache.set(route.id, template);
return template;
} catch (error) {
return new Template(`
<div class="error">
<h1>Failed to compile template</h1>
<p>${error.message}</p>
</div>
`);
}
}
}
+380 -401
View File
@@ -1,476 +1,455 @@
import "./linq.js"; import './linq.js'
function selectPath(data, expression) { function selectPath(data, expression) {
if (!expression) return data; if (!expression) return data;
try { try {
return new Function("$data", `with($data) { return (${expression}); }`)( return new Function('$data', `with($data) { return (${expression}); }`)(data);
data, } catch {
); console.error(`Error evaluating Template expression: ${expression}`);
} catch { return undefined;
console.error(`Error evaluating Template expression: ${expression}`); }
return undefined;
}
} }
class ScopeDict { class ScopeDict {
constructor(initial = {}) { constructor(initial = {}) {
this._entries = { ...initial }; this._entries = { ...initial };
}
set(name, value) {
if (name.startsWith("$")) {
throw new Error(
`Cannot declare '${name}' with @let. Variables starting with '$' are reserved.`,
);
} }
this._entries[name] = value;
}
setBuiltin(name, value) { set(name, value) {
this._entries[name] = value; if (name.startsWith('$')) {
} throw new Error(`Cannot declare '${name}' with @let. Variables starting with '$' are reserved.`);
}
this._entries[name] = value;
}
has(name) { setBuiltin(name, value) {
return name in this._entries; this._entries[name] = value;
} }
get(name) { has(name) {
return this._entries[name]; return name in this._entries;
} }
clone() { get(name) {
return new ScopeDict(this._entries); return this._entries[name];
} }
clone() {
return new ScopeDict(this._entries);
}
} }
function createScopeProxy(data, scope) { function createScopeProxy(data, scope) {
if (data === null || data === undefined || typeof data !== "object") { if (data === null || data === undefined || typeof data !== 'object') {
scope.setBuiltin("$this", data); scope.setBuiltin('$this', data);
return new Proxy( return new Proxy({}, {
{}, get(_target, prop) {
{ if (prop === '$this') return data;
get(_target, prop) { if (scope.has(prop)) return scope.get(prop);
if (prop === "$this") return data; return undefined;
if (scope.has(prop)) return scope.get(prop); },
return undefined; has(_target, prop) {
return prop === '$this' || scope.has(prop);
}
});
}
scope.setBuiltin('$this', data);
return new Proxy(data, {
get(target, prop) {
if (prop === '$this') return data;
if (scope.has(prop)) return scope.get(prop);
return target[prop];
}, },
has(_target, prop) { has(target, prop) {
return prop === "$this" || scope.has(prop); return prop === '$this' || scope.has(prop) || prop in target;
}, }
}, });
);
}
scope.setBuiltin("$this", data);
return new Proxy(data, {
get(target, prop) {
if (prop === "$this") return data;
if (scope.has(prop)) return scope.get(prop);
return target[prop];
},
has(target, prop) {
return prop === "$this" || scope.has(prop) || prop in target;
},
});
} }
function skipString(str, i) { function skipString(str, i) {
const quote = str[i]; const quote = str[i];
i++;
while (i < str.length && str[i] !== quote) {
if (str[i] === "\\") i++;
i++; i++;
} while (i < str.length && str[i] !== quote) {
return i; if (str[i] === '\\') i++;
i++;
}
return i;
} }
function findClosingParen(str, openPos) { function findClosingParen(str, openPos) {
let depth = 1; let depth = 1;
let i = openPos + 1; let i = openPos + 1;
while (i < str.length && depth > 0) { while (i < str.length && depth > 0) {
if (str[i] === "'" || str[i] === '"' || str[i] === "`") { if (str[i] === "'" || str[i] === '"' || str[i] === '`') {
i = skipString(str, i) + 1; i = skipString(str, i) + 1;
continue; continue;
}
if (str[i] === '(') depth++;
else if (str[i] === ')') depth--;
if (depth > 0) i++;
} }
if (str[i] === "(") depth++; if (depth !== 0) throw new Error('Unclosed ( in template');
else if (str[i] === ")") depth--; return i;
if (depth > 0) i++;
}
if (depth !== 0) throw new Error("Unclosed ( in template");
return i;
} }
function findClosingBrace(str, openPos) { function findClosingBrace(str, openPos) {
let depth = 1; let depth = 1;
let i = openPos + 1; let i = openPos + 1;
while (i < str.length && depth > 0) { while (i < str.length && depth > 0) {
if (str[i] === "'" || str[i] === '"' || str[i] === "`") { if (str[i] === "'" || str[i] === '"' || str[i] === '`') {
i = skipString(str, i) + 1; i = skipString(str, i) + 1;
continue; continue;
}
if (str[i] === '{' && str[i + 1] === '{') {
const end = str.indexOf('}}', i + 2);
if (end === -1) throw new Error('Unclosed {{ }} in template');
i = end + 2;
continue;
}
if (str[i] === '{') depth++;
else if (str[i] === '}') depth--;
if (depth > 0) i++;
} }
if (str[i] === "{" && str[i + 1] === "{") { if (depth !== 0) throw new Error('Unclosed { in template');
const end = str.indexOf("}}", i + 2); return i;
if (end === -1) throw new Error("Unclosed {{ }} in template"); }
i = end + 2;
continue; function findTopLevelComma(str) {
let depth = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === "'" || str[i] === '"' || str[i] === '`') {
i = skipString(str, i);
continue;
}
if (str[i] === '(') depth++;
else if (str[i] === ')') depth--;
else if (str[i] === ',' && depth === 0) return i;
} }
if (str[i] === "{") depth++; return -1;
else if (str[i] === "}") depth--;
if (depth > 0) i++;
}
if (depth !== 0) throw new Error("Unclosed { in template");
return i;
} }
function formatNumber(value, spec) { function formatNumber(value, spec) {
const hasThousands = spec.includes(","); const hasThousands = spec.includes(',');
const dotIdx = spec.indexOf("."); const dotIdx = spec.indexOf('.');
let decimals = 0; let decimals = 0;
if (dotIdx !== -1) { if (dotIdx !== -1) {
decimals = spec.length - dotIdx - 1; decimals = spec.length - dotIdx - 1;
}
let result = value.toFixed(decimals);
if (hasThousands) {
const parts = result.split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
result = parts.join(".");
}
if (!spec.includes(".") && !hasThousands) {
const padLength = spec.replace(/[^0]/g, "").length;
if (padLength > 0) {
const isNeg = value < 0;
let abs = Math.abs(Math.round(value)).toString();
abs = abs.padStart(padLength, "0");
result = isNeg ? "-" + abs : abs;
} }
}
return result; let result = value.toFixed(decimals);
if (hasThousands) {
const parts = result.split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
result = parts.join('.');
}
if (!spec.includes('.') && !hasThousands) {
const padLength = spec.replace(/[^0]/g, '').length;
if (padLength > 0) {
const isNeg = value < 0;
let abs = Math.abs(Math.round(value)).toString();
abs = abs.padStart(padLength, '0');
result = isNeg ? '-' + abs : abs;
}
}
return result;
} }
function formatDate(date, spec) { function formatDate(date, spec) {
const pad = (n, len = 2) => String(n).padStart(len, "0"); const pad = (n, len = 2) => String(n).padStart(len, '0');
const tokens = { const tokens = {
yyyy: date.getFullYear(), 'yyyy': date.getFullYear(),
yy: String(date.getFullYear()).slice(-2), 'yy': String(date.getFullYear()).slice(-2),
MM: pad(date.getMonth() + 1), 'MM': pad(date.getMonth() + 1),
M: date.getMonth() + 1, 'M': date.getMonth() + 1,
dd: pad(date.getDate()), 'dd': pad(date.getDate()),
d: date.getDate(), 'd': date.getDate(),
HH: pad(date.getHours()), 'HH': pad(date.getHours()),
H: date.getHours(), 'H': date.getHours(),
hh: pad(date.getHours() % 12 || 12), 'hh': pad(date.getHours() % 12 || 12),
h: date.getHours() % 12 || 12, 'h': date.getHours() % 12 || 12,
mm: pad(date.getMinutes()), 'mm': pad(date.getMinutes()),
m: date.getMinutes(), 'm': date.getMinutes(),
ss: pad(date.getSeconds()), 'ss': pad(date.getSeconds()),
s: date.getSeconds(), 's': date.getSeconds(),
fff: pad(date.getMilliseconds(), 3), 'fff': pad(date.getMilliseconds(), 3),
}; };
let result = spec; let result = spec;
for (const [token, value] of Object.entries(tokens).sort( for (const [token, value] of Object.entries(tokens).sort((a, b) => b[0].length - a[0].length)) {
(a, b) => b[0].length - a[0].length, result = result.replaceAll(token, String(value));
)) { }
result = result.replaceAll(token, String(value));
}
return result; return result;
} }
function createFormatter(formatSpec) { function createFormatter(formatSpec) {
return (value) => { return (value) => {
if (value == null) return ""; if (value == null) return '';
if (value instanceof Date) return formatDate(value, formatSpec); if (value instanceof Date) return formatDate(value, formatSpec);
if (typeof value === "number") return formatNumber(value, formatSpec); if (typeof value === 'number') return formatNumber(value, formatSpec);
return String(value); return String(value);
}; };
} }
class StaticTemplatePart {
constructor(text) {
this.text = text;
}
render(_data) { class StaticTemplatePart {
return this.text; constructor(text) {
} this.text = text;
}
render(_data) {
return this.text;
}
} }
class VariableTemplatePart { class VariableTemplatePart {
constructor(contextPath, formatter) { constructor(contextPath, formatter) {
this.contextPath = contextPath; this.contextPath = contextPath;
this.formatter = formatter || ((x) => x); this.formatter = formatter || (x => x);
} }
render(data) { render(data) {
return this.formatter(selectPath(data, this.contextPath)); return this.formatter(selectPath(data, this.contextPath));
} }
} }
class LetTemplatePart { class LetTemplatePart {
constructor(name, expression) { constructor(name, expression) {
this.name = name; this.name = name;
this.expression = expression; this.expression = expression;
} }
declareScoped(scope, data) { declareScoped(scope, data) {
scope.set(this.name, selectPath(data, this.expression)); scope.set(this.name, selectPath(data, this.expression));
} }
render(_data) { render(_data) {
return ""; return '';
} }
} }
class ListTemplatePart { class ListTemplatePart {
constructor(varNames, contextPath, innerTemplate, emptyTemplate, formatter) { constructor(varNames, contextPath, innerTemplate, emptyTemplate, formatter) {
this.varNames = varNames; this.varNames = varNames;
this.contextPath = contextPath; this.contextPath = contextPath;
this.formatter = formatter || ((x) => x); this.formatter = formatter || (x => x);
this.innerTemplate = innerTemplate; this.innerTemplate = innerTemplate;
this.emptyTemplate = emptyTemplate; this.emptyTemplate = emptyTemplate;
}
render(data) {
const list = this.formatter(selectPath(data, this.contextPath));
const arr = Array.isArray(list) ? list : Array.from(list);
if (arr.length === 0) {
return this.emptyTemplate ? this.emptyTemplate.render(data) : "";
} }
let result = ""; render(data) {
const count = arr.length; const list = this.formatter(selectPath(data, this.contextPath));
for (let index = 0; index < count; index++) { const arr = Array.isArray(list) ? list : Array.from(list);
const scope = new ScopeDict();
const item = arr[index]; if (arr.length === 0) {
if (this.varNames.length === 1) { return this.emptyTemplate ? this.emptyTemplate.render(data) : '';
scope.setBuiltin(this.varNames[0], item);
} else {
for (let v = 0; v < this.varNames.length; v++) {
scope.setBuiltin(this.varNames[v], item[v]);
} }
}
scope.setBuiltin("$index", index);
scope.setBuiltin("$first", index === 0);
scope.setBuiltin("$last", index === count - 1);
scope.setBuiltin("$even", index % 2 === 0);
scope.setBuiltin("$odd", index % 2 === 1);
scope.setBuiltin("$count", count);
result += this.innerTemplate.render(data, scope);
}
return result; let result = '';
} const count = arr.length;
for (let index = 0; index < count; index++) {
const scope = new ScopeDict();
const item = arr[index];
if (this.varNames.length === 1) {
scope.setBuiltin(this.varNames[0], item);
} else {
for (let v = 0; v < this.varNames.length; v++) {
scope.setBuiltin(this.varNames[v], item[v]);
}
}
scope.setBuiltin('$index', index);
scope.setBuiltin('$first', index === 0);
scope.setBuiltin('$last', index === count - 1);
scope.setBuiltin('$even', index % 2 === 0);
scope.setBuiltin('$odd', index % 2 === 1);
scope.setBuiltin('$count', count);
result += this.innerTemplate.render(data, scope);
}
return result;
}
} }
class ConditionalTemplatePart { class ConditionalTemplatePart {
constructor(contextPath, condition, trueTemplate, falseTemplate, formatter) { constructor(contextPath, condition, trueTemplate, falseTemplate, formatter) {
this.contextPath = contextPath; this.contextPath = contextPath;
this.formatter = formatter || ((x) => x); this.formatter = formatter || (x => x);
this.condition = condition; this.condition = condition;
this.trueTemplate = trueTemplate; this.trueTemplate = trueTemplate;
this.falseTemplate = falseTemplate; this.falseTemplate = falseTemplate;
} }
render(data) { render(data) {
const selectedData = this.formatter(selectPath(data, this.contextPath)); const selectedData = this.formatter(selectPath(data, this.contextPath));
if (this.condition(selectedData)) { if (this.condition(selectedData)) {
return this.trueTemplate ? this.trueTemplate.render(data) : ""; return this.trueTemplate ? this.trueTemplate.render(data) : '';
} else { } else {
return this.falseTemplate ? this.falseTemplate.render(data) : ""; return this.falseTemplate ? this.falseTemplate.render(data) : '';
}
} }
}
} }
export class Template { export class Template {
constructor(templateString) { constructor(templateString) {
if (templateString != null) { if (templateString != null) {
this.parts = this._parseBlock(templateString); this.parts = this._parseBlock(templateString);
}
}
_parseBlock(str) {
const parts = [];
let i = 0;
while (i < str.length) {
// {{ expression }} or {{ expression:format }}
if (str[i] === "{" && str[i + 1] === "{") {
const end = str.indexOf("}}", i + 2);
if (end === -1) throw new Error("Unclosed {{ }}");
const content = str.substring(i + 2, end).trim();
let expression,
formatter = null;
const colonIdx = content.lastIndexOf(":");
if (colonIdx > 0) {
const possibleFormat = content.substring(colonIdx + 1).trim();
if (/^[0#.,yMdHhmsafzZ\-\/: ]+$/.test(possibleFormat)) {
expression = content.substring(0, colonIdx).trim();
formatter = createFormatter(possibleFormat);
} else {
expression = content;
}
} else {
expression = content;
} }
parts.push(new VariableTemplatePart(expression, formatter));
i = end + 2;
continue;
}
// @for(item of expression){...} @empty{...}
if (str.startsWith("@for(", i)) {
const parenOpen = i + 4;
const parenClose = findClosingParen(str, parenOpen);
const forClause = str.substring(parenOpen + 1, parenClose).trim();
const ofIdx = forClause.indexOf(" of ");
if (ofIdx === -1)
throw new Error('@for missing "of": @for(item of expression)');
const varNames = forClause
.substring(0, ofIdx)
.split(",")
.map((v) => v.trim());
const expression = forClause.substring(ofIdx + 4).trim();
const braceOpen = str.indexOf("{", parenClose + 1);
if (braceOpen === -1) throw new Error("@for missing block");
const braceClose = findClosingBrace(str, braceOpen);
const blockContent = str.substring(braceOpen + 1, braceClose);
const innerTemplate = new Template(null);
innerTemplate.parts = this._parseBlock(blockContent);
let emptyTemplate = null;
let afterBlock = braceClose + 1;
const remaining = str.substring(afterBlock);
const emptyMatch = remaining.match(/^\s*@empty\s*\{/);
if (emptyMatch) {
const emptyBraceOpen = afterBlock + emptyMatch[0].length - 1;
const emptyBraceClose = findClosingBrace(str, emptyBraceOpen);
const emptyContent = str.substring(
emptyBraceOpen + 1,
emptyBraceClose,
);
emptyTemplate = new Template(null);
emptyTemplate.parts = this._parseBlock(emptyContent);
afterBlock = emptyBraceClose + 1;
}
parts.push(
new ListTemplatePart(
varNames,
expression,
innerTemplate,
emptyTemplate,
),
);
i = afterBlock;
continue;
}
// @if(expression){...}@else{...}
if (str.startsWith("@if(", i)) {
const parenOpen = i + 3;
const parenClose = findClosingParen(str, parenOpen);
const expression = str.substring(parenOpen + 1, parenClose).trim();
const trueBraceOpen = str.indexOf("{", parenClose + 1);
if (trueBraceOpen === -1) throw new Error("@if missing block");
const trueBraceClose = findClosingBrace(str, trueBraceOpen);
const trueContent = str.substring(trueBraceOpen + 1, trueBraceClose);
const trueTemplate = new Template(null);
trueTemplate.parts = this._parseBlock(trueContent);
let falseTemplate = null;
let afterBlock = trueBraceClose + 1;
const remaining = str.substring(afterBlock);
const elseMatch = remaining.match(/^\s*@else\s*\{/);
if (elseMatch) {
const falseBraceOpen = afterBlock + elseMatch[0].length - 1;
const falseBraceClose = findClosingBrace(str, falseBraceOpen);
const falseContent = str.substring(
falseBraceOpen + 1,
falseBraceClose,
);
falseTemplate = new Template(null);
falseTemplate.parts = this._parseBlock(falseContent);
afterBlock = falseBraceClose + 1;
}
parts.push(
new ConditionalTemplatePart(
expression,
(val) => !!val,
trueTemplate,
falseTemplate,
),
);
i = afterBlock;
continue;
}
// @let name = expression (ends at newline or end of string)
if (str.startsWith("@let ", i)) {
const lineEnd = str.indexOf("\n", i);
const end = lineEnd === -1 ? str.length : lineEnd;
const declaration = str.substring(i + 5, end).trim();
const eqIdx = declaration.indexOf("=");
if (eqIdx === -1) throw new Error("Invalid @let: missing =");
const name = declaration.substring(0, eqIdx).trim();
const expression = declaration.substring(eqIdx + 1).trim();
parts.push(new LetTemplatePart(name, expression));
i = end + 1;
continue;
}
// Static text — collect until next special token
let end = i;
while (end < str.length) {
if (str[end] === "{" && str[end + 1] === "{") break;
if (
str[end] === "@" &&
(str.startsWith("@for(", end) ||
str.startsWith("@if(", end) ||
str.startsWith("@let ", end))
)
break;
end++;
}
if (end > i) {
parts.push(new StaticTemplatePart(str.substring(i, end)));
i = end;
}
} }
return parts; _parseBlock(str) {
} const parts = [];
let i = 0;
render(data, parentScope = new ScopeDict()) { while (i < str.length) {
const scope = parentScope.clone(); // {{ expression }} or {{ expression:format }}
const proxy = createScopeProxy(data, scope); if (str[i] === '{' && str[i + 1] === '{') {
const end = str.indexOf('}}', i + 2);
if (end === -1) throw new Error('Unclosed {{ }}');
const content = str.substring(i + 2, end).trim();
let result = ""; let expression, formatter = null;
for (const part of this.parts) { const colonIdx = content.lastIndexOf(':');
part.declareScoped?.(scope, proxy); if (colonIdx > 0) {
result += part.render(proxy); const possibleFormat = content.substring(colonIdx + 1).trim();
if (/^[0#.,yMdHhmsafzZ\-\/: ]+$/.test(possibleFormat)) {
expression = content.substring(0, colonIdx).trim();
formatter = createFormatter(possibleFormat);
} else {
expression = content;
}
} else {
expression = content;
}
parts.push(new VariableTemplatePart(expression, formatter));
i = end + 2;
continue;
}
// @for(item of expression){...} @empty{...}
if (str.startsWith('@for(', i)) {
const parenOpen = i + 4;
const parenClose = findClosingParen(str, parenOpen);
const forClause = str.substring(parenOpen + 1, parenClose).trim();
const ofIdx = forClause.indexOf(' of ');
if (ofIdx === -1) throw new Error('@for missing "of": @for(item of expression)');
const varNames = forClause.substring(0, ofIdx).split(',').map(v => v.trim());
const expression = forClause.substring(ofIdx + 4).trim();
const braceOpen = str.indexOf('{', parenClose + 1);
if (braceOpen === -1) throw new Error('@for missing block');
const braceClose = findClosingBrace(str, braceOpen);
const blockContent = str.substring(braceOpen + 1, braceClose);
const innerTemplate = new Template(null);
innerTemplate.parts = this._parseBlock(blockContent);
let emptyTemplate = null;
let afterBlock = braceClose + 1;
const remaining = str.substring(afterBlock);
const emptyMatch = remaining.match(/^\s*@empty\s*\{/);
if (emptyMatch) {
const emptyBraceOpen = afterBlock + emptyMatch[0].length - 1;
const emptyBraceClose = findClosingBrace(str, emptyBraceOpen);
const emptyContent = str.substring(emptyBraceOpen + 1, emptyBraceClose);
emptyTemplate = new Template(null);
emptyTemplate.parts = this._parseBlock(emptyContent);
afterBlock = emptyBraceClose + 1;
}
parts.push(new ListTemplatePart(varNames, expression, innerTemplate, emptyTemplate));
i = afterBlock;
continue;
}
// @if(expression){...}@else{...}
if (str.startsWith('@if(', i)) {
const parenOpen = i + 3;
const parenClose = findClosingParen(str, parenOpen);
const expression = str.substring(parenOpen + 1, parenClose).trim();
const trueBraceOpen = str.indexOf('{', parenClose + 1);
if (trueBraceOpen === -1) throw new Error('@if missing block');
const trueBraceClose = findClosingBrace(str, trueBraceOpen);
const trueContent = str.substring(trueBraceOpen + 1, trueBraceClose);
const trueTemplate = new Template(null);
trueTemplate.parts = this._parseBlock(trueContent);
let falseTemplate = null;
let afterBlock = trueBraceClose + 1;
const remaining = str.substring(afterBlock);
const elseMatch = remaining.match(/^\s*@else\s*\{/);
if (elseMatch) {
const falseBraceOpen = afterBlock + elseMatch[0].length - 1;
const falseBraceClose = findClosingBrace(str, falseBraceOpen);
const falseContent = str.substring(falseBraceOpen + 1, falseBraceClose);
falseTemplate = new Template(null);
falseTemplate.parts = this._parseBlock(falseContent);
afterBlock = falseBraceClose + 1;
}
parts.push(new ConditionalTemplatePart(expression, val => !!val, trueTemplate, falseTemplate));
i = afterBlock;
continue;
}
// @let name = expression (ends at newline or end of string)
if (str.startsWith('@let ', i)) {
const lineEnd = str.indexOf('\n', i);
const end = lineEnd === -1 ? str.length : lineEnd;
const declaration = str.substring(i + 5, end).trim();
const eqIdx = declaration.indexOf('=');
if (eqIdx === -1) throw new Error('Invalid @let: missing =');
const name = declaration.substring(0, eqIdx).trim();
const expression = declaration.substring(eqIdx + 1).trim();
parts.push(new LetTemplatePart(name, expression));
i = end + 1;
continue;
}
// Static text — collect until next special token
let end = i;
while (end < str.length) {
if (str[end] === '{' && str[end + 1] === '{') break;
if (str[end] === '@' && (
str.startsWith('@for(', end) ||
str.startsWith('@if(', end) ||
str.startsWith('@let ', end)
)) break;
end++;
}
if (end > i) {
parts.push(new StaticTemplatePart(str.substring(i, end)));
i = end;
}
}
return parts;
}
render(data, parentScope = new ScopeDict()) {
const scope = parentScope.clone();
const proxy = createScopeProxy(data, scope);
let result = '';
for (const part of this.parts) {
part.declareScoped?.(scope, proxy);
result += part.render(proxy);
}
return result;
} }
return result;
}
} }
-55
View File
@@ -1,55 +0,0 @@
import {
initRouter,
Route,
ViewChild,
Component,
ComponentInput,
ComponentDefinition,
} from "./pwa.js";
class TestComponent extends Component {
static get definition() {
return new ComponentDefinition({
name: "test-component",
template: `<div>
<h1>Test Component</h1>
<p>This is a test component.</p>
<button
id="test-button"
(click)="incrementCount()"
[class.green-button]="count % 2 !== 0"
[class.red-button]="count % 2 === 0"
>Count: {{count}}</button>
</div>`,
style: `
.red-button {
background-color: red;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
.green-button {
background-color: green;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
`
});
}
count = new ComponentInput(0);
incrementCount() {
this.count++;
}
}
const route1 = new Route("/counter", TestComponent);
const route2 = new Route("/counter/:count", TestComponent);
initRouter("routerOutlet", "styleOutlet", [route1, route2]);
-204
View File
@@ -1,204 +0,0 @@
// ─── parseDate (C# DateTime.ParseExact style) ───
// Parses a date string using an exact format pattern.
// Supported tokens:
// yyyy — 4-digit year
// yy — 2-digit year (assumes 2000+)
// MM — 2-digit month (01–12)
// M — 1 or 2-digit month
// dd — 2-digit day (01–31)
// d — 1 or 2-digit day
// HH — 2-digit hour 24h (00–23)
// H — 1 or 2-digit hour 24h
// hh — 2-digit hour 12h (01–12)
// h — 1 or 2-digit hour 12h
// mm — 2-digit minute (00–59)
// m — 1 or 2-digit minute
// ss — 2-digit second (00–59)
// s — 1 or 2-digit second
// fff — 3-digit milliseconds
// ff — 2-digit (tenths + hundredths)
// f — 1-digit (tenths)
// tt — AM/PM
// t — A/P
// Z — literal 'Z' (UTC marker)
// K — timezone offset (+HH:mm, -HH:mm, or Z)
//
// All other characters are matched literally.
// Returns Date on success, null on failure.
const TOKEN_ORDER = [
"yyyy", "yy",
"MM", "M",
"dd", "d",
"HH", "H", "hh", "h",
"mm", "m",
"ss", "s",
"fff", "ff", "f",
"tt", "t",
"K", "Z",
];
const TOKEN_PATTERNS = {
yyyy: "(\\d{4})",
yy: "(\\d{2})",
MM: "(\\d{2})",
M: "(\\d{1,2})",
dd: "(\\d{2})",
d: "(\\d{1,2})",
HH: "(\\d{2})",
H: "(\\d{1,2})",
hh: "(\\d{2})",
h: "(\\d{1,2})",
mm: "(\\d{2})",
m: "(\\d{1,2})",
ss: "(\\d{2})",
s: "(\\d{1,2})",
fff: "(\\d{3})",
ff: "(\\d{2})",
f: "(\\d{1})",
tt: "(AM|PM|am|pm)",
t: "([AaPp])",
K: "(Z|[+-]\\d{2}:\\d{2})",
Z: "(Z)",
};
function buildFormatRegex(format) {
const groups = [];
let regexStr = "";
let i = 0;
while (i < format.length) {
let matched = false;
for (const token of TOKEN_ORDER) {
if (format.startsWith(token, i)) {
groups.push(token);
regexStr += TOKEN_PATTERNS[token];
i += token.length;
matched = true;
break;
}
}
if (!matched) {
// Escape literal character
regexStr += format[i].replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
i++;
}
}
return { regex: new RegExp("^" + regexStr + "$"), groups };
}
export function parseDate(input, format) {
if (input == null || format == null) return null;
if (input instanceof Date) return input;
const str = String(input);
const { regex, groups } = buildFormatRegex(format);
const match = str.match(regex);
if (!match) return null;
let year = 0, month = 1, day = 1;
let hour = 0, minute = 0, second = 0, ms = 0;
let isPM = false, isAM = false;
let tzOffset = null; // minutes
for (let g = 0; g < groups.length; g++) {
const token = groups[g];
const val = match[g + 1];
switch (token) {
case "yyyy": year = parseInt(val, 10); break;
case "yy": year = 2000 + parseInt(val, 10); break;
case "MM":
case "M": month = parseInt(val, 10); break;
case "dd":
case "d": day = parseInt(val, 10); break;
case "HH":
case "H": hour = parseInt(val, 10); break;
case "hh":
case "h": hour = parseInt(val, 10); break;
case "mm":
case "m": minute = parseInt(val, 10); break;
case "ss":
case "s": second = parseInt(val, 10); break;
case "fff": ms = parseInt(val, 10); break;
case "ff": ms = parseInt(val, 10) * 10; break;
case "f": ms = parseInt(val, 10) * 100; break;
case "tt": isPM = val.toUpperCase() === "PM"; isAM = val.toUpperCase() === "AM"; break;
case "t": isPM = val.toUpperCase() === "P"; isAM = val.toUpperCase() === "A"; break;
case "Z": tzOffset = 0; break;
case "K":
if (val === "Z") {
tzOffset = 0;
} else {
const sign = val[0] === "+" ? 1 : -1;
const [h, m] = val.substring(1).split(":").map(Number);
tzOffset = sign * (h * 60 + m);
}
break;
}
}
// 12h → 24h conversion
if (isPM && hour < 12) hour += 12;
if (isAM && hour === 12) hour = 0;
if (tzOffset !== null) {
// Build UTC date, apply offset
const utcMs = Date.UTC(year, month - 1, day, hour, minute, second, ms);
return new Date(utcMs - tzOffset * 60000);
}
return new Date(year, month - 1, day, hour, minute, second, ms);
}
export function formatDate(date, spec) {
const pad = (n, l = 2) => String(n).padStart(l, "0");
const tokens = {
yyyy: date.getFullYear(),
yy: String(date.getFullYear()).slice(-2),
MM: pad(date.getMonth() + 1),
M: date.getMonth() + 1,
dd: pad(date.getDate()),
d: date.getDate(),
HH: pad(date.getHours()),
H: date.getHours(),
hh: pad(date.getHours() % 12 || 12),
h: date.getHours() % 12 || 12,
mm: pad(date.getMinutes()),
m: date.getMinutes(),
ss: pad(date.getSeconds()),
s: date.getSeconds(),
fff: pad(date.getMilliseconds(), 3),
};
let result = spec;
for (const [tok, val] of Object.entries(tokens).sort(
(a, b) => b[0].length - a[0].length,
)) {
result = result.replaceAll(tok, String(val));
}
return result;
}
// ─── Input transform presets ───
export const IntInput = { transform: parseInt };
export const FloatInput = { transform: parseFloat };
export const BoolInput = {
transform: (v) => {
if (typeof v === "boolean") return v;
if (typeof v === "string") {
if (v.toLowerCase() === "true") return true;
if (v.toLowerCase() === "false") return false;
}
return Boolean(v);
},
};
export function DateInput(format) {
return {
transform: (v) => parseDate(v, format),
};
}
export const IsoDateInput = DateInput("yyyy-MM-ddTHH:mm:ssK");
+216 -635
View File
@@ -1,656 +1,237 @@
<!-- OnlyPrompt - Marketplace page: dynamic prompts, category filter, sort, crypto payment modal --> <!-- OnlyPrompt - Marketplace page:
- Browse and filter AI prompts with buy/view details buttons and pricing
- Added sort dropdown (Best Rating, Price Low to High, Price High to Low) - UI only -->
<!doctype html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OnlyPrompt - Marketplace</title> <title>OnlyPrompt - Marketplace</title>
<link rel="stylesheet" href="../css/variables.css" /> <link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/base.css" /> <link rel="stylesheet" href="../css/base.css">
<link rel="stylesheet" href="../css/sidebar.css" /> <link rel="stylesheet" href="../css/sidebar.css">
<link rel="stylesheet" href="../css/login.css" /> <link rel="stylesheet" href="../css/login.css">
<link rel="stylesheet" href="../css/topbar.css" /> <link rel="stylesheet" href="../css/topbar.css">
<link rel="stylesheet" href="../css/marketplace.css" /> <link rel="stylesheet" href="../css/marketplace.css">
<script src="../js/profile-shared.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<link <style>
rel="stylesheet" /* Additional inline style for sort dropdown – can be moved to marketplace.css */
href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" .filter-sort-row {
/> display: flex;
<style> justify-content: space-between;
/* Additional inline style for sort dropdown – can be moved to marketplace.css */ align-items: center;
flex-wrap: wrap;
gap: 16px;
margin-bottom: 32px;
border-bottom: 1px solid #e5e7eb;
padding-bottom: 16px;
}
.filter-buttons {
margin-bottom: 0;
border-bottom: none;
padding-bottom: 0;
}
.sort-dropdown {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 30px;
padding: 8px 16px;
font-size: 0.9rem;
font-weight: 500;
color: #334155;
cursor: pointer;
outline: none;
}
.sort-dropdown:hover {
border-color: #94a3b8;
}
@media (max-width: 700px) {
.filter-sort-row { .filter-sort-row {
display: flex; flex-direction: column;
justify-content: space-between; align-items: stretch;
align-items: center;
flex-wrap: wrap;
gap: 16px;
margin-bottom: 32px;
border-bottom: 1px solid #e5e7eb;
padding-bottom: 16px;
}
.filter-buttons {
margin-bottom: 0;
border-bottom: none;
padding-bottom: 0;
} }
.sort-dropdown { .sort-dropdown {
background: #f8fafc; align-self: flex-start;
border: 1px solid #e2e8f0;
border-radius: 30px;
padding: 8px 16px;
font-size: 0.9rem;
font-weight: 500;
color: #334155;
cursor: pointer;
outline: none;
} }
.sort-dropdown:hover { }
border-color: #94a3b8; </style>
} </head>
@media (max-width: 700px) { <body>
.filter-sort-row { <div class="layout" style="display: flex; min-height: 100vh; background: var(--bg);">
flex-direction: column;
align-items: stretch;
}
.sort-dropdown {
align-self: flex-start;
}
}
</style>
</head>
<body>
<div
class="layout"
style="display: flex; min-height: 100vh; background: var(--bg)"
>
<div id="sidebar-container"></div>
<div style="flex: 1; display: flex; flex-direction: column"> <div id="sidebar-container"></div>
<div id="topbar-container"></div>
<main class="marketplace-main"> <div style="flex:1; margin:40px auto; max-width:950px;">
<!-- Header -->
<div class="marketplace-header"> <div id="topbar-container"></div>
<h1>Marketplace</h1>
<p>Browse and discover high-quality AI prompts</p> <main class="marketplace-main">
<!-- Header -->
<div class="marketplace-header">
<h1>Marketplace</h1>
<p>Browse and discover high-quality AI prompts</p>
</div>
<!-- Filter + Sort Row -->
<div class="filter-sort-row">
<div class="filter-buttons">
<button class="filter-btn active">All</button>
<button class="filter-btn">Writing</button>
<button class="filter-btn">Coding</button>
<button class="filter-btn">Art</button>
<button class="filter-btn">Marketing</button>
<button class="filter-btn">Video</button>
<button class="filter-btn">Data</button>
</div> </div>
<select class="sort-dropdown" aria-label="Sort prompts">
<option value="best">Best Rating</option>
<option value="price_low">Price: Low to High</option>
<option value="price_high">Price: High to Low</option>
</select>
</div>
<!-- Filter + Sort Row --> <!-- Prompts Grid -->
<div class="filter-sort-row"> <div class="prompts-grid">
<div class="filter-buttons" id="category-filters">
<button class="filter-btn active" data-category="">All</button> <!-- Prompt Card 1 -->
<div class="prompt-card">
<img src="../images/content/market1.png" alt="Creative Blog Post Generator" class="prompt-img">
<div class="prompt-info">
<h3 class="prompt-title">Creative Blog Post Generator</h3>
<div class="prompt-author">@JaneDoe</div>
<p class="prompt-description">Generate engaging blog posts in minutes to captivate your audience.</p>
<div class="prompt-rating">
<span><i class="bi bi-star-fill"></i> 4.8</span>
<span>(124 reviews)</span>
</div>
<div class="prompt-price">$19.99</div>
<div class="prompt-actions">
<button class="buy-btn">Buy Now</button>
<button class="details-btn">View Details</button>
</div>
</div> </div>
<select
class="sort-dropdown"
id="sort-select"
aria-label="Sort prompts"
>
<option value="date|false">Newest</option>
<option value="date|true">Oldest</option>
<option value="rating|false">Best Rating</option>
<option value="rating|true">Lowest Rating</option>
<option value="free|true">Free</option>
<option value="price|true">Lowest Price</option>
<option value="price|false">Highest Price</option>
</select>
</div> </div>
<!-- Prompts Grid --> <!-- Prompt Card 2 -->
<div class="prompts-grid" id="prompts-grid"></div> <div class="prompt-card">
<img src="../images/content/market2.png" alt="Python Code Assistant" class="prompt-img">
<!-- Empty State --> <div class="prompt-info">
<div <h3 class="prompt-title">Python Code Assistant</h3>
id="market-empty" <div class="prompt-author">@JaneDoe</div>
style=" <p class="prompt-description">Efficiently debug and write Python code with AI assistance.</p>
display: none; <div class="prompt-rating">
text-align: center; <span><i class="bi bi-star-fill"></i> 4.7</span>
padding: 60px 20px; <span>(98 reviews)</span>
color: #64748b; </div>
" <div class="prompt-price">$19.99</div>
> <div class="prompt-actions">
<i <button class="buy-btn">Buy Now</button>
class="bi bi-bag-x" <button class="details-btn">View Details</button>
style="font-size: 3rem; display: block; margin-bottom: 16px" </div>
></i> </div>
<h3 style="margin-bottom: 8px">No prompts found</h3>
<p>Try a different category or search term.</p>
</div> </div>
<!-- Error State --> <!-- Prompt Card 3 -->
<div <div class="prompt-card">
id="market-error" <img src="../images/content/market3.png" alt="Digital Art Style Guide" class="prompt-img">
style=" <div class="prompt-info">
display: none; <h3 class="prompt-title">Digital Art Style Guide</h3>
text-align: center; <div class="prompt-author">@JaneDoe</div>
padding: 60px 20px; <p class="prompt-description">Create stunning digital art styles with this comprehensive guide.</p>
color: #ef4444; <div class="prompt-rating">
" <span><i class="bi bi-star-fill"></i> 4.8</span>
> <span>(156 reviews)</span>
<i </div>
class="bi bi-exclamation-circle" <div class="prompt-price">$19.99</div>
style="font-size: 3rem; display: block; margin-bottom: 16px" <div class="prompt-actions">
></i> <button class="buy-btn">Buy Now</button>
<h3 style="margin-bottom: 8px">Could not load prompts</h3> <button class="details-btn">View Details</button>
<p id="market-error-msg"></p> </div>
</div>
</div> </div>
</main>
</div> <!-- Prompt Card 4 -->
<div class="prompt-card">
<img src="../images/content/market4.png" alt="Marketing Copywriter" class="prompt-img">
<div class="prompt-info">
<h3 class="prompt-title">Marketing Copywriter</h3>
<div class="prompt-author">@JaneDoe</div>
<p class="prompt-description">Generate engaging marketing copy in minutes.</p>
<div class="prompt-rating">
<span><i class="bi bi-star-fill"></i> 4.8</span>
<span>(112 reviews)</span>
</div>
<div class="prompt-price">$19.99</div>
<div class="prompt-actions">
<button class="buy-btn">Buy Now</button>
<button class="details-btn">View Details</button>
</div>
</div>
</div>
<!-- Prompt Card 5 -->
<div class="prompt-card">
<img src="../images/content/market5.png" alt="Midjourney Image Prompts" class="prompt-img">
<div class="prompt-info">
<h3 class="prompt-title">Midjourney Image Prompts</h3>
<div class="prompt-author">@JaneDoe</div>
<p class="prompt-description">Curated prompts for stunning Midjourney images.</p>
<div class="prompt-rating">
<span><i class="bi bi-star-fill"></i> 4.7</span>
<span>(203 reviews)</span>
</div>
<div class="prompt-price">$19.99</div>
<div class="prompt-actions">
<button class="buy-btn">Buy Now</button>
<button class="details-btn">View Details</button>
</div>
</div>
</div>
<!-- Prompt Card 6 -->
<div class="prompt-card">
<img src="../images/content/market6.png" alt="UI Design Assistant" class="prompt-img">
<div class="prompt-info">
<h3 class="prompt-title">UI Design Assistant</h3>
<div class="prompt-author">@JaneDoe</div>
<p class="prompt-description">Generate UI components and design systems with AI.</p>
<div class="prompt-rating">
<span><i class="bi bi-star-fill"></i> 4.9</span>
<span>(87 reviews)</span>
</div>
<div class="prompt-price">$19.99</div>
<div class="prompt-actions">
<button class="buy-btn">Buy Now</button>
<button class="details-btn">View Details</button>
</div>
</div>
</div>
</div>
</main>
</div> </div>
</div>
<!-- ── Payment Modal ─────────────────────────────────────────────── --> <script>
<div fetch('../html/sidebar.html')
id="payment-overlay" .then(r => r.text())
style=" .then(data => {
display: none; document.getElementById('sidebar-container').innerHTML = data;
position: fixed; // Remove 'active' from all sidebar links
inset: 0; document.querySelectorAll('#sidebar-container .sidebar a').forEach(link => {
background: rgba(0, 0, 0, 0.5); link.classList.remove('active');
z-index: 1000;
align-items: center;
justify-content: center;
"
>
<div
style="
background: #fff;
border-radius: 16px;
padding: 32px;
max-width: 460px;
width: 90%;
position: relative;
max-height: 90vh;
overflow-y: auto;
"
>
<button
onclick="closePayment()"
style="
position: absolute;
top: 14px;
right: 18px;
background: none;
border: none;
font-size: 1.4rem;
cursor: pointer;
color: #64748b;
"
>
&#x2715;
</button>
<!-- Step 1: Choose method -->
<div id="pay-step-1">
<h2 style="margin-bottom: 4px">Subscribe to access</h2>
<p
id="pay-prompt-title"
style="color: #6366f1; font-weight: 600; margin-bottom: 16px"
></p>
<p style="color: #64748b; margin-bottom: 24px">
Choose a payment method to unlock this prompt:
</p>
<div style="display: flex; flex-direction: column; gap: 12px">
<button class="pay-method-btn" onclick="selectCrypto('btc')">
<span style="font-size: 1.4rem">₿</span> Bitcoin (BTC)
<span
id="price-btc"
style="margin-left: auto; font-size: 0.85rem; color: #94a3b8"
></span>
</button>
<button class="pay-method-btn" onclick="selectCrypto('eth')">
<span style="font-size: 1.4rem">Ξ</span> Ethereum (ETH)
<span
id="price-eth"
style="margin-left: auto; font-size: 0.85rem; color: #94a3b8"
></span>
</button>
<button class="pay-method-btn" onclick="selectCrypto('sol')">
<span style="font-size: 1.4rem">◎</span> Solana (SOL)
<span
id="price-sol"
style="margin-left: auto; font-size: 0.85rem; color: #94a3b8"
></span>
</button>
<button class="pay-method-btn" onclick="selectCrypto('usdt')">
<span style="font-size: 1.4rem">₮</span> USDT (TRC-20)
<span
id="price-usdt"
style="margin-left: auto; font-size: 0.85rem; color: #94a3b8"
></span>
</button>
</div>
<p
style="
margin-top: 20px;
font-size: 0.8rem;
color: #94a3b8;
text-align: center;
"
>
<i class="bi bi-shield-lock-fill"></i> Payments are processed
on-chain. No account needed.
</p>
</div>
<!-- Step 2: Send payment -->
<div id="pay-step-2" style="display: none">
<button
onclick="backToStep1()"
style="
background: none;
border: none;
color: #6366f1;
cursor: pointer;
margin-bottom: 16px;
font-size: 0.9rem;
"
>
&#8592; Back
</button>
<h2 id="pay-crypto-title" style="margin-bottom: 8px"></h2>
<p style="color: #64748b; margin-bottom: 8px">
Send exactly <strong id="pay-amount"></strong> to:
</p>
<div
style="
background: #f1f5f9;
border-radius: 10px;
padding: 14px 16px;
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 8px;
"
>
<code
id="pay-address"
style="font-size: 0.85rem; word-break: break-all; flex: 1"
></code>
<button
onclick="copyAddress()"
title="Copy"
style="
background: none;
border: none;
cursor: pointer;
color: #6366f1;
font-size: 1.1rem;
"
>
<i class="bi bi-clipboard"></i>
</button>
</div>
<p style="font-size: 0.78rem; color: #94a3b8; margin-bottom: 20px">
⚠️ Only send the exact amount. Payments are non-refundable.
</p>
<div
style="
background: #fef9c3;
border: 1px solid #fde68a;
border-radius: 10px;
padding: 12px 14px;
font-size: 0.82rem;
color: #92400e;
margin-bottom: 20px;
"
>
<i class="bi bi-info-circle-fill"></i> After sending, click the
button below to confirm. Access will be granted once the transaction
is verified.
</div>
<button
onclick="confirmPayment()"
style="
width: 100%;
padding: 12px;
background: #6366f1;
color: #fff;
border: none;
border-radius: 10px;
font-weight: 600;
font-size: 1rem;
cursor: pointer;
"
>
I've sent the payment ✓
</button>
</div>
<!-- Step 3: Success -->
<div
id="pay-step-3"
style="display: none; text-align: center; padding: 20px 0"
>
<i
class="bi bi-check-circle-fill"
style="
font-size: 3.5rem;
color: #10b981;
display: block;
margin-bottom: 16px;
"
></i>
<h2 style="margin-bottom: 8px">Payment received!</h2>
<p style="color: #64748b; margin-bottom: 24px">
Your access is being activated. This usually takes 1–2 minutes.
</p>
<button
onclick="closePayment()"
style="
padding: 12px 28px;
background: #6366f1;
color: #fff;
border: none;
border-radius: 10px;
font-weight: 600;
cursor: pointer;
"
>
Done
</button>
</div>
</div>
</div>
<script type="module">
// ── Sidebar & Topbar ──────────────────────────────────────────────
fetch("/sidebar.html")
.then((r) => r.text())
.then((data) => {
document.getElementById("sidebar-container").innerHTML = data;
document
.querySelectorAll("#sidebar-container .sidebar a")
.forEach((l) => l.classList.remove("active"));
const link = document.querySelectorAll(
"#sidebar-container .sidebar li a",
)[1];
if (link) link.classList.add("active");
}); });
fetch("/topbar.html") // Set 'active' on the second link (Marketplace) - index 1
.then((r) => r.text()) const secondLink = document.querySelectorAll('#sidebar-container .sidebar li a')[1];
.then( if (secondLink) secondLink.classList.add('active');
(data) => });
(document.getElementById("topbar-container").innerHTML = data),
);
// ── State ───────────────────────────────────────────────────────── fetch('../html/topbar.html')
let activeCategory = ""; .then(r => r.text())
let searchTimeout; .then(data => document.getElementById('topbar-container').innerHTML = data);
</script>
function timeAgo(dateStr) { </body>
const diff = Date.now() - new Date(dateStr).getTime();
const m = Math.floor(diff / 60000);
if (m < 1) return "just now";
if (m < 60) return `${m}m ago`;
const h = Math.floor(m / 60);
if (h < 24) return `${h}h ago`;
return `${Math.floor(h / 24)}d ago`;
}
function renderStars(rating) {
if (rating == null)
return '<span style="color:#94a3b8;font-size:0.8rem;">No reviews yet</span>';
const stars = Math.round(rating);
return `<span class="prompt-rating"><span style="color:#f59e0b">${"★".repeat(stars)}${"☆".repeat(5 - stars)}</span> ${rating.toFixed(1)}</span>`;
}
function promptPrice(prompt) {
if (prompt.price != null && Number(prompt.price) > 0) {
return `$${Number(prompt.price).toFixed(2)}`;
}
if (prompt.tierLevel) return `$${(prompt.tierLevel * 4.99).toFixed(2)}/mo`;
if (prompt.canAccess === false) return "Paid";
return "Free";
}
function getNumericPrice(prompt) {
if (prompt.price != null && Number(prompt.price) > 0) {
return Number(prompt.price);
}
if (prompt.tierLevel) return prompt.tierLevel * 4.99;
return 0;
}
function applyMarketplaceSort(prompts, sortBy, ascending) {
if (sortBy === "free") {
return prompts.filter((prompt) => getNumericPrice(prompt) === 0);
}
if (sortBy === "price") {
const direction = ascending === "true" ? 1 : -1;
return prompts
.slice()
.sort((a, b) => (getNumericPrice(a) - getNumericPrice(b)) * direction);
}
return prompts;
}
const MARKET_IMAGES = [
"/images/content/market1.png",
"/images/content/market2.png",
"/images/content/market3.png",
"/images/content/market4.png",
"/images/content/market5.png",
"/images/content/market6.png",
];
let cardIndex = 0;
function renderCard(p) {
const paid = p.price != null && Number(p.price) > 0;
const locked = p.canAccess === false || paid || p.tierLevel != null;
const img = p.exampleImageUrl || p._img || MARKET_IMAGES[cardIndex++ % MARKET_IMAGES.length];
return `
<div class="prompt-card">
<img src="${img}" alt="${p.title}" class="prompt-img">
<div class="prompt-info">
<div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
<div style="width:34px;height:34px;border-radius:50%;background:#6366f1;color:#fff;font-weight:700;display:flex;align-items:center;justify-content:center;font-size:0.95rem;flex-shrink:0;">${p.creatorName.charAt(0).toUpperCase()}</div>
<span class="prompt-author">@${p.creatorName}</span>
<span style="margin-left:auto;font-size:0.75rem;color:#94a3b8;">${timeAgo(p.timeStamp)}</span>
</div>
<h3 class="prompt-title">${p.title}</h3>
<div style="margin-bottom:12px;">${renderStars(p.averageRating)}</div>
<div class="prompt-price">${promptPrice(p)}</div>
<div class="prompt-actions">
${
locked
? `<button class="buy-btn" style="background:#ef4444;" onclick='openPayment(${JSON.stringify(p)})'><i class="bi bi-lock-fill"></i> Pay</button>`
: `<button class="buy-btn" style="background:#10b981;" onclick="location.href='/post-detail?id=${p.id}'">Access <i class="bi bi-unlock-fill"></i></button>`
}
${
locked
? `<button class="details-btn" disabled style="opacity:.45;cursor:not-allowed;"><i class="bi bi-lock-fill"></i> Details</button>`
: `<button class="details-btn" onclick="location.href='/post-detail?id=${p.id}'">View Details</button>`
}
</div>
</div>
</div>`;
}
async function loadPrompts() {
const grid = document.getElementById("prompts-grid");
const emptyEl = document.getElementById("market-empty");
const errorEl = document.getElementById("market-error");
const search = document.getElementById("topbarSearchInput")?.value.trim() || "";
const [sortBy, ascending] = document
.getElementById("sort-select")
.value.split("|");
grid.innerHTML = "";
emptyEl.style.display = "none";
errorEl.style.display = "none";
cardIndex = 0;
try {
const apiSortBy = sortBy === "price" || sortBy === "free" ? "date" : sortBy;
const apiAscending = sortBy === "price" || sortBy === "free" ? "false" : ascending;
let url = `/api/v1/prompts?sortBy=${apiSortBy}&ascending=${apiAscending}&limit=50`;
if (activeCategory) url += `&category=${activeCategory}`;
if (search) url += `&search=${encodeURIComponent(search)}`;
const res = await fetch(url);
if (res.status === 401) {
location.href = "/login";
return;
}
if (!res.ok) throw new Error(`Server error ${res.status}`);
let prompts = applyMarketplaceSort(await res.json(), sortBy, ascending);
if (prompts.length === 0) {
emptyEl.style.display = "block";
return;
}
grid.innerHTML = prompts.map(renderCard).join("");
} catch (e) {
document.getElementById("market-error-msg").textContent =
e.message || "Please check if the backend is running.";
errorEl.style.display = "block";
}
}
async function loadCategories() {
try {
const res = await fetch("/api/v1/categories/minimal");
if (!res.ok) return;
const cats = await res.json();
const container = document.getElementById("category-filters");
cats.forEach((c) => {
const btn = document.createElement("button");
btn.className = "filter-btn";
btn.dataset.category = c.slug;
btn.textContent = c.name;
btn.addEventListener("click", () => {
document
.querySelectorAll("#category-filters .filter-btn")
.forEach((b) => b.classList.remove("active"));
btn.classList.add("active");
activeCategory = c.slug;
loadPrompts();
});
container.appendChild(btn);
});
} catch {}
}
// ── Category filter (All) ──────────────────────────────────────────
document
.querySelector("#category-filters .filter-btn")
.addEventListener("click", function () {
document
.querySelectorAll("#category-filters .filter-btn")
.forEach((b) => b.classList.remove("active"));
this.classList.add("active");
activeCategory = "";
loadPrompts();
});
document
.getElementById("sort-select")
.addEventListener("change", loadPrompts);
function wireMarketplaceTopbarSearch() {
const input = document.getElementById("topbarSearchInput");
if (!input || input.dataset.marketplaceSearchReady === "true") return;
input.dataset.marketplaceSearchReady = "true";
input.addEventListener("input", () => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(loadPrompts, 400);
});
}
const topbarObserver = new MutationObserver(wireMarketplaceTopbarSearch);
topbarObserver.observe(document.body, { childList: true, subtree: true });
wireMarketplaceTopbarSearch();
// Make openPayment global
window.openPayment = openPayment;
// ── Payment Modal ──────────────────────────────────────────────────
const CRYPTO_ADDRESSES = {
btc: "1A1zP1eP5QGefi2DMPTfTL5SLmv7Divf1N",
eth: "0x742d35Cc6634C0532925a3b8D4C9B8E4D8F2b1a",
sol: "7EcDhSYGxXyscszYEp35KHN8vvw3svAuLKTzXwCFLtV1",
usdt: "TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE",
};
const CRYPTO_NAMES = {
btc: "Bitcoin (BTC)",
eth: "Ethereum (ETH)",
sol: "Solana (SOL)",
usdt: "USDT TRC-20",
};
let currentPrompt = null;
let currentCrypto = null;
function openPayment(prompt) {
currentPrompt = prompt;
const usd = prompt.price != null && Number(prompt.price) > 0
? Number(prompt.price)
: prompt.tierLevel ? prompt.tierLevel * 4.99 : 0;
document.getElementById("pay-prompt-title").textContent = prompt.title;
document.getElementById("price-btc").textContent =
`≈ ${(usd / 67000).toFixed(6)} BTC`;
document.getElementById("price-eth").textContent =
`≈ ${(usd / 3200).toFixed(5)} ETH`;
document.getElementById("price-sol").textContent =
`≈ ${(usd / 145).toFixed(3)} SOL`;
document.getElementById("price-usdt").textContent =
`${usd.toFixed(2)} USDT`;
document.getElementById("pay-step-1").style.display = "block";
document.getElementById("pay-step-2").style.display = "none";
document.getElementById("pay-step-3").style.display = "none";
document.getElementById("payment-overlay").style.display = "flex";
}
window.selectCrypto = function (crypto) {
currentCrypto = crypto;
const usd = currentPrompt.tierLevel
? currentPrompt.tierLevel * 4.99
: 0;
const amounts = {
btc: `${(usd / 67000).toFixed(6)} BTC`,
eth: `${(usd / 3200).toFixed(5)} ETH`,
sol: `${(usd / 145).toFixed(3)} SOL`,
usdt: `${usd.toFixed(2)} USDT`,
};
document.getElementById("pay-crypto-title").textContent =
CRYPTO_NAMES[crypto];
document.getElementById("pay-amount").textContent = amounts[crypto];
document.getElementById("pay-address").textContent =
CRYPTO_ADDRESSES[crypto];
document.getElementById("pay-step-1").style.display = "none";
document.getElementById("pay-step-2").style.display = "block";
};
window.backToStep1 = function () {
document.getElementById("pay-step-1").style.display = "block";
document.getElementById("pay-step-2").style.display = "none";
};
window.copyAddress = function () {
navigator.clipboard.writeText(CRYPTO_ADDRESSES[currentCrypto]);
};
window.confirmPayment = function () {
document.getElementById("pay-step-2").style.display = "none";
document.getElementById("pay-step-3").style.display = "block";
};
window.closePayment = function () {
document.getElementById("payment-overlay").style.display = "none";
};
document
.getElementById("payment-overlay")
.addEventListener("click", function (e) {
if (e.target === this) closePayment();
});
// ── Init ───────────────────────────────────────────────────────────
await loadCategories();
await loadPrompts();
</script>
</body>
</html> </html>
+98 -398
View File
@@ -1,414 +1,114 @@
<!-- OnlyPrompt - Post Detail: dynamic prompt loaded via API --> <!-- OnlyPrompt - Settings page:
- User preferences with tabs for profile, security, and notifications -->
<!doctype html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OnlyPrompt - Post Detail</title> <title>OnlyPrompt - Post Detail</title>
<link rel="stylesheet" href="../css/variables.css" /> <link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/base.css" /> <link rel="stylesheet" href="../css/base.css">
<link rel="stylesheet" href="../css/sidebar.css" /> <link rel="stylesheet" href="../css/sidebar.css">
<link rel="stylesheet" href="../css/login.css" /> <link rel="stylesheet" href="../css/login.css">
<link rel="stylesheet" href="../css/topbar.css" /> <link rel="stylesheet" href="../css/topbar.css">
<link rel="stylesheet" href="../css/post-detail.css" /> <link rel="stylesheet" href="../css/post-detail.css">
<script src="../js/profile-shared.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<link </head>
rel="stylesheet" <body>
href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" <div class="layout" style="display: flex; min-height: 100vh; background: var(--bg);">
/>
</head>
<body>
<div
class="layout"
style="display: flex; min-height: 100vh; background: var(--bg)"
>
<div id="sidebar-container"></div>
<div style="flex: 1; display: flex; flex-direction: column"> <div id="sidebar-container"></div>
<div id="topbar-container"></div>
<main class="post-detail-main"> <div style="flex:1; display: flex; flex-direction: column;">
<div class="post-detail-container" id="detail-content">
<!-- Loading --> <div id="topbar-container"></div>
<div
id="detail-loading" <main class="post-detail-main">
style="text-align: center; padding: 60px 20px; color: #64748b" <div class="post-detail-container">
> <!-- Header -->
<i <div class="post-header">
class="bi bi-hourglass-split" <h1 class="post-title">Marketing Guru: Campaign Strategist</h1>
style="font-size: 2.5rem; display: block; margin-bottom: 12px" <div class="post-meta">
></i> <span class="category">Marketing</span>
<p>Loading prompt...</p> <span class="category">Business</span>
<span class="category">Copywriting</span>
<span class="updated">Updated: Oct 26, 2023</span>
</div> </div>
<div class="post-stats">
<!-- Error --> <span><i class="bi bi-bookmark-star"></i> 2,109 Saves</span>
<div <span><i class="bi bi-eye"></i> 14.5k Views</span>
id="detail-error"
style="
display: none;
text-align: center;
padding: 60px 20px;
color: #ef4444;
"
>
<i
class="bi bi-exclamation-circle"
style="font-size: 2.5rem; display: block; margin-bottom: 12px"
></i>
<h3 id="detail-error-title">Prompt not found</h3>
<p
id="detail-error-msg"
style="color: #64748b; margin-top: 8px"
></p>
<button
onclick="history.back()"
style="
margin-top: 20px;
padding: 10px 24px;
background: #6366f1;
color: #fff;
border: none;
border-radius: 10px;
font-weight: 600;
cursor: pointer;
"
>
Go Back
</button>
</div> </div>
</div>
<!-- Content (hidden until loaded) --> <!-- Prompt Content Section -->
<div id="detail-body" style="display: none"> <div class="prompt-section">
<!-- Header --> <h2>PROMPT</h2>
<div class="post-header"> <div class="prompt-content">
<div <p>You are an expert marketing strategist and copywriter. I will provide a product name, target audience, and key benefits. Your goal is to create a comprehensive marketing campaign plan, including:</p>
style=" <ul>
display: flex; <li>Campaign objectives</li>
align-items: center; <li>Target Audience: [User Input]</li>
gap: 10px; <li>Expected Output: A detailed marketing plan with channel strategy, messaging, and sample copy</li>
margin-bottom: 16px; <li>Budget considerations and KPIs</li>
" </ul>
> </div>
<div </div>
id="creator-avatar"
style=" <!-- Rating & Like -->
width: 42px; <div class="rating-section">
height: 42px; <div class="rating-stars">
border-radius: 50%; <span><i class="bi bi-star-fill"></i> 4.9</span>
background: #6366f1; <span><i class="bi bi-star-fill"></i> 4.8 (241 Ratings)</span>
color: #fff; </div>
font-weight: 700; <button class="like-btn"><i class="bi bi-heart"></i> Like (212)</button>
font-size: 1.1rem; </div>
display: flex;
align-items: center; <!-- Example Output Section -->
justify-content: center; <div class="example-section">
flex-shrink: 0; <h2>EXAMPLE OUTPUT</h2>
" <div class="example-content">
></div> <h3>Generated Strategy 16px</h3>
<div> <div class="example-output-text">
<span <p><strong>Output: EcoWare Campaign</strong></p>
id="creator-name" <p><strong>Campaign Overview</strong><br>Target Persona: Sarah Jenkins, 28, Eco-conscious</p>
style="font-weight: 600; font-size: 0.95rem" <p><strong>Key Messaging</strong><br>Channel Strategy<br>Sample Copy<br>Social<br>Email</p>
></span>
<span
id="prompt-date"
style="display: block; font-size: 0.8rem; color: #94a3b8"
></span>
</div>
<div style="margin-left: auto">
<span id="tier-badge"></span>
<button
id="edit-prompt-btn"
style="
display: none;
margin-left: 10px;
padding: 6px 14px;
border: none;
border-radius: 10px;
background: #f1f5f9;
color: #334155;
font-weight: 700;
cursor: pointer;
"
>
Edit
</button>
</div>
</div>
<h1 class="post-title" id="prompt-title"></h1>
<div class="post-meta">
<span class="category" id="prompt-category"></span>
<span class="updated" id="prompt-updated"></span>
</div>
<div class="post-stats">
<span id="prompt-rating-stat"></span>
</div>
</div> </div>
<!-- Optional example image (if uploaded in create) -->
<!-- Description --> <div class="example-image" style="display: none;">
<div class="prompt-section" id="desc-section"> <img src="#" alt="Example Output Image">
<h2>DESCRIPTION</h2>
<div class="prompt-content">
<p id="prompt-description"></p>
</div>
</div>
<!-- Prompt Content (only if accessible) -->
<div class="prompt-section" id="prompt-content-section">
<h2>PROMPT</h2>
<div
class="prompt-content"
id="prompt-body"
style="
white-space: pre-wrap;
font-family: monospace;
background: #f8fafc;
border-radius: 10px;
padding: 16px;
font-size: 0.9rem;
line-height: 1.7;
"
></div>
</div>
<!-- Example Output -->
<div class="example-section" id="example-section" style="display: none">
<h2>EXAMPLE OUTPUT</h2>
<div class="example-content">
<div id="example-output-text" class="example-output-text" style="white-space: pre-wrap"></div>
<div id="example-image" class="example-image" style="display: none">
<img id="example-image-img" src="" alt="Example output image">
</div>
</div>
</div>
<!-- Locked section (shown instead of prompt if no access) -->
<div
id="locked-section"
style="
display: none;
text-align: center;
padding: 40px 20px;
background: #f8fafc;
border-radius: 12px;
margin-bottom: 28px;
"
>
<i
class="bi bi-lock-fill"
style="
font-size: 2.5rem;
color: #94a3b8;
display: block;
margin-bottom: 12px;
"
></i>
<h3 style="margin-bottom: 8px">
This prompt requires a subscription
</h3>
<p style="color: #64748b; margin-bottom: 20px">
Subscribe to <strong id="locked-creator"></strong> to access
this prompt.
</p>
<button
id="locked-subscribe-btn"
style="
padding: 12px 28px;
background: #6366f1;
color: #fff;
border: none;
border-radius: 10px;
font-weight: 600;
cursor: pointer;
font-size: 1rem;
"
>
Subscribe <span id="locked-tier-name"></span>
</button>
</div>
<!-- Rating -->
<div class="rating-section" id="rating-section">
<div class="rating-stars" id="rating-display"></div>
</div> </div>
</div> </div>
</div> </div>
</main>
</div> <!-- Unlock / Buy Section -->
<div class="unlock-section">
<button class="unlock-btn">Unlock Full Prompt • $19.99</button>
</div>
</div>
</main>
</div> </div>
</div>
<script type="module"> <script>
fetch("/sidebar.html") // Fetch sidebar and topbar
.then((r) => r.text()) fetch('../html/sidebar.html')
.then((data) => { .then(r => r.text())
document.getElementById("sidebar-container").innerHTML = data; .then(data => {
document document.getElementById('sidebar-container').innerHTML = data;
.querySelectorAll("#sidebar-container .sidebar a") // Remove active class from all sidebar links
.forEach((l) => l.classList.remove("active")); document.querySelectorAll('#sidebar-container .sidebar a').forEach(link => {
link.classList.remove('active');
}); });
fetch("/topbar.html") // Optionally set active on a relevant link (e.g., Marketplace)
.then((r) => r.text()) const marketplaceLink = document.querySelector('#sidebar-container a[href="marketplace.html"]');
.then( if (marketplaceLink) marketplaceLink.classList.add('active');
(data) => });
(document.getElementById("topbar-container").innerHTML = data),
);
const params = new URLSearchParams(location.search); fetch('../html/topbar.html')
const id = params.get("id"); .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data);
if (!id) { </script>
showError("No prompt ID provided", "Add ?id=... to the URL."); </body>
} else {
loadPrompt(id);
}
async function loadPrompt(id) {
try {
const res = await fetch(`/api/v1/prompts/${id}`);
if (res.status === 401) {
location.href = "/login";
return;
}
if (res.status === 404) {
showError(
"Prompt not found",
"This prompt does not exist or you do not have access.",
);
return;
}
if (!res.ok) throw new Error(`Server error ${res.status}`);
const p = await res.json();
renderPrompt(p);
} catch (e) {
showError("Could not load prompt", e.message);
}
}
function renderPrompt(p) {
document.title = `${p.title} — OnlyPrompt`;
document.getElementById("creator-avatar").textContent = p.creatorName
.charAt(0)
.toUpperCase();
document.getElementById("creator-name").textContent = p.creatorName;
document.getElementById("prompt-date").textContent = new Date(
p.timeStamp,
).toLocaleDateString("de-CH", {
year: "numeric",
month: "long",
day: "numeric",
});
document.getElementById("prompt-title").textContent = p.title;
document.getElementById("prompt-category").textContent =
p.categoryName || "Uncategorized";
document.getElementById("prompt-updated").textContent =
`Updated: ${new Date(p.timeStamp).toLocaleDateString()}`;
document.getElementById("prompt-description").textContent =
p.description;
document.getElementById("prompt-body").textContent = p.content;
document.getElementById("prompt-rating-stat").innerHTML =
`<i class="bi ${p.isLiked ? 'bi-heart-fill' : 'bi-heart'}" style="color:#ef4444;"></i> ${p.likeCount || 0} likes
<span style="margin-left:12px;"><i class="bi ${p.isSaved ? 'bi-bookmark-fill' : 'bi-bookmark'}" style="color:#f59e0b;"></i> ${p.saveCount || 0} saves</span>`;
renderExamples(p);
renderOwnerActions(p);
// Tier badge
const badge = document.getElementById("tier-badge");
if (p.price != null && Number(p.price) > 0) {
badge.innerHTML = `<span style="background:#fef3c7;color:#92400e;border-radius:20px;padding:4px 14px;font-size:0.8rem;font-weight:600;">$${Number(p.price).toFixed(2)}</span>`;
} else if (p.tierName) {
badge.innerHTML = `<span style="background:#f1f5f9;color:#475569;border-radius:20px;padding:4px 14px;font-size:0.8rem;font-weight:600;"><i class="bi bi-lock-fill"></i> ${p.tierName}</span>`;
} else {
badge.innerHTML = `<span style="background:#dcfce7;color:#166534;border-radius:20px;padding:4px 14px;font-size:0.8rem;font-weight:600;">Free</span>`;
}
// Rating
if (p.averageRating != null) {
const stars = Math.round(p.averageRating);
document.getElementById("rating-display").innerHTML =
`<span style="color:#f59e0b;font-size:1.1rem;">${"★".repeat(stars)}${"☆".repeat(5 - stars)}</span>
<span style="margin-left:8px;font-weight:600;">${p.averageRating.toFixed(1)}</span>
<span style="color:#94a3b8;font-size:0.85rem;margin-left:4px;">/ 5.0</span>`;
document.getElementById("prompt-rating-stat").innerHTML =
`<i class="bi ${p.isLiked ? 'bi-heart-fill' : 'bi-heart'}" style="color:#ef4444;"></i> ${p.likeCount || 0} likes
<span style="margin-left:12px;"><i class="bi ${p.isSaved ? 'bi-bookmark-fill' : 'bi-bookmark'}" style="color:#f59e0b;"></i> ${p.saveCount || 0} saves</span>
<span style="margin-left:12px;"><i class="bi bi-star-fill" style="color:#f59e0b;"></i> ${p.averageRating.toFixed(1)} rating</span>`;
} else {
document.getElementById("rating-display").innerHTML =
'<span style="color:#94a3b8;font-size:0.9rem;">No ratings yet</span>';
}
// Content visibility
if (p.content) {
document.getElementById("prompt-content-section").style.display =
"block";
document.getElementById("locked-section").style.display = "none";
} else {
document.getElementById("prompt-content-section").style.display =
"none";
document.getElementById("locked-section").style.display = "block";
document.getElementById("locked-creator").textContent = p.creatorName;
document.getElementById("locked-tier-name").textContent = p.tierName
? `— ${p.tierName}`
: "";
}
document.getElementById("detail-loading").style.display = "none";
document.getElementById("detail-body").style.display = "block";
}
async function renderOwnerActions(p) {
try {
const response = await fetch("/api/v1/auth/me", {
credentials: "same-origin",
});
if (!response.ok) return;
const user = await response.json();
if (user.id !== p.creatorId) return;
const editBtn = document.getElementById("edit-prompt-btn");
editBtn.style.display = "inline-block";
editBtn.onclick = () => {
location.href = `/create?id=${p.id}`;
};
} catch {
// Keep edit hidden if the current user cannot be loaded.
}
}
function renderExamples(p) {
const section = document.getElementById("example-section");
const text = document.getElementById("example-output-text");
const imageWrap = document.getElementById("example-image");
const image = document.getElementById("example-image-img");
if (!p.exampleOutput && !p.exampleImageUrl) {
section.style.display = "none";
return;
}
section.style.display = "block";
text.textContent = p.exampleOutput || "";
text.style.display = p.exampleOutput ? "block" : "none";
if (p.exampleImageUrl) {
image.src = p.exampleImageUrl;
imageWrap.style.display = "block";
} else {
image.removeAttribute("src");
imageWrap.style.display = "none";
}
}
function showError(title, msg) {
document.getElementById("detail-loading").style.display = "none";
document.getElementById("detail-error").style.display = "block";
document.getElementById("detail-error-title").textContent = title;
document.getElementById("detail-error-msg").textContent = msg;
}
</script>
</body>
</html> </html>
+43 -330
View File
@@ -13,7 +13,6 @@
<link rel="stylesheet" href="../css/login.css"> <link rel="stylesheet" href="../css/login.css">
<link rel="stylesheet" href="../css/topbar.css"> <link rel="stylesheet" href="../css/topbar.css">
<link rel="stylesheet" href="../css/profile.css"> <link rel="stylesheet" href="../css/profile.css">
<script src="../js/profile-shared.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
</head> </head>
<body> <body>
@@ -29,40 +28,61 @@
<section class="profile-header" style="display:flex;align-items:center;gap:32px;border-bottom:1px solid #e5e7eb;padding-bottom:24px;"> <section class="profile-header" style="display:flex;align-items:center;gap:32px;border-bottom:1px solid #e5e7eb;padding-bottom:24px;">
<img id="profileAvatar" src="../images/content/cat.png" class="profile-avatar" style="width:110px;height:110px;border-radius:50%;object-fit:cover;"> <img src="../images/content/cat.png" class="profile-avatar" style="width:110px;height:110px;border-radius:50%;object-fit:cover;">
<div class="profile-info" style="flex:1;"> <div class="profile-info" style="flex:1;">
<h1 id="profileDisplayName" style="font-size:2rem;font-weight:700;margin-bottom:4px;">Loading...</h1> <h1 style="font-size:2rem;font-weight:700;margin-bottom:4px;">Sunny the Cat</h1>
<div id="profileSlug" style="color:#64748b;margin-bottom:8px;"> <div style="color:#64748b;margin-bottom:8px;">
@profile <i class="bi bi-patch-check-fill" style="color:#3b82f6;"></i> @sunny_the_cat <i class="bi bi-patch-check-fill" style="color:#3b82f6;"></i>
</div> </div>
<div id="profileBio" style="margin-bottom:8px;"> <div style="margin-bottom:8px;">
Loading profile... 🐾 Cat prompt creator | Nap enthusiast | AI Cat Content Curator<br>
Chasing lasers and building purrfect prompts.
</div> </div>
<div id="profileSpecialities" style="color:#64748b;"></div> <div style="color:#64748b;">Cat City, Dreamland 🐈</div>
<div id="profileStats" style="display:flex;gap:18px;color:#64748b;margin-top:12px;font-size:0.95rem;">
<span><strong id="profileRating" style="color:#111827;">0.0</strong> rating</span>
<span><strong id="profileSubscribers" style="color:#111827;">0</strong> subscribers</span>
</div>
</div> </div>
<div id="profileActions" style="display:flex;flex-direction:column;gap:10px;"> <div style="display:flex;flex-direction:column;gap:10px;">
<button id="primaryProfileButton" class="login-button" onclick="location.href='settings.html'">Edit Profile</button> <button class="login-button">Edit Profile</button>
<button id="shareProfileButton" class="login-button" style="background:#f3f4f6;color:#111;box-shadow:none;">Share Profile</button> <button class="login-button" style="background:#f3f4f6;color:#111;box-shadow:none;">Share Profile</button>
</div> </div>
</section> </section>
<nav class="profile-tabs" style="display:flex;gap:24px;border-bottom:2px solid #e5e7eb;margin:32px 0 18px 0;flex-wrap:wrap;"> <nav style="display:flex;gap:24px;border-bottom:2px solid #e5e7eb;margin:32px 0 18px 0;">
<button type="button" class="profile-tab active" data-tab="mine" id="myPromptsTab">My Prompts</button> <a href="#" style="padding:10px 0;color:#3b82f6;font-weight:600;border-bottom:2px solid #3b82f6;">My Prompts (2)</a>
<button type="button" class="profile-tab" data-tab="favorites" id="favoritesTab">Favorites</button> <a href="#" style="padding:10px 0;color:#64748b;">Favorites (15)</a>
<button type="button" class="profile-tab" data-tab="saved" id="savedTab">Saved</button> <a href="#" style="padding:10px 0;color:#64748b;">Saved (7)</a>
</nav> </nav>
<section id="profile-prompts-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:24px;"> <section style="display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:24px;">
<div style="grid-column:1/-1;color:#64748b;text-align:center;padding:28px;">Loading prompts...</div>
<div style="background:#fff;border-radius:18px;box-shadow:0 2px 8px rgba(59,130,246,0.06);padding:18px;display:flex;gap:16px;">
<img src="../images/content/post1.png" style="width:60px;height:60px;border-radius:12px;">
<div>
<div style="font-weight:700;">Galactic Catventure</div>
<div style="color:#64748b;margin-bottom:6px;">A cosmic journey of a curious cat exploring the stars.</div>
<div style="display:flex;gap:16px;color:#64748b;">
<span><i class="bi bi-heart"></i> 128</span>
<span><i class="bi bi-chat"></i> 15</span>
</div>
</div>
</div>
<div style="background:#fff;border-radius:18px;box-shadow:0 2px 8px rgba(59,130,246,0.06);padding:18px;display:flex;gap:16px;">
<img src="../images/content/post2.png" style="width:60px;height:60px;border-radius:12px;">
<div>
<div style="font-weight:700;">Minimalist Cat Logo</div>
<div style="color:#64748b;margin-bottom:6px;">Sleek logo design for feline fans.</div>
<div style="display:flex;gap:16px;color:#64748b;">
<span><i class="bi bi-heart"></i> 54</span>
<span><i class="bi bi-chat"></i> 6</span>
</div>
</div>
</div>
</section> </section>
</main> </main>
@@ -70,7 +90,7 @@
</div> </div>
<script> <script>
fetch('/sidebar.html') fetch('../html/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
@@ -83,316 +103,9 @@
if (profileLink) profileLink.classList.add('active'); if (profileLink) profileLink.classList.add('active');
}); });
fetch('/topbar.html') fetch('../html/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
const profileAvatar = document.getElementById('profileAvatar');
const profileDisplayName = document.getElementById('profileDisplayName');
const profileSlug = document.getElementById('profileSlug');
const profileBio = document.getElementById('profileBio');
const profileSpecialities = document.getElementById('profileSpecialities');
const profileRating = document.getElementById('profileRating');
const profileSubscribers = document.getElementById('profileSubscribers');
const profilePromptsGrid = document.getElementById('profile-prompts-grid');
const myPromptsTab = document.getElementById('myPromptsTab');
const favoritesTab = document.getElementById('favoritesTab');
const savedTab = document.getElementById('savedTab');
const profileActions = document.getElementById('profileActions');
const primaryProfileButton = document.getElementById('primaryProfileButton');
const shareProfileButton = document.getElementById('shareProfileButton');
const profileTabs = document.querySelector('.profile-tabs');
const params = new URLSearchParams(location.search);
const profileId = params.get('id');
let ownPrompts = [];
let allPrompts = [];
let profilePrompts = [];
let activeProfileTab = 'mine';
let currentUserId = null;
let isOwnProfile = !profileId;
let profileLoaded = false;
let currentIsFollowing = false;
async function fetchJson(url) {
const response = await fetch(url, { credentials: 'same-origin' });
if (response.status === 401) {
location.href = '/login';
return null;
}
if (!response.ok) throw new Error(`${url} returned ${response.status}`);
return response.json();
}
function renderProfile(profile, fallbackName = 'Profile') {
profileDisplayName.textContent = profile.displayName || fallbackName;
profileSlug.innerHTML = `@${profile.user?.userName || profile.slug || 'profile'} <i class="bi bi-patch-check-fill" style="color:#3b82f6;"></i>`;
profileBio.textContent = profile.bio || 'No bio yet.';
profileSpecialities.textContent = profile.specialities || 'No specialities added yet.';
profileRating.textContent = Number(profile.averageRating || 0).toFixed(1);
profileSubscribers.textContent = profile.subscribers || 0;
if (profile.avatarUrl) {
profileAvatar.src = profile.avatarUrl;
}
profileLoaded = true;
}
function renderProfileFromPrompt(prompt) {
if (!prompt || profileLoaded) return;
profileDisplayName.textContent = prompt.creatorName || 'Creator Profile';
profileSlug.innerHTML = `@${prompt.creatorName || 'creator'} <i class="bi bi-patch-check-fill" style="color:#3b82f6;"></i>`;
profileBio.textContent = 'No bio yet.';
profileSpecialities.textContent = '';
profileRating.textContent = Number(prompt.averageRating || 0).toFixed(1);
profileSubscribers.textContent = 0;
if (prompt.creatorAvatarUrl) {
profileAvatar.src = prompt.creatorAvatarUrl;
}
}
async function loadCreatorCardFallback() {
if (isOwnProfile || profileLoaded || !profileId) return;
try {
const creators = await fetchJson('/api/v1/profiles?limit=100');
const creator = creators.find((item) => item.userId?.toLowerCase() === profileId.toLowerCase());
if (!creator) return;
renderProfile({
displayName: creator.displayName,
slug: creator.slug,
bio: creator.bio,
avatarUrl: creator.avatarUrl,
specialities: null,
averageRating: creator.averageRating,
subscribers: creator.subscribers
}, 'Creator Profile');
} catch {
// Prompt data below still provides a minimal fallback if creator cards fail.
}
}
async function loadProfile() {
try {
const currentProfile = await window.loadCurrentProfile();
currentUserId = currentProfile.user?.id;
isOwnProfile = !profileId || profileId.toLowerCase() === currentUserId?.toLowerCase();
if (isOwnProfile) {
renderProfile(currentProfile, 'My Profile');
return;
}
const profile = await fetchJson(`/api/v1/profiles/${encodeURIComponent(profileId)}`);
renderProfile(profile, 'Creator Profile');
} catch (error) {
if (isOwnProfile) {
profileDisplayName.textContent = 'Profile unavailable';
profileBio.textContent = error.message;
} else {
profileDisplayName.textContent = 'Loading creator...';
profileBio.textContent = '';
}
}
}
function isPromptMarked(type, id) {
if (type === 'liked') {
const prompt = allPrompts.find((item) => item.id === id);
return prompt?.isLiked === true;
}
if (type === 'saved') {
const prompt = allPrompts.find((item) => item.id === id);
return prompt?.isSaved === true;
}
return false;
}
function renderProfilePrompt(prompt, options = {}) {
const image = prompt.exampleImageUrl || '../images/content/post1.png';
const showEdit = options.showEdit === true;
const rating = prompt.averageRating == null ? 'No ratings' : prompt.averageRating.toFixed(1);
return `
<div onclick="location.href='/post-detail?id=${prompt.id}'" style="background:#fff;border-radius:18px;box-shadow:0 2px 8px rgba(59,130,246,0.06);padding:18px;display:flex;gap:16px;cursor:pointer;">
<img src="${image}" alt="${prompt.title}" style="width:72px;height:72px;border-radius:12px;object-fit:cover;">
<div style="flex:1;min-width:0;">
<div style="font-weight:700;">${prompt.title}</div>
<div style="color:#64748b;margin-bottom:8px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;">${prompt.description || 'No description yet.'}</div>
<div style="display:flex;gap:16px;color:#64748b;align-items:center;flex-wrap:wrap;">
<span><i class="bi bi-star"></i> ${rating}</span>
${prompt.creatorName ? `<span>@${prompt.creatorName}</span>` : ''}
${showEdit ? `<button onclick="event.stopPropagation(); location.href='/create?id=${prompt.id}'" style="border:none;background:#f1f5f9;color:#334155;border-radius:10px;padding:6px 10px;font-weight:700;cursor:pointer;">Edit</button>` : ''}
</div>
</div>
</div>`;
}
function renderPromptList(prompts, emptyText, options = {}) {
if (!prompts.length) {
profilePromptsGrid.innerHTML = `<div style="grid-column:1/-1;color:#64748b;text-align:center;padding:28px;">${emptyText}</div>`;
return;
}
profilePromptsGrid.innerHTML = prompts.map((prompt) => renderProfilePrompt(prompt, options)).join('');
}
function updateTabs() {
document.querySelectorAll('.profile-tab').forEach((tab) => {
tab.classList.toggle('active', tab.dataset.tab === activeProfileTab);
});
const liked = allPrompts.filter((prompt) => isPromptMarked('liked', prompt.id));
const saved = allPrompts.filter((prompt) => isPromptMarked('saved', prompt.id));
myPromptsTab.textContent = `My Prompts (${ownPrompts.length})`;
favoritesTab.textContent = `Favorites (${liked.length})`;
savedTab.textContent = `Saved (${saved.length})`;
if (activeProfileTab === 'favorites') {
renderPromptList(liked, 'No liked prompts yet.');
} else if (activeProfileTab === 'saved') {
renderPromptList(saved, 'No saved prompts yet.');
} else {
renderPromptList(ownPrompts, 'No prompts yet.', { showEdit: true });
}
}
function updateProfileMode() {
if (isOwnProfile) {
profileActions.style.display = 'flex';
primaryProfileButton.textContent = 'Edit Profile';
primaryProfileButton.disabled = false;
primaryProfileButton.onclick = () => location.href = 'settings.html';
profileTabs.style.display = 'flex';
return;
}
profileActions.style.display = 'flex';
primaryProfileButton.textContent = currentIsFollowing ? 'Following' : 'Follow';
primaryProfileButton.disabled = false;
primaryProfileButton.onclick = toggleProfileFollow;
favoritesTab.style.display = 'none';
savedTab.style.display = 'none';
myPromptsTab.textContent = `Prompts (${profilePrompts.length})`;
renderPromptList(profilePrompts, 'No prompts yet.');
}
async function loadFollowState() {
if (isOwnProfile || !profileId) return;
try {
const response = await fetch(`/api/v1/subscriptions/${encodeURIComponent(profileId)}`, {
credentials: 'same-origin'
});
if (response.status === 401) {
location.href = '/login';
return;
}
const subscription = response.ok ? await response.json() : null;
currentIsFollowing = subscription !== null;
updateProfileMode();
} catch {
currentIsFollowing = false;
}
}
async function toggleProfileFollow() {
if (!profileId) return;
primaryProfileButton.disabled = true;
const response = await fetch(`/api/v1/subscriptions/${encodeURIComponent(profileId)}`, {
method: currentIsFollowing ? 'DELETE' : 'PUT',
credentials: 'same-origin'
});
if (response.status === 401) {
location.href = '/login';
return;
}
if (response.ok) {
const currentSubscribers = Number(profileSubscribers.textContent || 0);
currentIsFollowing = !currentIsFollowing;
profileSubscribers.textContent = Math.max(0, currentSubscribers + (currentIsFollowing ? 1 : -1));
updateProfileMode();
} else {
primaryProfileButton.disabled = false;
}
}
shareProfileButton.addEventListener('click', async () => {
const url = isOwnProfile
? `${location.origin}/profile.html`
: `${location.origin}/profile.html?id=${encodeURIComponent(profileId)}`;
try {
await navigator.clipboard.writeText(url);
shareProfileButton.textContent = 'Copied';
setTimeout(() => shareProfileButton.textContent = 'Share Profile', 1200);
} catch {
location.href = url;
}
});
async function loadOwnPrompts() {
try {
const response = await fetch('/api/v1/prompts/mine');
if (response.status === 401) {
location.href = '/login';
return;
}
if (!response.ok) throw new Error('Prompts could not be loaded.');
ownPrompts = await response.json();
updateTabs();
} catch (error) {
profilePromptsGrid.innerHTML = `<div style="grid-column:1/-1;color:#ef4444;text-align:center;padding:28px;">${error.message}</div>`;
}
}
async function loadAllPromptReferences() {
try {
const response = await fetch('/api/v1/prompts?limit=100');
if (!response.ok) return;
allPrompts = await response.json();
if (isOwnProfile) {
updateTabs();
} else {
profilePrompts = allPrompts.filter((prompt) => prompt.creatorId?.toLowerCase() === profileId.toLowerCase());
renderProfileFromPrompt(profilePrompts[0]);
updateProfileMode();
}
} catch {
// Favorites and saved stay empty if prompts cannot be loaded.
}
}
document.querySelectorAll('.profile-tab').forEach((tab) => {
tab.addEventListener('click', () => {
if (!isOwnProfile) {
updateProfileMode();
return;
}
activeProfileTab = tab.dataset.tab;
updateTabs();
});
});
(async function initProfilePage() {
await loadProfile();
await loadCreatorCardFallback();
await loadFollowState();
updateProfileMode();
if (isOwnProfile) {
loadOwnPrompts();
}
loadAllPromptReferences();
})();
</script> </script>
</body> </body>
</html> </html>
+10 -74
View File
@@ -13,7 +13,6 @@
<link rel="stylesheet" href="../css/login.css"> <link rel="stylesheet" href="../css/login.css">
<link rel="stylesheet" href="../css/topbar.css"> <link rel="stylesheet" href="../css/topbar.css">
<link rel="stylesheet" href="../css/settings.css"> <link rel="stylesheet" href="../css/settings.css">
<script src="../js/profile-shared.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
</head> </head>
<body> <body>
@@ -41,7 +40,7 @@
<!-- Tab Content: Profile --> <!-- Tab Content: Profile -->
<div id="profileTab" class="tab-content active"> <div id="profileTab" class="tab-content active">
<form class="settings-form" id="profileSettingsForm"> <form class="settings-form">
<div class="form-group"> <div class="form-group">
<label for="avatar">Profile Picture</label> <label for="avatar">Profile Picture</label>
<div class="avatar-upload"> <div class="avatar-upload">
@@ -52,11 +51,11 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="displayName">Display Name</label> <label for="displayName">Display Name</label>
<input type="text" id="displayName" placeholder="Display name"> <input type="text" id="displayName" placeholder="Sunny the Cat">
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="username">Username</label> <label for="username">Username</label>
<input type="text" id="username" placeholder="username" required> <input type="text" id="username" placeholder="@username">
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="bio">Bio</label> <label for="bio">Bio</label>
@@ -64,11 +63,10 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="email">Email Address</label> <label for="email">Email Address</label>
<input type="email" id="email" placeholder="your@email.com" readonly> <input type="email" id="email" placeholder="your@email.com">
</div> </div>
<div class="form-actions"> <div class="form-actions">
<button type="submit" class="save-btn">Save Changes</button> <button type="submit" class="save-btn">Save Changes</button>
<p id="profileSaveStatus" style="margin-top:10px;color:#64748b;text-align:center;"></p>
</div> </div>
</form> </form>
</div> </div>
@@ -156,29 +154,7 @@
}); });
}); });
let currentAvatarUrl = ''; // Avatar preview (simple)
let currentSlug = '';
function setProfileForm(profile) {
document.getElementById('displayName').value = profile.displayName || '';
document.getElementById('username').value = profile.user?.userName || '';
document.getElementById('email').value = profile.user?.email || '';
document.getElementById('bio').value = profile.bio || '';
currentAvatarUrl = profile.avatarUrl || '../images/content/cat.png';
currentSlug = profile.slug || profile.user?.userName || '';
avatarPreview.src = currentAvatarUrl;
}
async function loadProfileSettings() {
try {
const profile = await window.loadCurrentProfile();
setProfileForm(profile);
} catch (error) {
document.getElementById('profileSaveStatus').textContent = 'Profile could not be loaded.';
}
}
// Avatar preview and save as data URL
const avatarUpload = document.getElementById('avatarUpload'); const avatarUpload = document.getElementById('avatarUpload');
const avatarPreview = document.getElementById('avatarPreview'); const avatarPreview = document.getElementById('avatarPreview');
if (avatarUpload) { if (avatarUpload) {
@@ -187,53 +163,15 @@
if (file && (file.type === 'image/png' || file.type === 'image/jpeg')) { if (file && (file.type === 'image/png' || file.type === 'image/jpeg')) {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = function(ev) { reader.onload = function(ev) {
currentAvatarUrl = ev.target.result; avatarPreview.src = ev.target.result;
avatarPreview.src = currentAvatarUrl;
}; };
reader.readAsDataURL(file); reader.readAsDataURL(file);
} }
}); });
} }
document.getElementById('profileSettingsForm').addEventListener('submit', async (e) => { // Demo form submits for all forms
e.preventDefault(); document.querySelectorAll('.settings-form').forEach(form => {
const status = document.getElementById('profileSaveStatus');
status.textContent = 'Saving...';
try {
const userName = document.getElementById('username').value.trim();
const response = await fetch('/api/v1/profiles', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({
displayName: document.getElementById('displayName').value.trim(),
userName,
slug: userName || currentSlug,
bio: document.getElementById('bio').value.trim(),
avatarUrl: currentAvatarUrl,
specialities: null,
isPublic: true
})
});
if (response.status === 401) {
location.href = '/login';
return;
}
if (!response.ok) throw new Error('Profile could not be saved.');
const savedProfile = await window.loadCurrentProfile(true);
window.setCurrentProfile(savedProfile);
setProfileForm(savedProfile);
status.textContent = 'Saved.';
} catch (error) {
status.textContent = error.message;
}
});
// Demo form submits for forms that are not connected yet
document.querySelectorAll('.settings-form:not(#profileSettingsForm)').forEach(form => {
form.addEventListener('submit', (e) => { form.addEventListener('submit', (e) => {
e.preventDefault(); e.preventDefault();
alert('Settings saved (demo)'); alert('Settings saved (demo)');
@@ -241,7 +179,7 @@
}); });
// Fetch sidebar and topbar // Fetch sidebar and topbar
fetch('/sidebar.html') fetch('../html/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
@@ -251,11 +189,9 @@
const settingsLink = document.querySelector('#sidebar-container a[href="settings.html"]'); const settingsLink = document.querySelector('#sidebar-container a[href="settings.html"]');
if (settingsLink) settingsLink.classList.add('active'); if (settingsLink) settingsLink.classList.add('active');
}); });
fetch('/topbar.html') fetch('../html/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
loadProfileSettings();
</script> </script>
</body> </body>
</html> </html>
+2 -4
View File
@@ -67,14 +67,12 @@
<!-- Logout bottom --> <!-- Logout bottom -->
<div class="sidebar-bottom"> <div class="sidebar-bottom">
<form action="/api/v1/auth/logout" method="post"> <a href="login.html" class="sidebar-logout">
<button type="submit" class="sidebar-logout">
<div class="logout-left"> <div class="logout-left">
<i class="bi bi-box-arrow-right"></i> <i class="bi bi-box-arrow-right"></i>
<span class="nav-text">Logout</span> <span class="nav-text">Logout</span>
</div> </div>
<i class="bi bi-chevron-right logout-arrow"></i> <i class="bi bi-chevron-right logout-arrow"></i>
</button> </a>
</form>
</div> </div>
</div> </div>
-5
View File
@@ -45,11 +45,6 @@
<input type="text" id="displayName" name="displayName" placeholder="Enter your display name" required> <input type="text" id="displayName" name="displayName" placeholder="Enter your display name" required>
</div> </div>
<div class="form-group">
<label for="userName">Username</label>
<input type="text" id="userName" name="userName" placeholder="Choose a username" required>
</div>
<div class="form-group"> <div class="form-group">
<label for="password">Password</label> <label for="password">Password</label>
<!-- Password field with button to show/hide password --> <!-- Password field with button to show/hide password -->
-28
View File
@@ -1,28 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OnlyPrompt - Test</title>
<link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/base.css">
<div id="styleOutlet">
</div>
</head>
<body>
<div>
<h1>Test Site</h1>
<a href="/counter/1">Go to count 1</a>
<a href="/counter/2">Go to count 2</a>
<a href="/counter/3">Go to count 3</a>
<div id="routerOutlet">
Hello There
</div>
</div>
<script type="module" src="./js/node-test.js"></script>
</body>
</html>
+2 -2
View File
@@ -8,7 +8,7 @@
<header class="topbar-shell"> <header class="topbar-shell">
<div class="topbar-search"> <div class="topbar-search">
<i class="bi bi-search"></i> <i class="bi bi-search"></i>
<input id="topbarSearchInput" type="search" placeholder="Search"> <input type="text" placeholder="Search">
</div> </div>
<div class="topbar-actions"> <div class="topbar-actions">
@@ -21,7 +21,7 @@
<!-- Profile avatar on the right (must be changed with backend) --> <!-- Profile avatar on the right (must be changed with backend) -->
<button class="topbar-avatar-btn" aria-label="Profile"> <button class="topbar-avatar-btn" aria-label="Profile">
<img id="topbarAvatar" src="../images/content/cat.png" alt="Profile Picture" class="topbar-avatar"> <img src="../images/content/cat.png" alt="Profile Picture" class="topbar-avatar">
</button> </button>
</div> </div>
</header> </header>
+25 -43
View File
@@ -1,21 +1,21 @@
# OnlyPrompt - AI Prompt Marketplace # OnlyPrompt - AI Prompt Marketplace
## Description ## Description
OnlyPrompt is a web application where users can create, publish, discover and interact with AI prompts. Users can edit their profiles, follow creators, like and save prompts, write reviews and browse free or paid prompt cards in a marketplace. OnlyPrompt is a frontend web applications where people can publish and sell their high-quality AI prompts. User can browse, filter, rate and unlock premium features such as private chats with creators for exclusive AI tips.
This project is built with HTML, CSS and JavaScript. This project is built with with HTML, CSS and Java Script.
## Special Features ## Special Features
- 📝 Create, edit and publish AI prompts - 📝 Create and publish new prompts
- 🔍 Browse prompts in a marketplace with category, search and price filters - 🔍 Live search and category filtering
- 📄 View prompt detail pages with examples, ratings and access states - 💬 Premium chat simulation with creators
- ❤️ Like and save prompts - 🔒 Unlock premium prompts (payment simulation)
- 👥 Follow and discover other creators - ⭐ Rating system
- 👤 Edit user profiles with display name, username, bio and profile picture - ❤️ Save favorites (LocalStorage)
- 🌐 View own and public creator profiles - 📱 Fully responsive design (mobile & desktop)
- 📱 Responsive layout for desktop and mobile - 🌐 External API integration (e.g., RandomUser API for creator profiles)
- 🔄 Server communication through a REST API - 💾 Client-side data persistence
- 💾 Shared data persistence with backend and database - 🔄 Basic server communication (optional file-based backend)
## Installment (for local use) ## Installment (for local use)
@@ -33,36 +33,18 @@ DB_PASSWORD=onlyprompt
``` ```
## Technologies, Libraries, Frameworks ## Technologies, Libraries, Frameworks
- HTML5 for page structure - HTML5 (Structure)
- CSS3 with Flexbox/Grid for layout and responsive design - CSS3 + Bootstrap + PureCSS (Styling & responsive layout)
- Bootstrap Icons for UI icons - Vanilla JavaScript (Application logic)
- Vanilla JavaScript for DOM manipulation, events and API calls - JavaScript Libraries Axios, JQuery
- Fetch API for asynchronous server communication - ASP.NET Core (Backend)
- ASP.NET Core as helper backend - Postgres (Backend Datastorage)
- PostgreSQL for shared data persistence - Docker (Deployment)
- Docker for local development and deployment
## Technical Decisions
The frontend is built with plain HTML, CSS and Vanilla JavaScript because the project focuses on understanding core frontend concepts without using a JavaScript framework. The backend is used as a helper service for authentication, shared data persistence and REST API communication. Docker is used so that the project can be started consistently on different machines.
## Use of AI Tools
AI tools were used as support during development, mainly for debugging, comparing implementation approaches and improving documentation wording. Generated suggestions were reviewed, adapted and tested by the team before being included in the project.
## Security Considerations
The project uses authentication with a JWT cookie so that protected pages and API endpoints require a logged-in user. User input is validated on the backend for important operations such as registration, profile updates and prompt creation.
Known limitations:
- Payment and premium access are simulated and are not connected to a real payment provider.
- User-generated content is displayed in the frontend, so XSS prevention is important. The project avoids intentionally executing user input as code, but further output sanitization would be needed for production.
- Authentication is implemented for local project use and would need additional hardening for production.
## Reflection
A main challenge was connecting static frontend pages with dynamic backend data while keeping the application usable and consistent. During development, the project evolved from demo pages into a connected application with real profiles, prompts, likes, saves and creator interactions. We learned how important clear API structures, consistent data models and regular browser testing are when multiple pages depend on the same shared data.
## Group members and their roles ## Group members and their roles
| Name | Role | - Thuvaraka Yogarajah
| --- | --- | - Isabelle Nachbaur
| **Thuvaraka Yogarajah** | Initial project structure, HTML layout and API backend scaffold | - Florian Klessascheck
| **Isabelle Nachbaur** | Frontend pages, UI design, prompt creation flow, marketplace/profile features | - Abdul Geylani Semiz
| **Florian Klessascheck** | Backend setup, authentication, database integration, Docker setup and utility/PWA experiments |
| **Abdul Geylani Semiz** | Dynamic API integration for dashboard feed, marketplace, post detail and community creator features |