// Word (.docx) çıktısını APA 7 biçimine getiren yardımcılar: // - Pandoc'un varsayılan şablon belgesinden APA 7 stilleriyle bir şablon (reference.docx) üretir. // - apa7 sınıfının başlık sayfası alanlarını kaynaktan çıkarır. // - Pandoc ara biçimine (JSON) APA başlık sayfası, özet, tablo/şekil başlıkları ve kaynakça bölümü ekler. import { existsSync } from 'node:fs'; import { writeFile } from 'node:fs/promises'; import path from 'node:path'; import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate'; import { DATA_DIR } from './config.js'; const W = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'; const FONT = 'Times New Roman'; const RFONTS = ``; // APA 7: çift satır aralığı, paragraflar arasında boşluk yok, ilk satır girintisi 1,27 cm (0,5 inç). const SPACING = ''; const INDENT = ''; const BLACK = ''; /** OOXML öğe sırasına uygun paragraf stili. */ function paragraphStyle(id, name, { keep = false, indent = '', center = false, right = false, outline, bold = false, italic = false, basedOn = 'Normal' } = {}) { const pPr = [ keep ? '' : '', SPACING, indent, center ? '' : right ? '' : '', outline != null ? `` : '', ].join(''); const rPr = [RFONTS, bold ? '' : '', italic ? '' : '', BLACK].join(''); return `${pPr}${rPr}`; } const APA_STYLES = [ paragraphStyle('BodyText', 'Body Text', { indent: INDENT }), paragraphStyle('FirstParagraph', 'First Paragraph', { indent: INDENT, basedOn: 'BodyText' }), paragraphStyle('Compact', 'Compact'), paragraphStyle('Title', 'Title', { keep: true, center: true, bold: true }), paragraphStyle('Subtitle', 'Subtitle', { center: true }), paragraphStyle('Author', 'Author', { center: true }), paragraphStyle('Date', 'Date', { center: true }), paragraphStyle('AbstractTitle', 'Abstract Title', { keep: true, center: true, bold: true }), paragraphStyle('Abstract', 'Abstract'), // APA 7 başlık düzeyleri paragraphStyle('Heading1', 'heading 1', { keep: true, center: true, outline: 0, bold: true }), paragraphStyle('Heading2', 'heading 2', { keep: true, outline: 1, bold: true }), paragraphStyle('Heading3', 'heading 3', { keep: true, outline: 2, bold: true, italic: true }), paragraphStyle('Heading4', 'heading 4', { keep: true, indent: INDENT, outline: 3, bold: true }), paragraphStyle('Heading5', 'heading 5', { keep: true, indent: INDENT, outline: 4, bold: true, italic: true }), // Kaynakça: asılı girinti paragraphStyle('Bibliography', 'Bibliography', { indent: '' }), paragraphStyle('BlockText', 'Block Text', { indent: '' }), paragraphStyle('Caption', 'Caption', { keep: true }), paragraphStyle('TableCaption', 'Table Caption', { keep: true, basedOn: 'Caption' }), paragraphStyle('ImageCaption', 'Image Caption', { basedOn: 'Caption' }), paragraphStyle('TOCHeading', 'TOC Heading', { keep: true, center: true, bold: true }), paragraphStyle('Header', 'header', { right: true }), // Thoth'un eklediği paragraflar için (Pandoc "custom-style" ile adından eşler) paragraphStyle('APAEtiket', 'APA Etiket', { keep: true }), paragraphStyle('APAOrtali', 'APA Ortalı', { center: true }), paragraphStyle('APADenklemNo', 'APA Denklem No', { right: true }), ``, ]; const HEADER_XML = ` PAGE 1`; // A4, dört kenarda 2,54 cm (1 inç) boşluk, sağ üstte sayfa numarası. const SECT_PR = ''; /** Pandoc'un varsayılan şablon belgesini APA 7 stillerine çevirir. */ export function patchReferenceDoc(bytes) { const zip = unzipSync(bytes); let styles = strFromU8(zip['word/styles.xml']); styles = styles .replace(/[\s\S]*?<\/w:rPrDefault>/, `${RFONTS}${BLACK}`) .replace(/[\s\S]*?<\/w:pPrDefault>/, `${SPACING}`) // Tema yazı tipleri ve renkler: her yerde Times New Roman ve siyah .replace(/]*?[Tt]heme[^>]*\/>/g, RFONTS) .replace(/]*\/>/g, '') .replace(//g, '') .replace(//g, ''); for (const style of APA_STYLES) { const id = style.match(/w:styleId="([^"]+)"/)[1]; const existing = new RegExp(`]*w:styleId="${id}"[^>]*>[\\s\\S]*?`); styles = existing.test(styles) ? styles.replace(existing, style) : styles.replace('', `${style}`); } zip['word/styles.xml'] = strToU8(styles); const doc = strFromU8(zip['word/document.xml']); zip['word/document.xml'] = strToU8(doc.replace(/[\s\S]*?<\/w:sectPr>/, SECT_PR)); zip['word/header1.xml'] = strToU8(HEADER_XML); const rels = strFromU8(zip['word/_rels/document.xml.rels']); zip['word/_rels/document.xml.rels'] = strToU8(rels.replace( '', '', )); const types = strFromU8(zip['[Content_Types].xml']); zip['[Content_Types].xml'] = strToU8(types.replace( '', '', )); return zipSync(zip); } const escapeXml = (s) => s.replace(/&/g, '&').replace(//g, '>'); /** Şablon belgenin üst bilgisine solda kısa başlığı (APA 7 profesyonel makale), sağda sayfa numarasını koyar. */ export function withRunningHead(referenceBytes, runningHead) { const zip = unzipSync(new Uint8Array(referenceBytes)); // A4 metin genişliği: 11906 - 2 x 1440 = 9026 twip zip['word/header1.xml'] = strToU8(HEADER_XML.replace( '', `${escapeXml(runningHead)}`, )); return zipSync(zip); } const REFERENCE_DOC = path.join(DATA_DIR, 'apa7-sablon-v1.docx'); /** APA 7 şablon belgesinin yolunu verir; yoksa Pandoc'un varsayılanından üretir. */ export async function apaReferenceDoc(runPandoc) { if (existsSync(REFERENCE_DOC)) return REFERENCE_DOC; const { code, stdout, stderr } = await runPandoc(['--print-default-data-file', 'reference.docx']); if (code !== 0) throw new Error(`Word şablonu alınamadı: ${stderr}`); await writeFile(REFERENCE_DOC, patchReferenceDoc(new Uint8Array(stdout))); return REFERENCE_DOC; } // ---- apa7 sınıfının başlık sayfası alanları ---- /** `\komut{...}` biçimindeki ilk komutun (yıldızsız) dengeli parantezli bağımsız değişkenini döndürür. */ export function extractCommand(source, name) { const re = new RegExp(`\\\\${name}(?![a-zA-Z*])\\s*\\{`, 'g'); for (const m of source.matchAll(re)) { // Yorum satırındaki komutlar atlanır. const lineStart = source.lastIndexOf('\n', m.index) + 1; if (/(? 0; i++) { if (source[i] === '\\') i++; else if (source[i] === '{') depth++; else if (source[i] === '}') depth--; } if (depth === 0) return source.slice(start, i - 1).trim(); } return null; } export const FRONT_FIELDS = ['title', 'shorttitle', 'authorsnames','authorsaffiliations', 'course', 'professor', 'duedate', 'authornote', 'abstract', 'keywords']; /** Belge apa7 sınıfını kullanıyorsa kipini ve başlık sayfası alanlarını (LaTeX olarak) verir. */ export function apaFrontMatter(source) { const cls = source.match(/\\documentclass\s*(?:\[([^\]]*)\])?\s*\{apa7\}/); if (!cls) return null; const options = (cls[1] ?? '').split(',').map((o) => o.trim()); const fields = {}; for (const f of FRONT_FIELDS) fields[f] = extractCommand(source, f); return { student: options.includes('stu'), repeatTitle: !options.includes('donotrepeattitle'), fields, }; } // ---- Pandoc ara biçimi (JSON) yardımcıları ---- const str = (text) => text.split(/(\s+)/).filter(Boolean).map((p) => (/^\s+$/.test(p) ? { t: 'Space' } : { t: 'Str', c: p })); const para = (inlines) => ({ t: 'Para', c: inlines }); const styled = (style, blocks) => ({ t: 'Div', c: [['', [], [['custom-style', style]]], blocks] }); const raw = (xml) => ({ t: 'RawBlock', c: ['openxml', xml] }); export const PAGE_BREAK = raw(''); const EMPTY_LINE = raw(''); export const TOC = raw( '' + 'İçindekiler' + ' TOC \\o "1-3" \\h \\z \\u ' + 'İçindekiler tablosunu görmek için alanları güncelleyin (F9).' + '', ); /** Bir blok listesinin ilk paragrafının satır içi öğeleri. */ const inlinesOf = (blocks) => { const first = (blocks ?? []).find((b) => b.t === 'Plain' || b.t === 'Para'); return first ? first.c : []; }; /** Satır içi öğelerin düz metni. */ export function plainText(blocks) { const text = (node) => { if (Array.isArray(node)) return node.map(text).join(''); if (!node || typeof node !== 'object') return ''; if (node.t === 'Str') return node.c; if (node.t === 'Space' || node.t === 'SoftBreak' || node.t === 'LineBreak') return ' '; return Array.isArray(node.c) ? text(node.c) : ''; }; return text(inlinesOf(blocks)).trim(); } /** * Etiketli ayrık denklemlere APA'daki gibi sağda "(1)" numarası verir ve \ref atıflarını bu numaralarla * değiştirir (Pandoc denklem atıflarını "[eq:etiket]" olarak bırakır). */ function numberEquations(blocks) { const numbers = new Map(); const collect = (node) => { if (Array.isArray(node)) return node.forEach(collect); if (!node || typeof node !== 'object') return; if (node.t === 'Math' && node.c[0].t === 'DisplayMath') { for (const m of node.c[1].matchAll(/\\label\{([^}]+)\}/g)) if (!numbers.has(m[1])) numbers.set(m[1], numbers.size + 1); } Object.values(node).forEach(collect); }; collect(blocks); if (!numbers.size) return blocks; const labelsIn = (node) => JSON.stringify(node).match(/\\\\label\{[^}]+\}/g)?.map((l) => l.slice(8, -1)) ?? []; const rewrite = (node) => { if (Array.isArray(node)) { // Denklem içeren paragrafın ardına sağa yaslı "(n)" satırı eklenir. return node.flatMap((n) => { if ((n?.t === 'Para' || n?.t === 'Plain') && n.c.some((i) => i.t === 'Math' && i.c[0].t === 'DisplayMath')) { const nums = labelsIn(n).filter((l) => numbers.has(l)).map((l) => numbers.get(l)); return [rewrite(n), ...nums.map((num) => styled('APA Denklem No', [para([{ t: 'Str', c: `(${num})` }])]))]; } return [rewrite(n)]; }); } if (!node || typeof node !== 'object') return node; if (node.t === 'Math' && node.c[0].t === 'DisplayMath') return { t: 'Math', c: [node.c[0], node.c[1].replace(/\\label\{[^}]*\}/g, '')] }; if (node.t === 'Link') { const target = node.c[2][0].replace(/^#/, ''); if (numbers.has(target)) return { t: 'Str', c: String(numbers.get(target)) }; } const copy = {}; for (const [k, v] of Object.entries(node)) copy[k] = rewrite(v); return copy; }; return rewrite(blocks); } function containsCite(node) { if (Array.isArray(node)) return node.some(containsCite); if (!node || typeof node !== 'object') return false; if (node.t === 'Cite') return true; return Object.values(node).some(containsCite); } /** * APA 7 düzenlemeleri: * - Tablo ve şekiller: üstte kalın "Tablo 1" / "Şekil 1", altında italik başlık. * - apa7 belgelerinde başlık sayfası, özet sayfası ve metnin başında yinelenen başlık. * - Atıf varsa yeni sayfada "Kaynaklar" bölümü. * @param front apaFrontMatter() sonucu; alanlar Pandoc blok listesine çevrilmiş olarak (fieldBlocks) */ export function applyApa(ast, { front = null, fieldBlocks = {}, hasBibliography = false } = {}) { let tables = 0; let figures = 0; const label = (word, n, captionInlines) => [ styled('APA Etiket', [para([{ t: 'Strong', c: [...str(word), { t: 'Space' }, { t: 'Str', c: String(n) }] }])]), styled('APA Etiket', [para([{ t: 'Emph', c: captionInlines }])]), ]; const mapBlocks = (blocks) => blocks.flatMap((b) => { if (b.t === 'Table') { const caption = inlinesOf(b.c[1][1]); if (!caption.length) return [b]; tables += 1; const table = { ...b, c: [b.c[0], [null, []], ...b.c.slice(2)] }; return [...label('Tablo', tables, caption), table]; } if (b.t === 'Figure') { const caption = inlinesOf(b.c[1][1]); figures += 1; return [...(caption.length ? label('Şekil', figures, caption) : []), ...mapBlocks(b.c[2])]; } if (b.t === 'Div') return [{ ...b, c: [b.c[0], mapBlocks(b.c[1])] }]; if (b.t === 'BlockQuote') return [{ ...b, c: mapBlocks(b.c) }]; return [b]; }); let blocks = mapBlocks(numberEquations(ast.blocks)); if (front) { const f = fieldBlocks; const line = (key, wrap = (x) => x) => (inlinesOf(f[key]).length ? [styled('APA Ortalı', [para(wrap(inlinesOf(f[key])))])] : []); const strong = (inl) => [{ t: 'Strong', c: inl }]; const titlePage = [ EMPTY_LINE, EMPTY_LINE, EMPTY_LINE, ...line('title', strong), EMPTY_LINE, ...line('authorsnames'), ...line('authorsaffiliations'), ...(front.student ? [...line('course'), ...line('professor'), ...line('duedate')] : []), ]; if (!front.student && f.authornote?.length) { titlePage.push(EMPTY_LINE, EMPTY_LINE, styled('APA Ortalı', [para(strong(str('Yazar Notu')))]), ...f.authornote); } const abstractPage = f.abstract?.length ? [ PAGE_BREAK, styled('APA Ortalı', [para(strong(str('Özet')))]), styled('Abstract', f.abstract), ...(inlinesOf(f.keywords).length ? [styled('Body Text', [para([{ t: 'Emph', c: str('Anahtar kelimeler:') }, { t: 'Space' }, ...inlinesOf(f.keywords)])])] : []), ] : []; const repeated = front.repeatTitle ? line('title', strong) : []; blocks = [...titlePage, ...abstractPage, PAGE_BREAK, ...repeated, ...blocks]; ast.meta = {}; // başlık bilgileri gövdeye yazıldı; Pandoc'un başlık bloğu kullanılmaz } if (hasBibliography && containsCite(blocks)) { blocks.push( PAGE_BREAK, { t: 'Header', c: [1, ['kaynaklar', ['unnumbered'], []], str('Kaynaklar')] }, { t: 'Div', c: [['refs', [], []], []] }, ); } // Ardışık sayfa sonları (ör. kaynakçadan önce \clearpage) boş sayfa oluşturmasın. const isEmpty = (b) => b.t === 'Div' && !b.c[1].length && !b.c[0][0]; blocks = blocks.filter((b) => !isEmpty(b)); blocks = blocks.filter((b, i) => !(b === PAGE_BREAK && (i === 0 || blocks[i - 1] === PAGE_BREAK))); return { ...ast, blocks }; }