Open platform to collect and prioritize feedback
Added import and export for tags
Albert Nimtz2060ed9689ad
diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex b55a39c98..80ee1d88d 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -176,6 +176,8 @@ func routes(r *web.Engine) *web.Engine {ui.Get("/admin/export", handlers.Page("Export · Site Settings", "", "Administration/pages/Export.page"))ui.Get("/admin/export/posts.csv", handlers.ExportPostsToCSV())ui.Get("/admin/export/backup.zip", handlers.ExportBackupZip())+ ui.Get("/admin/export/tags.json", handlers.ExportTagsJSON())+ ui.Post("/_api/admin/import/tags", handlers.ImportTagsJSON())ui.Get("/admin/webhooks", handlers.ManageWebhooks())ui.Post("/_api/admin/webhook", handlers.CreateWebhook())ui.Put("/_api/admin/webhook/:id", handlers.UpdateWebhook())diff --git a/app/handlers/tag_import_export.go b/app/handlers/tag_import_export.gonew file mode 100644index 000000000..6b8e28720--- /dev/null+++ b/app/handlers/tag_import_export.go@@ -0,0 +1,117 @@+package handlers++import (+ "encoding/json"+ "strings"++ "github.com/getfider/fider/app"+ "github.com/getfider/fider/app/models/cmd"+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/query"+ "github.com/getfider/fider/app/pkg/bus"+ "github.com/getfider/fider/app/pkg/errors"+ "github.com/getfider/fider/app/pkg/web"+)++// ExportTagsJSON returns a JSON file with all tags+func ExportTagsJSON() web.HandlerFunc {+ return func(c *web.Context) error {+ getAllTags := &query.GetAllTags{}+ if err := bus.Dispatch(c, getAllTags); err != nil {+ return c.Failure(err)+ }++ data, err := json.MarshalIndent(getAllTags.Result, "", " ")+ if err != nil {+ return c.Failure(errors.Wrap(err, "failed to marshal tags"))+ }++ return c.Attachment("tags.json", "application/json", data)+ }+}++// importTagInput is the shape of each tag in an import payload+type importTagInput struct {+ Name string `json:"name"`+ Color string `json:"color"`+ IsPublic bool `json:"isPublic"`+}++// ImportTagsResult is returned after an import+type ImportTagsResult struct {+ Created int `json:"created"`+ Skipped int `json:"skipped"`+ Errors []string `json:"errors"`+}++// ImportTagsJSON accepts a JSON array of tags and creates missing ones+func ImportTagsJSON() web.HandlerFunc {+ return func(c *web.Context) error {+ if c.Request.ContentLength == 0 {+ return c.BadRequest(web.Map{"error": "request body is empty"})+ }++ var input []importTagInput+ if err := json.Unmarshal([]byte(c.Request.Body), &input); err != nil {+ return c.BadRequest(web.Map{"error": "invalid JSON: " + err.Error()})+ }++ if len(input) == 0 {+ return c.BadRequest(web.Map{"error": "no tags provided"})+ }++ // Fetch existing tags once so we can skip duplicates+ getAllTags := &query.GetAllTags{}+ if err := bus.Dispatch(c, getAllTags); err != nil {+ return c.Failure(err)+ }++ existing := make(map[string]*entity.Tag, len(getAllTags.Result))+ for _, t := range getAllTags.Result {+ existing[strings.ToLower(t.Name)] = t+ }++ result := ImportTagsResult{}++ for _, t := range input {+ name := strings.TrimSpace(t.Name)+ color := strings.ToUpper(strings.TrimSpace(t.Color))++ if name == "" {+ result.Errors = append(result.Errors, "tag with empty name skipped")+ result.Skipped+++ continue+ }+ if len(color) != 6 {+ result.Errors = append(result.Errors, "tag '"+name+"': color must be exactly 6 hex characters")+ result.Skipped+++ continue+ }++ if _, exists := existing[strings.ToLower(name)]; exists {+ result.Skipped+++ continue+ }++ addTag := &cmd.AddNewTag{+ Name: name,+ Color: color,+ IsPublic: t.IsPublic,+ }+ if err := bus.Dispatch(c, addTag); err != nil {+ if errors.Cause(err) == app.ErrNotFound {+ result.Skipped+++ } else {+ result.Errors = append(result.Errors, "tag '"+name+"': "+err.Error())+ result.Skipped+++ }+ continue+ }++ existing[strings.ToLower(name)] = addTag.Result+ result.Created+++ }++ return c.Ok(result)+ }+}diff --git a/public/assets/images/heroicons-upload.svg b/public/assets/images/heroicons-upload.svgnew file mode 100644index 000000000..12535d25a--- /dev/null+++ b/public/assets/images/heroicons-upload.svg@@ -0,0 +1,4 @@+<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"+ d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0l-4 4m4-4v12" />+</svg>\ No newline at end of filediff --git a/public/pages/Administration/pages/ManageTags.page.tsx b/public/pages/Administration/pages/ManageTags.page.tsxindex 09d5fb257..04072f088 100644--- a/public/pages/Administration/pages/ManageTags.page.tsx+++ b/public/pages/Administration/pages/ManageTags.page.tsx@@ -1,12 +1,16 @@import React from "react"-import { Button } from "@fider/components"+import { Button, Icon } from "@fider/components"import { Tag } from "@fider/models"import { actions, Failure, Fider } from "@fider/services"+import { ImportTagsResult } from "@fider/services/actions/tag"import { AdminBasePage } from "../components/AdminBasePage"import { TagFormState, TagForm } from "../components/TagForm"import { TagListItem } from "../components/TagListItem"import { VStack } from "@fider/components/layout"+import IconDownload from "@fider/assets/images/heroicons-download.svg"+import IconUpload from "@fider/assets/images/heroicons-upload.svg"+import IconPlus from "@fider/assets/images/heroicons-plus.svg"interface ManageTagsPageProps {tags: Tag[]@@ -17,6 +21,9 @@ interface ManageTagsPageState {allTags: Tag[]deleting?: numberediting?: number+ importStatus?: "idle" | "loading" | "success" | "error"+ importResult?: ImportTagsResult+ importError?: string}const tagSorter = (t1: Tag, t2: Tag) => {@@ -39,6 +46,7 @@ export default class ManageTagsPage extends AdminBasePage<ManageTagsPageProps, Mthis.state = {isAdding: false,allTags: this.props.tags,+ importStatus: "idle",}}@@ -85,6 +93,43 @@ export default class ManageTagsPage extends AdminBasePage<ManageTagsPageProps, M})}+ private handleImportFile = async (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0]+ if (!file) return++ this.setState({ importStatus: "loading", importResult: undefined, importError: undefined })++ try {+ const text = await file.text()+ let parsed: Array<{ name: string; color: string; isPublic: boolean }>++ try {+ parsed = JSON.parse(text)+ } catch {+ this.setState({ importStatus: "error", importError: "Invalid JSON file." })+ return+ }++ if (!Array.isArray(parsed)) {+ this.setState({ importStatus: "error", importError: "JSON must be an array of tags." })+ return+ }++ const result = await actions.importTags(parsed)+ if (result.ok) {+ // Reload newly-created tags by merging them in (simplest: re-fetch via reload)+ this.setState({ importStatus: "success", importResult: result.data })+ } else {+ this.setState({ importStatus: "error", importError: "Import failed. Please check the file format." })+ }+ } catch {+ this.setState({ importStatus: "error", importError: "An unexpected error occurred." })+ }++ // Reset the file input so the same file can be selected again+ e.target.value = ""+ }+public content() {const publicTaglist = this.getTagList((t) => t.isPublic)const privateTagList = this.getTagList((t) => !t.isPublic)@@ -95,27 +140,74 @@ export default class ManageTagsPage extends AdminBasePage<ManageTagsPageProps, M<TagForm onSave={this.saveNewTag} onCancel={this.cancelAdd} />) : (<Button variant="secondary" onClick={this.addNew}>- Add new+ <Icon sprite={IconPlus} />+ <span>Add new</span></Button>))+ const { importStatus, importResult, importError } = this.state+return (<VStack spacing={8}><div><h2 className="text-display">Public Tags</h2><p className="text-muted">These tags are visible to all visitors.</p><VStack spacing={4} divide={true}>- {publicTaglist.length === 0 ? <p className="text-muted">There aren’t any public tags yet.</p> : publicTaglist}+ {publicTaglist.length === 0 ? <p className="text-muted">There aren't any public tags yet.</p> : publicTaglist}</VStack></div><div><h2 className="text-display">Private Tags</h2><p className="text-muted">These tags are only visible for members of this site.</p><VStack spacing={4} divide={true}>- {privateTagList.length === 0 ? <p className="text-muted">There aren’t any private tags yet.</p> : privateTagList}+ {privateTagList.length === 0 ? <p className="text-muted">There aren't any private tags yet.</p> : privateTagList}</VStack></div><div>{form}</div>++ {Fider.session.user.isAdministrator && (+ <div className="mt-4">+ <h2 className="text-display">Import & Export Tags</h2>+ <p className="text-muted">+ Download all your tags as a JSON file, or upload a <code>tags.json</code> file to restore or add tags. Existing tags with the same name will be+ skipped.+ </p>+ <div className="flex gap-2">+ <Button variant="secondary" href="/admin/export/tags.json">+ <Icon sprite={IconDownload} />+ <span>Export tags.json</span>+ </Button>+ <label>+ <input+ type="file"+ accept=".json,application/json"+ className="hidden"+ onChange={this.handleImportFile}+ disabled={importStatus === "loading"}+ id="tags-import-input"+ />+ <Button variant="secondary" onClick={() => document.getElementById("tags-import-input")?.click()} disabled={importStatus === "loading"}>+ <Icon sprite={IconUpload} />+ <span>{importStatus === "loading" ? "Importing…" : "Import tags.json"}</span>+ </Button>+ </label>+ </div>++ {importStatus === "success" && importResult && (+ <div className="mt-2 text-green-700">+ ✓ Import complete — <strong>{importResult.created}</strong> tag(s) created, <strong>{importResult.skipped}</strong> skipped.+ {importResult.errors && importResult.errors.length > 0 && (+ <ul className="mt-1 text-red-600 text-sm list-disc list-inside">+ {importResult.errors.map((e, i) => (+ <li key={i}>{e}</li>+ ))}+ </ul>+ )}+ </div>+ )}+ {importStatus === "error" && <div className="mt-2 text-red-600">✗ {importError}</div>}+ </div>+ )}</VStack>)}diff --git a/public/services/actions/tag.ts b/public/services/actions/tag.tsindex 3f59097eb..be18f38ac 100644--- a/public/services/actions/tag.ts+++ b/public/services/actions/tag.ts@@ -20,3 +20,13 @@ export const assignTag = async (slug: string, postNumber: number): Promise<Resulexport const unassignTag = async (slug: string, postNumber: number): Promise<Result> => {return http.delete(`/api/v1/posts/${postNumber}/tags/${slug}`).then(http.event("tag", "unassign"))}++export interface ImportTagsResult {+ created: number+ skipped: number+ errors: string[]+}++export const importTags = async (tags: Array<{ name: string; color: string; isPublic: boolean }>): Promise<Result<ImportTagsResult>> => {+ return http.post<ImportTagsResult>(`/_api/admin/import/tags`, tags).then(http.event("tag", "import"))+}