SPB Git

Repository Public

defaults.ts 12.2 KB 140 lines typescript

1/**2 * The catalogue of block types offered by the editor, and the factory of new blocks. Pure: usable on the server3 * (templates, tests) as well as in the browser.4 */5import { BlockSchema, LeafBlockSchema, newId, type Block, type BlockType, type Icon, type LeafBlock, type Locale, type SimKind } from "@/schema";6import { SIMULATIONS } from "@/sim/registry";7import { simDefaultConfig, simParams } from "./helpers";89export type BlockGroup = "text" | "structure" | "visual" | "data" | "interactive";10export interface CatalogEntry { type: BlockType; label: Record<Locale, string>; description: Record<Locale, string>; group: BlockGroup; icon: Icon }1112const entry = (type: BlockType, group: BlockGroup, icon: Icon, fr: string, en: string, dfr: string, den: string): CatalogEntry => ({ type, group, icon, label: { fr, en }, description: { fr: dfr, en: den } });1314/** One entry per block type. `CATALOG_BY_TYPE` below makes a missing type a compile error. */15const CATALOG_BY_TYPE: Record<BlockType, CatalogEntry> = {16  heading: entry("heading", "text", "document", "Titre", "Heading", "Titre de section, sur trois niveaux.", "Section title, three levels."),17  paragraph: entry("paragraph", "text", "book", "Paragraphe", "Paragraph", "Texte courant, ou chapeau d’introduction.", "Body text, or a lead paragraph."),18  list: entry("list", "text", "queue", "Liste", "List", "Liste à puces, numérotée ou à cocher.", "Bulleted, numbered or check list."),19  callout: entry("callout", "text", "info", "Encadré", "Callout", "Note, définition, théorème, mise en garde.", "Note, definition, theorem, warning."),20  equation: entry("equation", "text", "sigma", "Équation", "Equation", "Formule LaTeX avec ses variables.", "LaTeX formula with its variables."),21  code: entry("code", "text", "code", "Code", "Code", "Extrait de code coloré.", "Highlighted code excerpt."),22  references: entry("references", "text", "link", "Références", "References", "Liste des sources de la fiche.", "The list of the sheet’s sources."),23  divider: entry("divider", "structure", "arrows", "Séparateur", "Divider", "Filet entre deux parties.", "A rule between two parts."),24  cards: entry("cards", "structure", "layers", "Cartes", "Cards", "Grille de cartes avec icône et couleur.", "Grid of cards with icon and colour."),25  steps: entry("steps", "structure", "route", "Étapes", "Steps", "Suite d’étapes numérotées.", "A numbered sequence of steps."),26  timeline: entry("timeline", "structure", "clock", "Chronologie", "Timeline", "Jalons datés, en ligne ou en colonne.", "Dated milestones, in a row or a column."),27  comparison: entry("comparison", "structure", "scale", "Comparaison", "Comparison", "Options côte à côte, critère par critère.", "Options side by side, criterion by criterion."),28  accordion: entry("accordion", "structure", "split", "Accordéon", "Accordion", "Sections repliables.", "Collapsible sections."),29  tabs: entry("tabs", "structure", "puzzle", "Onglets", "Tabs", "Plusieurs blocs rangés par onglet.", "Several blocks arranged in tabs."),30  legend: entry("legend", "visual", "eye", "Légende", "Legend", "Signification des couleurs et des traits.", "What colours and strokes mean."),31  diagram: entry("diagram", "visual", "network", "Diagramme", "Diagram", "Nœuds, flèches et groupes, mis en page automatiquement.", "Nodes, arrows and groups, laid out automatically."),32  svg: entry("svg", "visual", "sparkles", "Illustration SVG", "SVG illustration", "Dessin vectoriel, nettoyé à l’import.", "Vector drawing, sanitised on import."),33  image: entry("image", "visual", "globe", "Image", "Image", "Image téléversée, avec légende.", "Uploaded picture, with a caption."),34  table: entry("table", "data", "table", "Tableau", "Table", "Tableau de texte, jusqu’à 8 colonnes.", "Text table, up to 8 columns."),35  chart: entry("chart", "data", "chart", "Graphique", "Chart", "Courbe, aire, barres, nuage ou histogramme.", "Line, area, bar, scatter or histogram."),36  matrix: entry("matrix", "data", "calculator", "Matrice", "Matrix", "Grille de nombres colorée (carte de chaleur).", "Coloured grid of numbers (heat map)."),37  quiz: entry("quiz", "interactive", "target", "Quiz", "Quiz", "Question à choix, avec explications.", "Multiple-choice question, with explanations."),38  simulation: entry("simulation", "interactive", "flask", "Simulation", "Simulation", "Modèle interactif à curseurs.", "Interactive model with sliders."),39};4041const ORDER: BlockType[] = [42  "heading", "paragraph", "list", "callout", "equation", "code", "references",43  "divider", "cards", "steps", "timeline", "comparison", "accordion", "tabs",44  "legend", "diagram", "svg", "image",45  "table", "chart", "matrix",46  "quiz", "simulation",47];48/** Every block type exactly once, grouped as the insertion menu shows them. */49export const BLOCK_CATALOG: CatalogEntry[] = [...ORDER, ...(Object.keys(CATALOG_BY_TYPE) as BlockType[]).filter((t) => !ORDER.includes(t))].map((t) => CATALOG_BY_TYPE[t]);50export const catalogEntry = (type: BlockType): CatalogEntry => CATALOG_BY_TYPE[type];5152/** Asset reference of a new image block until the author picks one (`opts.assetRef` avoids it). Never present in `doc.assets`. */53export const IMAGE_PLACEHOLDER_REF = "image-a-choisir";5455export interface NewBlockOptions { simKind?: SimKind; /** Local id (doc.assets[].id) of the picture of a new image block. */ assetRef?: string }5657type Draft = { type: BlockType } & Record<string, unknown>;5859function starter(type: BlockType, fr: boolean, opts: NewBlockOptions): Draft {60  const L = (f: string, e: string) => (fr ? f : e);61  switch (type) {62    case "heading": return { type, level: 2, text: L("Nouveau titre", "New heading") };63    case "paragraph": return { type, text: L("Nouveau paragraphe. Le texte accepte **gras**, *italique*, `code` et $x^2$.", "New paragraph. The text accepts **bold**, *italic*, `code` and $x^2$.") };64    case "list": return { type, style: "bullet", items: [L("Premier point", "First point"), L("Deuxième point", "Second point")] };65    case "equation": return { type, latex: "y = \\beta_0 + \\beta_1 x + \\varepsilon", derivation: "standard", variables: [{ symbol: "y", meaning: L("Variable expliquée", "Dependent variable") }, { symbol: "\\varepsilon", meaning: L("Terme d’erreur", "Error term") }] };66    case "callout": return { type, tone: "note", title: L("À retenir", "Key point"), text: L("Texte de l’encadré.", "Text of the callout.") };67    case "table": return { type, columns: [{ label: L("Colonne 1", "Column 1"), align: "left" }, { label: L("Colonne 2", "Column 2"), align: "left" }], rows: [["", ""], ["", ""]] };68    case "cards": return { type, columns: 3, items: [1, 2, 3].map((n) => ({ title: L(`Carte ${n}`, `Card ${n}`), text: L("Texte de la carte.", "Text of the card."), tone: "neutral" })) };69    case "steps": return { type, items: [1, 2, 3].map((n) => ({ title: L(`Étape ${n}`, `Step ${n}`), text: L("Ce qui se passe à cette étape.", "What happens at this step.") })) };70    case "legend": return { type, items: [{ label: L("Catégorie A", "Category A"), tone: "blue", shape: "square" }, { label: L("Catégorie B", "Category B"), tone: "amber", shape: "square" }] };71    case "diagram": return {72      type, kind: "flow", direction: "LR", routing: "curved",73      alt: L("Diagramme : l’entrée passe par un traitement et produit une sortie.", "Diagram: the input goes through a process and produces an output."),74      nodes: [{ id: "n-entree", label: L("Entrée", "Input"), shape: "round", tone: "blue" }, { id: "n-traitement", label: L("Traitement", "Process"), shape: "round", tone: "neutral" }, { id: "n-sortie", label: L("Sortie", "Output"), shape: "round", tone: "green" }],75      edges: [{ id: "e-1", from: "n-entree", to: "n-traitement" }, { id: "e-2", from: "n-traitement", to: "n-sortie" }],76      groups: [], legend: [{ label: L("Flux de données", "Data flow"), tone: "neutral", shape: "arrow" }],77    };78    case "timeline": return { type, orientation: "vertical", items: [{ when: "2017", title: L("Premier jalon", "First milestone"), tone: "neutral" }, { when: "2024", title: L("Deuxième jalon", "Second milestone"), tone: "neutral" }] };79    case "matrix": return {80      type, rowLabels: ["A", "B", "C"], colLabels: ["A", "B", "C"], values: [[1, 0.5, 0.2], [0.5, 1, 0.4], [0.2, 0.4, 1]],81      scale: "sequential", showValues: true, decimals: 2, dataKind: "illustrative",82      alt: L("Matrice 3 × 3 de valeurs illustratives entre 0 et 1.", "3 × 3 matrix of illustrative values between 0 and 1."),83    };84    case "code": return { type, language: "python", code: "import numpy as np\n\nx = np.linspace(0, 1, 11)\nprint(x.mean())" };85    case "chart": return {86      type, kind: "line", dataKind: "illustrative",87      title: L("Titre du graphique", "Chart title"),88      alt: L("Courbe illustrative qui croît de 1 à 6 entre x = 0 et x = 4.", "Illustrative line rising from 1 to 6 between x = 0 and x = 4."),89      x: { label: "x", type: "number", scale: "linear" }, y: { label: "y", scale: "linear" },90      series: [{ name: L("Série 1", "Series 1"), tone: "blue", points: [{ x: 0, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 3.5 }, { x: 3, y: 4.5 }, { x: 4, y: 6 }] }],91    };92    case "svg": return {93      type, alt: L("Illustration provisoire : un cercle dans un cadre.", "Placeholder illustration: a circle inside a frame."),94      tree: { tag: "svg", attrs: { viewBox: "0 0 240 120" }, children: [95        { tag: "rect", attrs: { x: "4", y: "4", width: "232", height: "112", rx: "12", fill: "none", stroke: "currentColor", "stroke-width": "2" }, children: [] },96        { tag: "circle", attrs: { cx: "120", cy: "60", r: "30", fill: "none", stroke: "currentColor", "stroke-width": "2" }, children: [] },97      ] },98    };99    case "image": return { type, assetRef: opts.assetRef ?? IMAGE_PLACEHOLDER_REF };100    case "comparison": return {101      type, columns: [{ title: L("Option A", "Option A"), tone: "blue" }, { title: L("Option B", "Option B"), tone: "amber" }],102      rows: [{ label: L("Critère 1", "Criterion 1"), cells: ["", ""] }, { label: L("Critère 2", "Criterion 2"), cells: ["", ""] }],103    };104    case "accordion": return { type, items: [{ title: L("Première section", "First section"), text: L("Contenu de la section.", "Content of the section.") }] };105    case "quiz": return { type, question: L("Quelle affirmation est vraie ?", "Which statement is true?"), choices: [{ text: L("Première réponse", "First answer"), correct: true, explanation: L("Pourquoi c’est juste.", "Why this is right.") }, { text: L("Deuxième réponse", "Second answer"), correct: false }] };106    case "simulation": {107      const kind = opts.simKind ?? "distribution";108      const config = simDefaultConfig(kind);109      const title = SIMULATIONS[kind].title[fr ? "fr" : "en"];110      return { type, kind, title, alt: L(`Simulation interactive : ${title}.`, `Interactive simulation: ${title}.`).slice(0, 600), seed: 1, config, params: simParams(kind, config) };111    }112    case "references": return { type, title: L("Références", "References") };113    case "divider": return { type };114    case "tabs": return {115      type, tabs: [1, 2].map((n) => ({ id: newId("t"), label: L(`Onglet ${n}`, `Tab ${n}`), blocks: [{ id: newId(), type: "paragraph", text: L(`Contenu de l’onglet ${n}.`, `Content of tab ${n}.`) }] })),116    };117  }118}119120/** A valid block of the given type, with a fresh id and starter content in the given language. */121export function newBlock(type: BlockType, locale: Locale, opts: NewBlockOptions = {}): Block {122  return BlockSchema.parse({ id: newId(), ...starter(type, locale === "fr", opts) });123}124125/** A valid block for a tab (anything but tabs). */126export function newLeafBlock(type: LeafBlock["type"], locale: Locale, opts: NewBlockOptions = {}): LeafBlock {127  return LeafBlockSchema.parse({ id: newId(), ...starter(type, locale === "fr", opts) });128}129130/**131 * Deep copy with fresh ids wherever ids must be unique in a document: the block, and for tabs every tab and every132 * nested block. Diagram node, edge and group ids are local to their block and stay as they are.133 */134export function duplicateBlock<B extends Block | LeafBlock>(block: B): B {135  const copy = structuredClone(block);136  copy.id = newId();137  if (copy.type === "tabs") for (const tab of copy.tabs) { tab.id = newId("t"); for (const child of tab.blocks) child.id = newId(); }138  return copy;139}140
Files main
Menu

Theme