import http from './client' import type { BatchDeleteResult, PageQuery, PageResult } from './types' /** One placement of a library field inside a template, with its typography. */ export interface TemplateField { id: number field_id: number /** Display position. The only thing that decides render order. */ sort: number name: string level: number font_size: number font_color: string } /** A template as it appears in the list table. */ export interface TemplateListItem { id: number name: string abstract: string | null field_count: number created_at: string updated_at: string } /** A template with its outline, already ordered by `sort`. */ export interface TemplateDetail { id: number name: string abstract: string | null fields: TemplateField[] created_at: string updated_at: string } /** One entry of the selection sent on create/update. */ export interface TemplateFieldInput { field_id: number sort: number } export interface TemplatePayload { name: string abstract: string | null fields: TemplateFieldInput[] } export async function listTemplates( query: PageQuery = {}, ): Promise> { const params: Record = {} if (query.keyword) params.keyword = query.keyword if (query.page) params.page = query.page if (query.page_size) params.page_size = query.page_size const { data } = await http.get>('/templates', { params }) return data } export async function getTemplate(id: number): Promise { const { data } = await http.get(`/templates/${id}`) return data } /** The API caps `page_size` at 200; a picker wants every template, so it loops. */ const TEMPLATE_PAGE_SIZE = 200 /** * Fetch every template, following pagination. * * A template picker that showed only the first page would silently hide the * template the user is looking for, and the paper view needs the whole list * before it can offer a switch without a search round trip. */ export async function fetchAllTemplates(): Promise { const all: TemplateListItem[] = [] let page = 1 for (;;) { const result = await listTemplates({ page, page_size: TEMPLATE_PAGE_SIZE }) all.push(...result.items) if (page >= result.pages || result.items.length === 0) { return all } page += 1 } } export async function createTemplate(payload: TemplatePayload): Promise { const { data } = await http.post('/templates', payload) return data } export async function updateTemplate( id: number, payload: Partial, ): Promise { const { data } = await http.patch(`/templates/${id}`, payload) return data } export async function deleteTemplate(id: number): Promise { await http.delete(`/templates/${id}`) } export async function batchDeleteTemplates(ids: number[]): Promise { const { data } = await http.post('/templates/batch-delete', { ids }) return data }