Author SHA1 Message Date
renovate 386ff76bff Update alpine/git Docker tag to v2.54.0
renovate/stability-days Updates have met minimum release age requirement
Test and deploy / test (push) Successful in 9m44s
Test and deploy / deploy (push) Has been skipped
2026-11-16 04:05:14 +00:00
adamfandClaude Opus 5.5 89aaf8d79e Save cover letters, split them into draggable sections, add a paragraph bank
Test and deploy / deploy (push) Successful in 13m45s
Test and deploy / test (push) Successful in 2m17s
Weekly Maintenance / maintenance (push) Successful in 14m27s
Renovate / renovate (push) Successful in 5m54s
The /cv Cover Letter tab kept nothing across a refresh and was one flat list
of paragraphs. Letters are now saved as CoverLetter rows (body is the
frontend's JSON, checked only for being an object of sane size), split into
named sections whose paragraphs drag within and between them, with a bank of
reusable CoverSnippet paragraphs beside the page to drag in as copies.
Everything stored is @admin; visitors still get the blank template, and
section titles never print.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 16:03:48 +00:00
19 changed files with 2975 additions and 90 deletions
+3 -3
View File
@@ -76,7 +76,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
- `graph/*.resolvers.go` — resolver implementations (one per schema file, `follow-schema` layout) - `graph/*.resolvers.go` — resolver implementations (one per schema file, `follow-schema` layout)
- `graph/generated.go` — auto-generated by gqlgen, do not edit - `graph/generated.go` — auto-generated by gqlgen, do not edit
- `graph/model/models_gen.go` — auto-generated GraphQL models, do not edit - `graph/model/models_gen.go` — auto-generated GraphQL models, do not edit
- `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing, Bookmark, Place, Box, Page, Background, Layout, Component) - `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing, Bookmark, Place, Box, Page, Background, Layout, Component, CoverLetter, CoverSnippet)
- `graph/directives.go` — the `@admin` / `@signedIn` schema directives (see Key Patterns) - `graph/directives.go` — the `@admin` / `@signedIn` schema directives (see Key Patterns)
- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, the Python-service call helper (`python_call.go`), uploads (`uploads.go`: validation, naming, Garage bucket with disk fallback), DB seeding. There is no Claude client in Go any more - `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, the Python-service call helper (`python_call.go`), uploads (`uploads.go`: validation, naming, Garage bucket with disk fallback), DB seeding. There is no Claude client in Go any more
@@ -85,7 +85,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
- `src/graphql.js` — thin axios-based GraphQL client (`POST /api/graphql`) - `src/graphql.js` — thin axios-based GraphQL client (`POST /api/graphql`)
- `src/api.js` — thin REST client for the `/api` JSON endpoints; failures become an `ApiError` carrying the backend's `error` message and the status - `src/api.js` — thin REST client for the `/api` JSON endpoints; failures become an `ApiError` carrying the backend's `error` message and the status
- `src/uploads.js` — storing and showing uploaded files: `uploadFile(file)` → public `/uploads/...` URL, `ACCEPT` for file pickers, `kindOf`/`tagFor`/`isUploadUrl`/`mediaSize`. Every upload goes through it - `src/uploads.js` — storing and showing uploaded files: `uploadFile(file)` → public `/uploads/...` URL, `ACCEPT` for file pickers, `kindOf`/`tagFor`/`isUploadUrl`/`mediaSize`. Every upload goes through it
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places, boxes, pages, layouts, components. `createCrudStore.js` is the factory behind places, boxes and pages; `createMirrorStore.js` is the one behind the home-page slices - `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places, boxes, pages, layouts, components, coverLetters, coverSnippets. `createCrudStore.js` is the factory behind places, boxes and pages; `createMirrorStore.js` is the one behind the home-page slices
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines). Canvas pages are admin-arranged boxes (built-in widgets or sandboxed-iframe HTML) stored as the `Box` GraphQL type, drawn by `views/home3/BoxCanvas.vue` per page key: the landing page (`/`, key `index`) is one, and admin-created `Page`s (e.g. shrines, and `/stp`, the `Page` with slug `stp`) are served at `/<slug>` by the router's catch-all, `views/canvas/CanvasPage.vue`. A `Layout` is a saved, named copy of a page's boxes and background that can be loaded onto any canvas (the canvas's Layouts button, or the admin Pages tab). A `Component` is a saved, named HTML box: "+ New box" places copies of it, and the canvas's Components button also places it *linked* (`Box.componentId`), so the box shows the component's HTML and editing it edits every linked box; the built-in starters in `templates.js` become components through that panel's "Import built-ins". Boxes and pages can be admin-only, filtered server-side. Each canvas page key also has an optional `Background`, set from the canvas's Background button and painted by `DefaultLayout`. See "The /stp canvas" in `vue/README.md` - `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines). Canvas pages are admin-arranged boxes (built-in widgets or sandboxed-iframe HTML) stored as the `Box` GraphQL type, drawn by `views/home3/BoxCanvas.vue` per page key: the landing page (`/`, key `index`) is one, and admin-created `Page`s (e.g. shrines, and `/stp`, the `Page` with slug `stp`) are served at `/<slug>` by the router's catch-all, `views/canvas/CanvasPage.vue`. A `Layout` is a saved, named copy of a page's boxes and background that can be loaded onto any canvas (the canvas's Layouts button, or the admin Pages tab). A `Component` is a saved, named HTML box: "+ New box" places copies of it, and the canvas's Components button also places it *linked* (`Box.componentId`), so the box shows the component's HTML and editing it edits every linked box; the built-in starters in `templates.js` become components through that panel's "Import built-ins". Boxes and pages can be admin-only, filtered server-side. Each canvas page key also has an optional `Background`, set from the canvas's Background button and painted by `DefaultLayout`. See "The /stp canvas" in `vue/README.md`
- `src/components/` — reusable UI components - `src/components/` — reusable UI components
- `src/assets/styles.css` — design tokens (Tailwind `@theme`), base element styles, shared classes and transitions. `layouts/CVLayout.vue` re-points the colour tokens for the light CV theme. See "Styling" in `vue/README.md`. - `src/assets/styles.css` — design tokens (Tailwind `@theme`), base element styles, shared classes and transitions. `layouts/CVLayout.vue` re-points the colour tokens for the light CV theme. See "Styling" in `vue/README.md`.
@@ -117,4 +117,4 @@ Each area has its own README with the detail that doesn't belong here:
- **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, nginx templating). Preserve these when editing; if you change the behaviour they describe, update them. - **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, nginx templating). Preserve these when editing; if you change the behaviour they describe, update them.
- **Resolver commentary lives inside function bodies**, because gqlgen relocates or strips anything above the signature when regenerating. - **Resolver commentary lives inside function bodies**, because gqlgen relocates or strips anything above the signature when regenerating.
- **Schema files use `#` comments**, not triple-quoted description blocks — descriptions would change GraphQL introspection output. - **Schema files use `#` comments**, not triple-quoted description blocks — descriptions would change GraphQL introspection output.
- **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead — e.g. `views/unused/CoverLetters.vue` is actually live on `/cv`. - **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead; being in `views/unused/` is not proof.
+9 -9
View File
@@ -4,19 +4,19 @@ go 1.26
require ( require (
github.com/99designs/gqlgen v0.17.95 github.com/99designs/gqlgen v0.17.95
github.com/aws/aws-sdk-go-v2 v1.47.4 github.com/aws/aws-sdk-go-v2 v1.47.3
github.com/aws/aws-sdk-go-v2/credentials v1.20.10 github.com/aws/aws-sdk-go-v2/credentials v1.20.9
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.5 github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3
github.com/gin-gonic/gin v1.12.0 github.com/gin-gonic/gin v1.11.0
github.com/golang-jwt/jwt/v5 v5.3.1 github.com/golang-jwt/jwt/v5 v5.3.0
github.com/gorilla/websocket v1.5.3 github.com/gorilla/websocket v1.5.3
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd
github.com/vektah/gqlparser/v2 v2.5.37 github.com/vektah/gqlparser/v2 v2.5.37
github.com/zmb3/spotify/v2 v2.4.3 github.com/zmb3/spotify/v2 v2.4.3
golang.org/x/crypto v0.58.0 golang.org/x/crypto v0.55.0
golang.org/x/oauth2 v0.37.0 golang.org/x/oauth2 v0.30.0
gorm.io/driver/postgres v1.6.3 gorm.io/driver/postgres v1.6.0
gorm.io/gorm v1.31.2 gorm.io/gorm v1.31.1
) )
require ( require (
+12
View File
@@ -116,3 +116,15 @@ models:
resolver: false resolver: false
uses: uses:
resolver: true resolver: true
CoverLetter:
model:
- adam-french.co.uk/backend/models.CoverLetter
fields:
deletedAt:
resolver: false
CoverSnippet:
model:
- adam-french.co.uk/backend/models.CoverSnippet
fields:
deletedAt:
resolver: false
+153
View File
@@ -0,0 +1,153 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"errors"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// CreateCoverLetter is the resolver for the createCoverLetter field.
func (r *mutationResolver) CreateCoverLetter(ctx context.Context, input model.CreateCoverLetterInput) (*models.CoverLetter, error) {
name, err := cleanCoverLetterName(input.Name)
if err != nil {
return nil, err
}
if err := checkCoverLetterBody(input.Body); err != nil {
return nil, err
}
taken, err := coverLetterNameTaken(r.Store.DB, name, 0)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a cover letter with that name")
}
letter := models.CoverLetter{Name: name, Body: input.Body}
if err := r.Store.DB.Create(&letter).Error; err != nil {
return nil, err
}
return &letter, nil
}
// UpdateCoverLetter is the resolver for the updateCoverLetter field.
func (r *mutationResolver) UpdateCoverLetter(ctx context.Context, id int, input model.UpdateCoverLetterInput) (*models.CoverLetter, error) {
var letter models.CoverLetter
if err := r.Store.DB.First(&letter, id).Error; err != nil {
return nil, err
}
if input.Name != nil {
name, err := cleanCoverLetterName(*input.Name)
if err != nil {
return nil, err
}
taken, err := coverLetterNameTaken(r.Store.DB, name, letter.ID)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a cover letter with that name")
}
letter.Name = name
}
if input.Body != nil {
if err := checkCoverLetterBody(*input.Body); err != nil {
return nil, err
}
letter.Body = *input.Body
}
if err := r.Store.DB.Save(&letter).Error; err != nil {
return nil, err
}
return &letter, nil
}
// DeleteCoverLetter is the resolver for the deleteCoverLetter field.
func (r *mutationResolver) DeleteCoverLetter(ctx context.Context, id int) (*models.CoverLetter, error) {
var letter models.CoverLetter
if err := r.Store.DB.First(&letter, id).Error; err != nil {
return nil, err
}
if err := r.Store.DB.Delete(&letter).Error; err != nil {
return nil, err
}
return &letter, nil
}
// CreateCoverSnippet is the resolver for the createCoverSnippet field.
func (r *mutationResolver) CreateCoverSnippet(ctx context.Context, input model.CreateCoverSnippetInput) (*models.CoverSnippet, error) {
text, err := cleanSnippetText(input.Text)
if err != nil {
return nil, err
}
snippet := models.CoverSnippet{Text: text}
if input.Section != nil {
if snippet.Section, err = cleanSnippetSection(*input.Section); err != nil {
return nil, err
}
}
if err := r.Store.DB.Create(&snippet).Error; err != nil {
return nil, err
}
return &snippet, nil
}
// UpdateCoverSnippet is the resolver for the updateCoverSnippet field.
func (r *mutationResolver) UpdateCoverSnippet(ctx context.Context, id int, input model.UpdateCoverSnippetInput) (*models.CoverSnippet, error) {
// Letters it was dropped into keep their own copy of the old text.
var snippet models.CoverSnippet
if err := r.Store.DB.First(&snippet, id).Error; err != nil {
return nil, err
}
var err error
if input.Text != nil {
if snippet.Text, err = cleanSnippetText(*input.Text); err != nil {
return nil, err
}
}
if input.Section != nil {
if snippet.Section, err = cleanSnippetSection(*input.Section); err != nil {
return nil, err
}
}
if err := r.Store.DB.Save(&snippet).Error; err != nil {
return nil, err
}
return &snippet, nil
}
// DeleteCoverSnippet is the resolver for the deleteCoverSnippet field.
func (r *mutationResolver) DeleteCoverSnippet(ctx context.Context, id int) (*models.CoverSnippet, error) {
var snippet models.CoverSnippet
if err := r.Store.DB.First(&snippet, id).Error; err != nil {
return nil, err
}
if err := r.Store.DB.Delete(&snippet).Error; err != nil {
return nil, err
}
return &snippet, nil
}
// CoverLetters is the resolver for the coverLetters field.
func (r *queryResolver) CoverLetters(ctx context.Context) ([]*models.CoverLetter, error) {
var letters []models.CoverLetter
if err := r.Store.DB.Order("updated_at DESC").Find(&letters).Error; err != nil {
return nil, err
}
return ptrs(letters), nil
}
// CoverSnippets is the resolver for the coverSnippets field.
func (r *queryResolver) CoverSnippets(ctx context.Context) ([]*models.CoverSnippet, error) {
var snippets []models.CoverSnippet
if err := r.Store.DB.Order("section ASC, created_at DESC").Find(&snippets).Error; err != nil {
return nil, err
}
return ptrs(snippets), nil
}
+84
View File
@@ -0,0 +1,84 @@
package graph
// Hand-written helpers for cover_letter.resolvers.go, kept out of the
// resolver file for the same reason as box_helpers.go.
import (
"encoding/json"
"errors"
"fmt"
"strings"
"unicode/utf8"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
const (
maxCoverLetterNameLen = 100
// A letter is a page of text; 100 KB is far beyond any real one and
// still small enough that a runaway client can't fill the table.
maxCoverLetterBodyLen = 100 * 1024
maxSnippetTextLen = 5000
maxSnippetSectionLen = 100
)
// cleanCoverLetterName trims name and reports why it can't be a letter's
// name.
func cleanCoverLetterName(name string) (string, error) {
name = strings.TrimSpace(name)
if name == "" {
return name, errors.New("a cover letter needs a name")
}
if len(name) > maxCoverLetterNameLen {
return name, fmt.Errorf("a cover letter name is at most %d characters", maxCoverLetterNameLen)
}
return name, nil
}
// coverLetterNameTaken reports whether a live letter other than exceptID has
// this name. Checked up front, like layoutNameTaken, so the admin gets a
// sentence rather than a constraint violation.
func coverLetterNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64
err := db.Model(&models.CoverLetter{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
return count > 0, err
}
// checkCoverLetterBody reports why body can't be stored. The server never
// reads inside it, so it only has to be a JSON object of a sane size — an
// array or a bare string would be a frontend bug worth refusing early.
func checkCoverLetterBody(body string) error {
if len(body) > maxCoverLetterBodyLen {
return fmt.Errorf("a cover letter is at most %d KB", maxCoverLetterBodyLen/1024)
}
var obj map[string]json.RawMessage
// null unmarshals into a nil map without error, so it is caught here too.
if err := json.Unmarshal([]byte(body), &obj); err != nil || obj == nil {
return errors.New("a cover letter body must be a JSON object")
}
return nil
}
// cleanSnippetText trims text and reports why it can't be a bank paragraph.
// Counted in characters, not bytes, since the limit is about how much prose
// fits rather than storage.
func cleanSnippetText(text string) (string, error) {
text = strings.TrimSpace(text)
if text == "" {
return text, errors.New("a paragraph can't be empty")
}
if utf8.RuneCountInString(text) > maxSnippetTextLen {
return text, fmt.Errorf("a paragraph is at most %d characters", maxSnippetTextLen)
}
return text, nil
}
// cleanSnippetSection trims a snippet's section title.
func cleanSnippetSection(section string) (string, error) {
section = strings.TrimSpace(section)
if utf8.RuneCountInString(section) > maxSnippetSectionLen {
return section, fmt.Errorf("a section title is at most %d characters", maxSnippetSectionLen)
}
return section, nil
}
@@ -0,0 +1,76 @@
package graph
import (
"strings"
"testing"
)
func TestCleanCoverLetterName(t *testing.T) {
for _, c := range []struct {
name, in, want string
wantErr bool
}{
{"plain", "Acme", "Acme", false},
{"trimmed", " Acme \n", "Acme", false},
{"empty", "", "", true},
{"only spaces", " ", "", true},
{"at the limit", strings.Repeat("a", maxCoverLetterNameLen), strings.Repeat("a", maxCoverLetterNameLen), false},
{"too long", strings.Repeat("a", maxCoverLetterNameLen+1), "", true},
} {
t.Run(c.name, func(t *testing.T) {
got, err := cleanCoverLetterName(c.in)
if (err != nil) != c.wantErr {
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
}
if !c.wantErr && got != c.want {
t.Fatalf("got %q, want %q", got, c.want)
}
})
}
}
func TestCheckCoverLetterBody(t *testing.T) {
for _, c := range []struct {
name, in string
wantErr bool
}{
{"object", `{"v":1,"sections":[]}`, false},
{"empty object", `{}`, false},
{"array", `[]`, true},
{"string", `"hi"`, true},
{"null", `null`, true},
{"not json", `{`, true},
{"empty", ``, true},
{"too big", `{"x":"` + strings.Repeat("a", maxCoverLetterBodyLen) + `"}`, true},
} {
t.Run(c.name, func(t *testing.T) {
if err := checkCoverLetterBody(c.in); (err != nil) != c.wantErr {
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
}
})
}
}
func TestCleanSnippetText(t *testing.T) {
for _, c := range []struct {
name, in, want string
wantErr bool
}{
{"plain", "I like Go.", "I like Go.", false},
{"trimmed", "\n I like Go. ", "I like Go.", false},
{"empty", " ", "", true},
// Characters, not bytes: 5000 two-byte runes still fit.
{"multibyte at the limit", strings.Repeat("é", maxSnippetTextLen), strings.Repeat("é", maxSnippetTextLen), false},
{"too long", strings.Repeat("a", maxSnippetTextLen+1), "", true},
} {
t.Run(c.name, func(t *testing.T) {
got, err := cleanSnippetText(c.in)
if (err != nil) != c.wantErr {
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
}
if !c.wantErr && got != c.want {
t.Fatalf("got %q, want %q", got, c.want)
}
})
}
}
+2
View File
@@ -192,6 +192,8 @@ func TestGuardedQueriesArePinned(t *testing.T) {
"places": "signedIn", "places": "signedIn",
"layouts": "admin", "layouts": "admin",
"components": "admin", "components": "admin",
"coverLetters": "admin",
"coverSnippets": "admin",
"permissionTypes": "signedIn", "permissionTypes": "signedIn",
} }
got := map[string]string{} got := map[string]string{}
File diff suppressed because it is too large Load Diff
+20
View File
@@ -59,6 +59,16 @@ type CreateComponentInput struct {
AdminOnly *bool `json:"adminOnly,omitempty"` AdminOnly *bool `json:"adminOnly,omitempty"`
} }
type CreateCoverLetterInput struct {
Name string `json:"name"`
Body string `json:"body"`
}
type CreateCoverSnippetInput struct {
Text string `json:"text"`
Section *string `json:"section,omitempty"`
}
type CreateFavoriteInput struct { type CreateFavoriteInput struct {
Type string `json:"type"` Type string `json:"type"`
Name string `json:"name"` Name string `json:"name"`
@@ -185,6 +195,16 @@ type UpdateComponentInput struct {
AdminOnly *bool `json:"adminOnly,omitempty"` AdminOnly *bool `json:"adminOnly,omitempty"`
} }
type UpdateCoverLetterInput struct {
Name *string `json:"name,omitempty"`
Body *string `json:"body,omitempty"`
}
type UpdateCoverSnippetInput struct {
Text *string `json:"text,omitempty"`
Section *string `json:"section,omitempty"`
}
type UpdateLayoutInput struct { type UpdateLayoutInput struct {
Name *string `json:"name,omitempty"` Name *string `json:"name,omitempty"`
} }
+60
View File
@@ -0,0 +1,60 @@
# Cover letters: saved letters from the /cv Cover Letter tab, and the bank of
# reusable paragraphs dragged into them. A letter's body is JSON the frontend
# owns (views/CV/coverLetter.js); the server only checks it is a JSON object
# of a sane size. See models.CoverLetter and graph/cover_letter_helpers.go.
#
# Admin only throughout, reads included: /cv is public, but the letters are
# drafts addressed to particular employers.
type CoverLetter {
id: ID!
createdAt: Time!
updatedAt: Time!
name: String!
# The whole letter, as a JSON object.
body: String!
}
type CoverSnippet {
id: ID!
createdAt: Time!
text: String!
# The section title it was written for; "" for none. Only groups the bank.
section: String!
}
input CreateCoverLetterInput {
name: String!
body: String!
}
input UpdateCoverLetterInput {
name: String
body: String
}
input CreateCoverSnippetInput {
text: String!
section: String
}
input UpdateCoverSnippetInput {
text: String
section: String
}
extend type Query {
# Most recently updated first.
coverLetters: [CoverLetter!]! @admin
# By section, then newest first.
coverSnippets: [CoverSnippet!]! @admin
}
extend type Mutation {
createCoverLetter(input: CreateCoverLetterInput!): CoverLetter! @admin
updateCoverLetter(id: ID!, input: UpdateCoverLetterInput!): CoverLetter! @admin
deleteCoverLetter(id: ID!): CoverLetter! @admin
createCoverSnippet(input: CreateCoverSnippetInput!): CoverSnippet! @admin
updateCoverSnippet(id: ID!, input: UpdateCoverSnippetInput!): CoverSnippet! @admin
deleteCoverSnippet(id: ID!): CoverSnippet! @admin
}
+26
View File
@@ -288,3 +288,29 @@ type Component struct {
Shadow string `gorm:"not null;default:''" json:"shadow"` Shadow string `gorm:"not null;default:''" json:"shadow"`
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"` AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
} }
// CoverLetter is a saved letter from the /cv Cover Letter tab. Body is the
// whole letter as JSON (contact block, sections, paragraphs; the shape is
// views/CV/coverLetter.js's) because only the frontend ever reads inside it —
// the same reasoning as Layout.Boxes. The unique index is partial for the
// same reason as Page's.
type CoverLetter struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Name string `gorm:"not null;index:idx_cover_letters_name,unique,where:deleted_at IS NULL" json:"name"`
Body string `gorm:"type:text;not null" json:"body"`
}
// CoverSnippet is a reusable paragraph in the cover-letter bank, dragged into
// a letter as a copy. Section is the title of the section it was written for,
// only used to group the bank; a snippet can be dropped into any section.
type CoverSnippet struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Text string `gorm:"type:text;not null" json:"text"`
Section string `gorm:"not null;default:''" json:"section"`
}
+2
View File
@@ -56,6 +56,8 @@ func migrateDatabase(db *gorm.DB) error {
&models.Background{}, &models.Background{},
&models.Layout{}, &models.Layout{},
&models.Component{}, &models.Component{},
&models.CoverLetter{},
&models.CoverSnippet{},
) )
if err != nil { if err != nil {
return err return err
+1 -1
View File
@@ -462,7 +462,7 @@ services:
# inside the container. Since SilverBullet itself runs with no SB_USER, that # inside the container. Since SilverBullet itself runs with no SB_USER, that
# gate is the only thing protecting it, so the blast radius stays here. # gate is the only thing protecting it, so the blast radius stays here.
silverbullet-git: silverbullet-git:
image: alpine/git:v2.49.1 image: alpine/git:v2.54.0
container_name: "${SILVERBULLET_GIT_HOST:-silverbullet-git}" container_name: "${SILVERBULLET_GIT_HOST:-silverbullet-git}"
restart: always restart: always
networks: networks:
+1 -1
View File
@@ -381,7 +381,7 @@ in its header comment; the summary:
| `views/home/BadApple.vue` | unfinished ASCII video player; not imported | | `views/home/BadApple.vue` | unfinished ASCII video player; not imported |
| `views/CV/CVProgramming.vue` | live — the only CV template listed in `CV.vue` | | `views/CV/CVProgramming.vue` | live — the only CV template listed in `CV.vue` |
| `views/CV/CV{General,Backend,Frontend,Security,Electrical,Hospitality,Analyst,Temp}.vue` | commented out of `CV.vue`'s list; unreachable | | `views/CV/CV{General,Backend,Frontend,Security,Electrical,Hospitality,Analyst,Temp}.vue` | commented out of `CV.vue`'s list; unreachable |
| `views/unused/CoverLetters.vue` | **live** despite the directory — it is the "Cover Letter" tab on `/cv` | | `views/CV/CoverLetters.vue` (+ `CoverSnippetBank.vue`, `coverLetter.js`) | live — the "Cover Letter" tab on `/cv`. Sections of draggable paragraphs; an admin also gets saved letters (`CoverLetter`) and a paragraph bank (`CoverSnippet`), both `@admin` |
| `views/unused/Notes.vue` | no route points at it; not imported | | `views/unused/Notes.vue` | no route points at it; not imported |
| `components/util/{MusicPlayer,ObjectTable}.vue` | not imported | | `components/util/{MusicPlayer,ObjectTable}.vue` | not imported |
| `components/elle/Elle.vue`, `components/borders/UtenaFrame.vue` | decorative; not imported | | `components/elle/Elle.vue`, `components/borders/UtenaFrame.vue` | decorative; not imported |
+28
View File
@@ -0,0 +1,28 @@
/**
* Saved cover letters (the `CoverLetter` GraphQL type) for the /cv Cover
* Letter tab — full CRUD, built on createCrudStore().
*
* `body` is the whole letter as a JSON string; views/CV/coverLetter.js owns
* its shape (parseBody / serialize), the server only checks it is an object.
*
* Admin only, so nothing fetches it until views/CV/CoverLetters.vue sees an
* admin signed in.
*/
import { createCrudStore } from "@/stores/createCrudStore";
const COVER_LETTER_FIELDS = `
id
name
body
updatedAt
`;
export const useCoverLettersStore = createCrudStore("coverLetters", {
type: "CoverLetter",
list: "coverLetters",
fields: COVER_LETTER_FIELDS,
// The list query is most recently updated first, so a new letter goes on top.
insert: "prepend",
deleteReturns: "object",
});
+29
View File
@@ -0,0 +1,29 @@
/**
* The cover-letter paragraph bank (the `CoverSnippet` GraphQL type): reusable
* paragraphs dragged into a letter as copies — full CRUD, built on
* createCrudStore().
*
* `section` is the title of the section a snippet was written for and only
* groups the bank (views/CV/CoverSnippetBank.vue); editing a snippet never
* changes letters it was already dropped into.
*
* Admin only, like stores/coverLetters.js.
*/
import { createCrudStore } from "@/stores/createCrudStore";
const COVER_SNIPPET_FIELDS = `
id
text
section
createdAt
`;
export const useCoverSnippetsStore = createCrudStore("coverSnippets", {
type: "CoverSnippet",
list: "coverSnippets",
fields: COVER_SNIPPET_FIELDS,
// The bank groups by section itself, so where a new one lands doesn't matter.
insert: "prepend",
deleteReturns: "object",
});
+641 -61
View File
@@ -1,92 +1,547 @@
<script setup> <script setup>
/** /**
* Editable cover-letter template (contenteditable paragraphs, print to PDF). * Editable cover letter (contenteditable fields, print to PDF), split into
* named sections whose paragraphs can be dragged within and between them.
* STATUS: live — CV.vue imports it as the "Cover Letter" tab on /cv. * STATUS: live — CV.vue imports it as the "Cover Letter" tab on /cv.
*
* Everyone gets the editor; /cv is public and nothing here needs the server
* until something is saved. An admin also gets the toolbar (saved letters,
* stores/coverLetters.js) and the paragraph bank (CoverSnippetBank.vue,
* stores/coverSnippets.js). The letter's data shape and the moves live in
* ./coverLetter.js.
*
* Section titles are editor furniture: they are `no-print`, so the printed
* letter is one run of paragraphs, as it was before sections existed.
*
* Editing: contenteditable elements are filled with v-text and read back on
* blur. v-text, not {{ }}, because it replaces the element's whole content —
* an interpolated text node would sit alongside the <div>s a browser adds on
* Enter and duplicate the text when Vue patched it.
*
* Dragging is native HTML5 DnD. `drag` holds what is in flight (dataTransfer
* can't be read until the drop) and `dropAt` where it would land, which is
* what draws the indicator line. Only the ⋮⋮ handle is draggable, so text in
* a paragraph stays selectable.
*/ */
import { ref } from "vue"; import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useAuthStore } from "@/stores/auth";
import { useCoverLettersStore } from "@/stores/coverLetters";
import { useCoverSnippetsStore } from "@/stores/coverSnippets";
import CoverSnippetBank from "./CoverSnippetBank.vue";
import {
insertParagraph,
moveParagraph,
newLetter,
newParagraph,
newSection,
parseBody,
serialize,
} from "./coverLetter";
const name = ref("Adam French"); const auth = useAuthStore();
const phone = ref("+447563266931"); const letters = useCoverLettersStore();
const email = ref("[email protected]"); const snippets = useCoverSnippetsStore();
const role = ref("Job title / role"); const isAdmin = computed(() => auth.loggedIn && !!auth.user.admin);
const paragraphs = ref([
"Why I'm interested in the company...",
"Why I'm a strong fit for the role...",
"Relevant experience and background...",
]);
const signoff = ref("Thank you for reading - Adam F");
function addParagraph() { const letter = ref(newLetter());
paragraphs.value.push("New paragraph..."); // The open saved letter's id, or null for one never saved (or deleted).
const currentId = ref(null);
// The body as last saved or loaded; the letter is unsaved when it differs.
// Starts as the blank template so an untouched page doesn't nag.
const savedBody = ref(serialize(letter.value));
const dirty = computed(() => serialize(letter.value) !== savedBody.value);
const current = computed(() =>
letters.coverLetters.find((l) => l.id === currentId.value),
);
const busy = ref(false);
const error = ref("");
onMounted(() => auth.ensureLoaded());
// The stores are admin only, so they are fetched once an admin is known,
// which can be after mount on a cold load.
watch(
isAdmin,
(admin) => {
if (!admin) return;
if (!letters.loaded) letters.fetch();
if (!snippets.loaded) snippets.fetch();
},
{ immediate: true },
);
// Closing the tab with unsaved changes asks first. Only for an admin, who
// can save; a visitor's letter is throwaway by design.
function onBeforeUnload(event) {
if (isAdmin.value && dirty.value) event.preventDefault();
}
onMounted(() => window.addEventListener("beforeunload", onBeforeUnload));
onBeforeUnmount(() =>
window.removeEventListener("beforeunload", onBeforeUnload),
);
// ── Saving ──────────────────────────────────────────────────────────────
async function run(fn) {
error.value = "";
busy.value = true;
try {
await fn();
} catch (err) {
error.value = err.message;
} finally {
busy.value = false;
}
} }
function removeParagraph(index) { function discardOk() {
paragraphs.value.splice(index, 1); return !dirty.value || confirm("Discard the unsaved changes?");
} }
function updateParagraph(index, event) { function open(letterRow) {
paragraphs.value[index] = event.target.innerText; letter.value = parseBody(letterRow.body);
currentId.value = letterRow.id;
// The normalised form, not the raw body, so an older row doesn't open
// already marked unsaved.
savedBody.value = serialize(letter.value);
} }
function onPick(event) {
const id = event.target.value;
const row = letters.coverLetters.find((l) => l.id === id);
if (row && discardOk()) open(row);
// Put the select back if the switch was refused or "New" was picked.
event.target.value = currentId.value ?? "";
}
function startNew() {
if (!discardOk()) return;
letter.value = newLetter();
currentId.value = null;
savedBody.value = serialize(letter.value);
}
function save() {
if (!currentId.value) return saveAs();
const body = serialize(letter.value);
run(async () => {
await letters.update(currentId.value, { body });
savedBody.value = body;
});
}
function saveAs() {
const suggestion = current.value
? `${current.value.name} (copy)`
: letter.value.role.trim();
const name = prompt("Name this cover letter", suggestion);
if (name === null) return;
const body = serialize(letter.value);
run(async () => {
const created = await letters.create({ name, body });
currentId.value = created.id;
savedBody.value = body;
});
}
function rename() {
if (!current.value) return;
const name = prompt("Rename cover letter", current.value.name);
if (name === null || name === current.value.name) return;
run(() => letters.update(currentId.value, { name }));
}
function removeLetter() {
if (!current.value) return;
if (!confirm(`Delete "${current.value.name}"? This can't be undone.`))
return;
run(async () => {
await letters.remove(currentId.value);
// The text stays on the page, now unsaved, in case it was a misclick.
currentId.value = null;
savedBody.value = "";
});
}
// ── Editing ─────────────────────────────────────────────────────────────
function addParagraph(section) {
section.paragraphs.push(newParagraph());
}
function removeParagraph(section, index) {
section.paragraphs.splice(index, 1);
}
function addSection() {
letter.value.sections.push(newSection("New section", ["New paragraph..."]));
}
function removeSection(index) {
const section = letter.value.sections[index];
if (
section.paragraphs.some((p) => p.text.trim()) &&
!confirm(`Remove "${section.title || "this section"}" and its text?`)
)
return;
letter.value.sections.splice(index, 1);
}
const sectionTitles = computed(() =>
[...new Set(letter.value.sections.map((s) => s.title.trim()))].filter(
Boolean,
),
);
function saveToBank(section, para) {
run(() =>
snippets.create({ text: para.text, section: section.title.trim() }),
);
}
// ── Dragging ────────────────────────────────────────────────────────────
// { kind: "para", from: { section, index } } | { kind: "snippet", text } | null
const drag = ref(null);
// { section, index } — where a drop would land, or null.
const dropAt = ref(null);
function onParaDragStart(si, pi, event) {
drag.value = { kind: "para", from: { section: si, index: pi } };
event.dataTransfer.effectAllowed = "copyMove";
// Firefox won't start a drag without some data set.
event.dataTransfer.setData(
"text/plain",
letter.value.sections[si].paragraphs[pi].text,
);
event.dataTransfer.setDragImage(
event.target.closest(".paragraph-wrapper"),
16,
16,
);
}
function onSnippetDrag(snippet) {
drag.value = { kind: "snippet", text: snippet.text };
}
function endDrag() {
drag.value = null;
dropAt.value = null;
}
function accept(event) {
if (!drag.value) return false;
event.preventDefault();
event.dataTransfer.dropEffect = drag.value.kind === "para" ? "move" : "copy";
return true;
}
/** Over a paragraph: before it if the pointer is in its top half, else after. */
function onParaDragOver(si, pi, event) {
if (!accept(event)) return;
const rect = event.currentTarget.getBoundingClientRect();
const after = event.clientY > rect.top + rect.height / 2;
dropAt.value = { section: si, index: after ? pi + 1 : pi };
}
/** Over a section's end zone, or its title row: the end of that section. */
function onSectionEndDragOver(si, event) {
if (!accept(event)) return;
dropAt.value = {
section: si,
index: letter.value.sections[si].paragraphs.length,
};
}
function onDrop(event) {
if (!drag.value || !dropAt.value) return endDrag();
event.preventDefault();
if (drag.value.kind === "para")
moveParagraph(letter.value, drag.value.from, dropAt.value);
else insertParagraph(letter.value, dropAt.value, drag.value.text);
endDrag();
}
/** A letter paragraph dropped on the bank: save a copy there. */
function onBankDrop() {
const from = drag.value?.from;
endDrag();
if (!from) return;
const section = letter.value.sections[from.section];
saveToBank(section, section.paragraphs[from.index]);
}
const indicatorAt = (si, index) =>
dropAt.value?.section === si && dropAt.value?.index === index;
</script> </script>
<template> <template>
<main> <main :class="['cl-wrap', { 'with-bank': isAdmin }]">
<div class="a5page"> <div class="cl-letter">
<div v-if="isAdmin" class="no-print toolbar">
<select
class="letter-pick"
:value="currentId ?? ''"
:disabled="busy"
@change="onPick"
>
<option value="" disabled>
{{
letters.coverLetters.length
? "Open a saved letter…"
: "No saved letters"
}}
</option>
<option
v-for="l in letters.coverLetters"
:key="l.id"
:value="l.id"
>
{{ l.name }}
</option>
</select>
<button
class="cv-btn cv-btn-sm"
:disabled="busy"
@click="startNew"
>
New
</button>
<button
class="cv-btn cv-btn-sm cv-btn-primary"
:disabled="busy || (currentId && !dirty)"
@click="save"
>
Save
</button>
<button
class="cv-btn cv-btn-sm"
:disabled="busy"
@click="saveAs"
>
Save as…
</button>
<button
class="cv-btn cv-btn-sm"
:disabled="busy || !current"
@click="rename"
>
Rename
</button>
<button
class="cv-btn cv-btn-sm cv-btn-danger"
:disabled="busy || !current"
@click="removeLetter"
>
Delete
</button>
<span v-if="dirty" class="unsaved">● unsaved</span>
<span v-else-if="current" class="saved">saved</span>
<p v-if="error" class="toolbar-error">{{ error }}</p>
<p v-else-if="letters.error" class="toolbar-error">
Couldn't load saved letters: {{ letters.error.message }}
</p>
</div>
<div class="a5page" @dragend="endDrag">
<div class="contact"> <div class="contact">
<h1 <h1
contenteditable="true" contenteditable="true"
@blur="name = $event.target.innerText" v-text="letter.name"
> @blur="letter.name = $event.target.innerText"
{{ name }} ></h1>
</h1>
<div class="contact-details"> <div class="contact-details">
<p <p
contenteditable="true" contenteditable="true"
@blur="phone = $event.target.innerText" v-text="letter.phone"
> @blur="letter.phone = $event.target.innerText"
{{ phone }} ></p>
</p>
<p <p
contenteditable="true" contenteditable="true"
@blur="email = $event.target.innerText" v-text="letter.email"
@blur="letter.email = $event.target.innerText"
></p>
</div>
</div>
<h2
contenteditable="true"
v-text="letter.role"
@blur="letter.role = $event.target.innerText"
></h2>
<section
v-for="(section, si) in letter.sections"
:key="section.id"
class="letter-section"
> >
{{ email }}
</p>
</div>
</div>
<h2 contenteditable="true" @blur="role = $event.target.innerText">
{{ role }}
</h2>
<div <div
v-for="(p, i) in paragraphs" class="no-print section-head"
:key="i" @dragover="onSectionEndDragOver(si, $event)"
class="paragraph-wrapper" @drop="onDrop"
> >
<p contenteditable="true" @blur="updateParagraph(i, $event)"> <input
{{ p }} v-model="section.title"
</p> class="section-title"
placeholder="Section title"
aria-label="Section title"
/>
<button <button
class="no-print remove-btn" class="section-btn"
title="Add a paragraph to this section"
@click="addParagraph(section)"
>
+ paragraph
</button>
<button
class="section-btn danger"
title="Remove this section"
@click="removeSection(si)"
>
remove
</button>
</div>
<div
v-for="(p, pi) in section.paragraphs"
:key="p.id"
:class="[
'paragraph-wrapper',
{
'drop-before': indicatorAt(si, pi),
dragging:
drag?.kind === 'para' &&
drag.from.section === si &&
drag.from.index === pi,
},
]"
@dragover="onParaDragOver(si, pi, $event)"
@drop="onDrop"
>
<span
class="no-print drag-handle"
draggable="true"
title="Drag to move"
@dragstart="onParaDragStart(si, pi, $event)"
>⋮⋮</span
>
<p
contenteditable="true"
v-text="p.text"
@blur="p.text = $event.target.innerText"
></p>
<div class="no-print para-actions">
<button
v-if="isAdmin"
class="bank-btn"
title="Save to the paragraph bank"
@click="saveToBank(section, p)"
>
☆
</button>
<button
class="remove-btn"
title="Remove paragraph" title="Remove paragraph"
@click="removeParagraph(i)" @click="removeParagraph(section, pi)"
> >
× ×
</button> </button>
</div> </div>
</div>
<div
:class="[
'no-print',
'section-end',
{
'drop-before': indicatorAt(
si,
section.paragraphs.length,
),
empty: !section.paragraphs.length,
},
]"
@dragover="onSectionEndDragOver(si, $event)"
@drop="onDrop"
>
<span v-if="!section.paragraphs.length">
Empty — drop a paragraph here
</span>
</div>
</section>
<p <p
contenteditable="true" contenteditable="true"
@blur="signoff = $event.target.innerText" v-text="letter.signoff"
> @blur="letter.signoff = $event.target.innerText"
{{ signoff }} ></p>
</p> <button class="no-print add-btn" @click="addSection()">
<button class="no-print add-btn" @click="addParagraph()"> + Add section
+ Add paragraph
</button> </button>
</div> </div>
</div>
<CoverSnippetBank
v-if="isAdmin"
:accepting="drag?.kind === 'para'"
:section-titles="sectionTitles"
@drag-snippet="onSnippetDrag"
@drag-end="endDrag"
@drop-paragraph="onBankDrop"
/>
</main> </main>
</template> </template>
<style scoped> <style scoped>
.cl-wrap.with-bank {
display: grid;
grid-template-columns: minmax(0, 210mm) 18rem;
justify-content: center;
gap: 1.5rem;
padding: 0 1rem;
}
/* Narrow screens: the bank goes under the letter. */
@media (max-width: 1100px) {
.cl-wrap.with-bank {
grid-template-columns: minmax(0, 210mm);
}
}
.toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.4rem;
max-width: 210mm;
margin: 1rem auto 0;
}
.letter-pick {
min-width: 12rem;
padding: 0.2rem 0.4rem;
border: 1px solid var(--color-ink-soft);
border-radius: 4px;
font-size: 0.85rem;
}
.unsaved {
color: var(--color-ink-danger);
font-size: 0.8rem;
}
.saved {
color: var(--color-ink-muted);
font-size: 0.8rem;
}
.toolbar-error {
flex-basis: 100%;
color: var(--color-ink-danger);
font-size: 0.85rem;
}
.a5page { .a5page {
max-width: 210mm; max-width: 210mm;
min-height: 148mm; min-height: 148mm;
@@ -130,32 +585,153 @@ function updateParagraph(index, event) {
margin: 0; margin: 0;
} }
/* innerText turns a line break typed into a paragraph into "\n"; this keeps
it showing as one once v-text writes it back. */
[contenteditable="true"] {
white-space: pre-wrap;
}
[contenteditable="true"]:hover, [contenteditable="true"]:hover,
[contenteditable="true"]:focus { [contenteditable="true"]:focus {
outline: 1px dashed #999; outline: 1px dashed #999;
outline-offset: 2px; outline-offset: 2px;
} }
.section-head {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0.25rem 0 0.35rem;
font-size: 0.75rem;
}
.section-title {
flex: 1;
padding: 0;
border: none;
border-bottom: 1px dashed transparent;
background: transparent;
color: #888;
font: inherit;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.section-title:hover,
.section-title:focus {
border-bottom-color: #bbb;
outline: none;
color: #555;
}
.section-btn {
border: none;
background: none;
color: #888;
cursor: pointer;
font-size: 0.75rem;
opacity: 0;
transition: opacity 0.15s;
}
.section-btn:hover {
color: #333;
}
.section-btn.danger:hover {
color: #c00;
}
.letter-section:hover .section-btn,
.section-btn:focus-visible {
opacity: 1;
}
.paragraph-wrapper { .paragraph-wrapper {
position: relative; position: relative;
} }
.paragraph-wrapper .remove-btn { .paragraph-wrapper.dragging {
position: absolute; opacity: 0.4;
top: 0;
right: -1.5rem;
border: none;
background: none;
color: #c00;
cursor: pointer;
font-size: 1rem;
opacity: 0;
} }
.paragraph-wrapper:hover .remove-btn { /* The drop indicator: a line just above the paragraph (or end zone) the
dragged one would land before. */
.drop-before::before {
content: "";
position: absolute;
left: 0;
right: 0;
top: -0.45rem;
height: 2px;
border-radius: 1px;
background: #2563eb;
}
.drag-handle {
position: absolute;
top: 0.1rem;
left: -1.6rem;
padding: 0 0.25rem;
color: #aaa;
cursor: grab;
font-size: 0.85rem;
letter-spacing: -0.15em;
user-select: none;
opacity: 0;
transition: opacity 0.15s;
}
.para-actions {
position: absolute;
top: 0;
right: -2.6rem;
display: flex;
gap: 0.1rem;
opacity: 0;
transition: opacity 0.15s;
}
.paragraph-wrapper:hover .drag-handle,
.paragraph-wrapper:hover .para-actions,
.para-actions:focus-within {
opacity: 1; opacity: 1;
} }
.para-actions button {
border: none;
background: none;
cursor: pointer;
font-size: 1rem;
line-height: 1.5;
}
.remove-btn {
color: #c00;
}
.bank-btn {
color: #b8860b;
}
.section-end {
position: relative;
min-height: 0.5rem;
}
.section-end.empty {
display: flex;
align-items: center;
justify-content: center;
min-height: 2.5rem;
margin-bottom: 0.75rem;
border: 1px dashed #ccc;
border-radius: 4px;
color: #999;
font-size: 0.8rem;
}
.add-btn { .add-btn {
margin-top: 0.5rem; margin-top: 0.5rem;
padding: 0.3rem 0.8rem; padding: 0.3rem 0.8rem;
@@ -179,5 +755,9 @@ function updateParagraph(index, event) {
.no-print { .no-print {
display: none !important; display: none !important;
} }
.cl-wrap.with-bank {
display: block;
padding: 0;
}
} }
</style> </style>
+324
View File
@@ -0,0 +1,324 @@
<script setup>
/**
* The paragraph bank beside the cover letter (admin only, never printed):
* reusable paragraphs from stores/coverSnippets.js, grouped by the section
* they were written for.
*
* Dragging works through the parent, which owns the one drag in progress:
* dragging a snippet out emits `drag-snippet` so CoverLetters.vue can drop a
* copy into the letter, and a letter paragraph dropped here (`accepting` is
* true while one is being dragged) emits `drop-paragraph` for the parent to
* save. Snippets are edited in place and saved on blur.
*/
import { computed, ref } from "vue";
import { useCoverSnippetsStore } from "@/stores/coverSnippets";
const props = defineProps({
// True while a letter paragraph is being dragged, so the bank can light up.
accepting: { type: Boolean, default: false },
// The letter's section titles, offered when adding a snippet.
sectionTitles: { type: Array, default: () => [] },
});
const emit = defineEmits(["drag-snippet", "drag-end", "drop-paragraph"]);
const store = useCoverSnippetsStore();
const filter = ref("");
const error = ref("");
const over = ref(false);
const newText = ref("");
const newSection = ref("");
/** [{ section, snippets }] in the store's order (section, then newest),
* narrowed by the filter, which matches text or section. */
const groups = computed(() => {
const q = filter.value.trim().toLowerCase();
const out = [];
for (const s of store.coverSnippets) {
if (
q &&
!s.text.toLowerCase().includes(q) &&
!s.section.toLowerCase().includes(q)
)
continue;
let group = out.find((g) => g.section === s.section);
if (!group) out.push((group = { section: s.section, snippets: [] }));
group.snippets.push(s);
}
return out;
});
async function run(fn) {
error.value = "";
try {
await fn();
} catch (err) {
error.value = err.message;
}
}
function add() {
run(async () => {
await store.create({ text: newText.value, section: newSection.value });
newText.value = "";
});
}
function save(snippet, field, value) {
if (snippet[field] === value) return;
run(() => store.update(snippet.id, { [field]: value }));
}
function remove(snippet) {
if (!confirm("Delete this paragraph from the bank?")) return;
run(() => store.remove(snippet.id));
}
function onDragStart(snippet, event) {
event.dataTransfer.effectAllowed = "copy";
// Firefox won't start a drag without some data set.
event.dataTransfer.setData("text/plain", snippet.text);
// Only the grip is draggable, so text in the textareas stays selectable
// (Firefox can't place a caret inside a draggable element); show the
// whole card moving rather than the grip.
event.dataTransfer.setDragImage(event.target.closest(".snippet"), 12, 12);
emit("drag-snippet", snippet);
}
function onDragOver(event) {
if (!props.accepting) return;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
over.value = true;
}
function onDrop(event) {
over.value = false;
if (!props.accepting) return;
event.preventDefault();
emit("drop-paragraph");
}
</script>
<template>
<aside
:class="['bank', 'no-print', { accepting, over }]"
@dragover="onDragOver"
@dragleave="over = false"
@drop="onDrop"
>
<div class="bank-head">
<h3>Paragraph bank</h3>
<span class="hint">drag into the letter</span>
</div>
<input
v-model="filter"
class="bank-filter"
type="search"
placeholder="Filter…"
/>
<p v-if="accepting" class="drop-hint">Drop here to save to the bank</p>
<p v-if="error" class="bank-error">{{ error }}</p>
<p v-if="store.error" class="bank-error">
Couldn't load the bank: {{ store.error.message }}
</p>
<p
v-else-if="store.loaded && !store.coverSnippets.length"
class="empty"
>
Nothing saved yet. Drag a paragraph here, or use ☆ on one.
</p>
<section v-for="g in groups" :key="g.section" class="group">
<h4>{{ g.section || "Unsorted" }}</h4>
<div v-for="s in g.snippets" :key="s.id" class="snippet">
<span
class="grip"
draggable="true"
title="Drag into the letter"
@dragstart="onDragStart(s, $event)"
@dragend="emit('drag-end')"
>⋮⋮</span
>
<textarea
:value="s.text"
rows="3"
@blur="save(s, 'text', $event.target.value.trim())"
></textarea>
<div class="snippet-foot">
<input
:value="s.section"
class="snippet-section"
placeholder="Section"
@change="save(s, 'section', $event.target.value.trim())"
/>
<button
class="cv-btn cv-btn-sm cv-btn-danger"
title="Delete from the bank"
@click="remove(s)"
>
×
</button>
</div>
</div>
</section>
<form class="add" @submit.prevent="add">
<textarea
v-model="newText"
rows="3"
placeholder="New reusable paragraph…"
></textarea>
<div class="snippet-foot">
<input
v-model="newSection"
class="snippet-section"
list="cover-section-titles"
placeholder="Section"
/>
<datalist id="cover-section-titles">
<option v-for="t in sectionTitles" :key="t" :value="t" />
</datalist>
<button
class="cv-btn cv-btn-sm"
type="submit"
:disabled="!newText.trim()"
>
Add
</button>
</div>
</form>
</aside>
</template>
<style scoped>
.bank {
align-self: start;
position: sticky;
top: 3.5rem;
max-height: calc(100vh - 4.5rem);
overflow-y: auto;
margin: 1rem 0;
padding: 0.75rem;
border: 1px solid var(--color-line);
border-radius: 6px;
background: var(--color-paper-tint);
font-size: 0.85rem;
transition:
border-color 0.15s,
background 0.15s;
}
.bank.accepting {
border-style: dashed;
border-color: var(--color-ink-muted);
}
.bank.over {
background: var(--color-paper-shade);
}
.bank-head {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 0.5rem;
}
.bank-head h3 {
font-size: 0.95rem;
font-weight: 600;
}
.hint,
.empty,
.drop-hint {
color: var(--color-ink-muted);
font-size: 0.8rem;
}
.drop-hint {
margin: 0.5rem 0;
text-align: center;
}
.bank-error {
color: var(--color-ink-danger);
margin: 0.5rem 0;
}
.bank-filter,
.bank textarea,
.snippet-section {
width: 100%;
padding: 0.25rem 0.4rem;
border: 1px solid var(--color-line);
border-radius: 4px;
font: inherit;
}
.bank textarea {
resize: vertical;
line-height: 1.4;
}
.group {
margin-top: 0.75rem;
}
.group h4 {
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--color-ink-muted);
margin-bottom: 0.3rem;
}
.snippet {
position: relative;
margin-bottom: 0.5rem;
padding: 0.4rem 0.4rem 0.4rem 1.3rem;
border: 1px solid var(--color-line-soft);
border-radius: 4px;
background: var(--color-paper);
}
/* A full-height strip down the left edge, so it is easy to grab. */
.grip {
position: absolute;
inset: 0 auto 0 0;
width: 1.1rem;
padding-top: 0.45rem;
text-align: center;
color: var(--color-ink-faint);
font-size: 0.75rem;
letter-spacing: -0.15em;
cursor: grab;
user-select: none;
}
.grip:hover {
color: var(--color-ink-soft);
background: var(--color-paper-tint);
}
.snippet-foot {
display: flex;
gap: 0.4rem;
margin-top: 0.3rem;
}
.snippet-section {
flex: 1;
font-size: 0.8rem;
}
.add {
margin-top: 1rem;
padding-top: 0.75rem;
border-top: 1px solid var(--color-line);
}
</style>
+133
View File
@@ -0,0 +1,133 @@
/**
* The cover letter as data, with no Vue in it: the default letter, the JSON
* body stored in a CoverLetter row (stores/coverLetters.js), and the moves
* the drag and drop in CoverLetters.vue makes.
*
* Body shape (v: 1):
* { v, name, phone, email, role, signoff,
* sections: [{ id, title, paragraphs: [{ id, text }] }] }
*
* Every section and paragraph carries an id because the template keys its
* v-for on it. Keying on the index would leave a contenteditable showing the
* old text after a reorder, since Vue would reuse the element in place.
*
* A position is `{ section, index }`: a section's index and a paragraph's
* index inside it. `index` may equal the paragraph count, meaning "at the end".
*/
export const BODY_VERSION = 1;
/** A short id, unique enough within one letter. crypto.randomUUID would do,
* but it is missing outside a secure context (the dev stack over a LAN IP). */
export function newId() {
return Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
}
export function newParagraph(text = "New paragraph...") {
return { id: newId(), text };
}
export function newSection(title = "New section", texts = []) {
return { id: newId(), title, paragraphs: texts.map(newParagraph) };
}
/** The blank template a visitor sees, and what "New" starts from. */
export function newLetter() {
return {
v: BODY_VERSION,
name: "Adam French",
phone: "+447563266931",
email: "[email protected]",
role: "Job title / role",
signoff: "Thank you for reading - Adam F",
sections: [
newSection("Why the company", ["Why I'm interested in the company..."]),
newSection("Why I fit", ["Why I'm a strong fit for the role..."]),
newSection("Experience", ["Relevant experience and background..."]),
],
};
}
const str = (v, fallback) => (typeof v === "string" ? v : fallback);
/**
* Read a stored body back into a letter. Anything missing or malformed
* falls back to the default field by field, so a hand-edited or older row
* still opens rather than blanking the page; ids are regenerated if absent.
*/
export function parseBody(json) {
const base = newLetter();
let raw;
try {
raw = JSON.parse(json);
} catch {
return base;
}
if (!raw || typeof raw !== "object") return base;
const sections = Array.isArray(raw.sections)
? raw.sections
.filter((s) => s && typeof s === "object")
.map((s) => ({
id: str(s.id, newId()),
title: str(s.title, ""),
paragraphs: Array.isArray(s.paragraphs)
? s.paragraphs
.filter((p) => p && typeof p.text === "string")
.map((p) => ({ id: str(p.id, newId()), text: p.text }))
: [],
}))
: base.sections;
return {
v: BODY_VERSION,
name: str(raw.name, base.name),
phone: str(raw.phone, base.phone),
email: str(raw.email, base.email),
role: str(raw.role, base.role),
signoff: str(raw.signoff, base.signoff),
sections,
};
}
/** The JSON stored as a CoverLetter's body. Also what the "unsaved" marker
* compares, so the key order here must stay fixed. */
export function serialize(letter) {
return JSON.stringify({
v: BODY_VERSION,
name: letter.name,
phone: letter.phone,
email: letter.email,
role: letter.role,
signoff: letter.signoff,
sections: letter.sections.map((s) => ({
id: s.id,
title: s.title,
paragraphs: s.paragraphs.map((p) => ({ id: p.id, text: p.text })),
})),
});
}
/**
* Move the paragraph at `from` to `to`, both positions as they are before the
* move. Moving down within one section shifts the target up by one once the
* paragraph has been taken out, which is corrected here so a drop lands where
* the indicator showed.
*/
export function moveParagraph(letter, from, to) {
const src = letter.sections[from.section];
const dst = letter.sections[to.section];
if (!src || !dst || !src.paragraphs[from.index]) return;
let index = to.index;
if (from.section === to.section) {
if (index === from.index || index === from.index + 1) return;
if (index > from.index) index -= 1;
}
const [para] = src.paragraphs.splice(from.index, 1);
dst.paragraphs.splice(index, 0, para);
}
/** Put a new paragraph holding `text` at `to`. */
export function insertParagraph(letter, to, text) {
const dst = letter.sections[to.section];
if (!dst) return;
dst.paragraphs.splice(to.index, 0, newParagraph(text));
}