mirror of
https://github.com/dolanmiu/docx.git
synced 2026-11-30 16:47:55 +01:00
feat: cite sources and list them in a bibliography, in each of Word's styles, from docx/bibliography (#557) (#3814)
* feat(bibliography): the sources part, the styles' framework, and Word's output to test against Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): citations and bibliographies, written as Word's content controls and fields Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * test(bibliography): keep the empty paragraphs in corpus s's bibliographies of GB7714 and ISO 690 The fixtures' generator left out the paragraphs of corpus s's bibliographies that have no text, though Word's styles write them: GB7714 and ISO 690 write an entry for a source with no author, title or other field as an empty paragraph, which Word keeps. Corpora a to d, Word's own output, keep empty paragraphs between entries too. Each of these fixtures gets back its 15 empty paragraphs, from the oracle, with the others as they were. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): write citations and bibliographies in GB7714, as Word does GB.XSL and ISO690.XSL share nearly every template, so the shared ones go in one family module, iso-690-family.ts, with the few that differ chosen by the variant: GB7714 cites a source with no author or year by its tag, and the two styles put the space after a website's or a report's production company by different fields. The module also reads the styles' HTML as Word's import does: spaces collapse, a space falls between two elements and at the end of a copied variable before the end of a paragraph, and a copied element with nothing in it leaves its formatting on for the rest of the bibliography. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): write citations and bibliographies in ISO 690 by first element and date, as Word does ISO690.XSL is GB.XSL's twin, so the style is the ISO 690 variant of the family module: a source with a title but no author or year is cited by nothing, "()", where GB7714 cites it by its tag. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): write citations and bibliographies in ISO 690 by numerical reference, as Word does ISO690Nmerical.XSL cites a source by its number, with the pages or volume cited after it, such as "(1 p. 5)", and lists the sources in the order the document cites them. Its entries are the ISO 690 family's, with the main contributors after the start of a journal article or conference paper. The style copies each entry from a variable, so Word reads an entry whose bold has nothing in it, such as one with no author, as bold that stays on for the rest of the bibliography. An empty xsl:value-of in an element ends it as usual, so a miscellaneous source with no publication doesn't leave italics on, as Word's own bibliography of such a source shows; libxslt's output differs from Word's there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * chore(bibliography): spell the styles' names and Word's abbreviations Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * test(bibliography): keep the empty entries of corpus s in the GOST and SIST02 fixtures Word writes an empty paragraph for a source whose entry is empty in a style, such as a miscellaneous source with no fields in GOST, as Word's style writes an empty <p> for it. gen-fixtures.mjs dropped every empty paragraph of corpus s, so the fixtures had fewer entries than the bibliography. They're rewritten from the oracle with them, and gen-fixtures.mjs needs the same change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): write citations and bibliographies in GOST, as Word does Ports Word's GOST - Name Sort (GostName.XSL) and GOST - Title Sort (GostTitle.XSL). They share everything but how an entry starts, how the bibliography is sorted, and a few templates, so both are written from one module, gost-family.ts: Name Sort starts an entry with its authors in bold and leaves the people who are those authors out of the rest; Title Sort starts it with its title in bold, sorts by title, then the main author's names, counts an organization as a book section's author, and writes an interview's responsibilities only when one of the first three isn't empty. The ports follow the templates where they do what they don't look like they do: _MaxAuthor is read without a $, so every author is listed up to three; a role is written only when one of its people has a last name; a location with neither a city nor a publisher is the source's distributor; and an entry of nothing but spaces is left empty, with no dot. Their output matches Word's for corpora a to d and the oracle's for corpus s, and the oracle's for 8 seeds of 300 random sources each. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * test(bibliography): end SIST02's corpus s entries without a space, as Word does Word's SIST02 style, run with libxslt, ends an entry that ends with a bold or italic element with a line break, which the oracle reads as a space. Word for Mac shows none: corpus b has "<b>MoraLuz</b> <i>Bread.</i>" and "<i>Untitled Notes.</i>", with nothing after them. Corpus s's expected bibliography is regenerated with the oracle reading no space at the end of a SIST02 paragraph, which changes 14 entries such as "<b>—.</b> ". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): write citations and bibliographies in SIST02, as Word does Word's SIST02 style (SIST02.XSL), with its own full-width punctuation and empty spaces, its name patterns, and Word's reading of its HTML: a space between two bold or italic elements that follow each other, even an empty one, and none at the end of an entry. Its quirks are kept, such as "ed." after any number of editors, "Vol. 5..", "[Cited: ]" for a date accessed with only a day, and "—." for an article whose title is the one before's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * test(bibliography): keep the empty paragraphs of corpus s's APA bibliography Word's APA style writes a paragraph for each source, empty for a source it has nothing to write for, such as a case with no title, number, court or date. The fixtures' generator left out empty paragraphs, so corpus s's expected bibliography was two entries short of what the style writes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): write citations and bibliographies in APA, as Word does Word's APASixthEditionOfficeOnline.xsl, written in TypeScript: citations such as "(Baker, 2010)", with the title when another source has the same first author and initials when another first author has the same last name, and the bibliography sorted by author, with a hanging indent. It follows the XSL, including its quirks: the editors of a conference's proceedings are always "Ed.", a work of art's date has no space after it without an artist, and Word reads a space after an entry that ends in italics, where MSXML writes a line break at the end of the copy of the entry. Its citations and bibliographies are Word's for every source of the four corpora Word wrote, and Word's XSL's for corpus s and for random sources. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): write citations and bibliographies in Harvard - Anglia, as Word does Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): write citations and bibliographies in Chicago, as Word does Ported from Word's CHICAGO.XSL, template by template, including its quirks: a space after an entry that ends with a title in italics, as Word's XSLT writes a line break there, "eds." left out after a list of editors, as Word's English has none, and no space before "Edited by" after the title of an interview. Tested against Word's own output for the probes' corpora, and against Word's XSL for the synthetic corpus and the branches neither reaches. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * test(bibliography): keep the empty paragraph Turabian writes for an artwork with nothing to write Corpus s's fixture left out the paragraph Word writes for an artwork with no artist, title, institution, city or publication title, which Turabian writes as an empty paragraph. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): write citations and bibliographies in Turabian, as Word does Turabian's citations are Chicago's, and it finds a source's authors and sorts its bibliography as Chicago does, so it shares those with Chicago, from chicago-family.ts. Its entries end with where and when the source was published. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): write citations and bibliographies in IEEE, as Word does Written from Word's IEEE2006OfficeOnline.xsl: citations such as "[1, p. 50]", and a bibliography that is a table of each source's number and entry, in the order the sources are cited. Its people are written with the style's own templates for initials, and some of its words are English written into the style, such as "Available:". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * test(bibliography): keep the empty paragraph MLA writes for an artwork with nothing to write Corpus s's MLA fixture left out the empty paragraph Word writes for the work of art with none of its fields, as its generator dropped empty paragraphs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): write citations and bibliographies in MLA, as Word does MLA, seventh edition, written from Word's MLASeventhEditionOfficeOnline.xsl: citations such as "(Baker 50)", with the title when the authors don't tell a source apart, and a bibliography sorted by the people each source is named by, with "—" for the same people as the entry before. It writes what Word's style writes, including where that isn't what MLA asks for: editors named first with no "eds." after several of them, an organization as a performer with no "Perf." before it, an interview's title without its italics when its interviewer follows, no space between a sound recording's album and its producer when it has neither composers nor a title, and a space after an entry that ends with italics, as Word reads it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * fix(bibliography): name the style as Word for Mac finds it, and write bibliographies' paragraphs as Word does Word for Mac only finds a style named with a slash before its file, and opens a document with a backslash in APA. A bibliography of no sources is Word's bold "Invalid source specified.", and IEEE's table has an empty paragraph after it, as Word writes them when it updates the fields. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat(bibliography): docx/bibliography, with sources, citations and bibliographies in each of Word's styles (#557) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * fix(bibliography): reject a style named after a property every object has createBibliography looked the style up in an ordinary object, so a name such as "toString" or "__proto__" found an inherited value, got past the check and failed later, when the document was packed. It now checks the style is one of the definitions' own keys, and throws the documented error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * fix(bibliography): throw for a source whose type isn't one of SourceType's A source with an unknown type, such as Word's own name "InternetSite" for SourceType.WEBSITE, was kept with no type and failed later in a style, with a TypeError. wordSourceOf now throws when the source is given, saying which source and type. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -22,6 +22,7 @@
|
||||
"chosung",
|
||||
"clippy",
|
||||
"coordsize",
|
||||
"Countinous",
|
||||
"datas",
|
||||
"DCMI",
|
||||
"DIFAT",
|
||||
@@ -33,15 +34,18 @@
|
||||
"execa",
|
||||
"falsey",
|
||||
"fillok",
|
||||
"GOST",
|
||||
"gradientshapeok",
|
||||
"horz",
|
||||
"iife",
|
||||
"Initializable",
|
||||
"iroha",
|
||||
"ISSN",
|
||||
"JOHAB",
|
||||
"kinsoku",
|
||||
"jsonify",
|
||||
"jszip",
|
||||
"nomine",
|
||||
"NUMPAGES",
|
||||
"odttf",
|
||||
"OLEDS",
|
||||
@@ -56,8 +60,10 @@
|
||||
"rsid",
|
||||
"sdtdh",
|
||||
"shadowok",
|
||||
"SIST",
|
||||
"strokeok",
|
||||
"textpathok",
|
||||
"Turabian",
|
||||
"twip",
|
||||
"twips",
|
||||
"ungrouping",
|
||||
|
||||
@@ -156,6 +156,42 @@ const doc = new Document({
|
||||
|
||||
In a page without a bundler, load `dist/embedded-files.umd.cjs` after `dist/index.umd.cjs`. It adds the `docxEmbeddedFiles` global. See the [embedded files](https://docx.js.org/#/usage/embedded-files) documentation.
|
||||
|
||||
# Citations and Bibliography
|
||||
|
||||
Sources, citations of them in the text and a bibliography, in one of Word's styles of citation, such as APA, MLA or Chicago, written as Word writes them, with `docx/bibliography`:
|
||||
|
||||
```ts
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
import { Bibliography, Citation, CitationStyle, SourceType, createBibliography } from "docx/bibliography";
|
||||
|
||||
const doc = new Document({
|
||||
bibliography: createBibliography({
|
||||
style: CitationStyle.APA,
|
||||
sources: [
|
||||
{
|
||||
tag: "Bak10",
|
||||
type: SourceType.BOOK,
|
||||
authors: [{ lastName: "Baker", firstName: "Anna" }],
|
||||
title: "The Art of Pizza",
|
||||
year: 2010,
|
||||
city: "Naples",
|
||||
publisher: "Oven Press",
|
||||
},
|
||||
],
|
||||
}),
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({ children: [new TextRun("Pizza has been baked in Naples for centuries "), new Citation("Bak10")] }),
|
||||
new Bibliography({ title: "References" }),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
In a page without a bundler, load `dist/bibliography.umd.cjs` after `dist/index.umd.cjs`. It adds the `docxBibliography` global. See the [citations and bibliography](https://docx.js.org/#/usage/bibliography) documentation.
|
||||
|
||||
# Playground
|
||||
|
||||
Experience `docx` in action through [Docx.js Editor][docxjs-editor-url], an interactive playground where you can code and preview the results in real-time.
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// Sources of several kinds, citations of them in the text, and a bibliography, in APA, as Word's References > Citations & Bibliography writes them
|
||||
// See docs/usage/bibliography.md for full documentation.
|
||||
|
||||
import * as fs from "fs";
|
||||
import { Document, HeadingLevel, Packer, Paragraph, TextRun } from "docx";
|
||||
import { Bibliography, Citation, CitationStyle, SourceType, createBibliography } from "docx/bibliography";
|
||||
|
||||
const doc = new Document({
|
||||
bibliography: createBibliography({
|
||||
style: CitationStyle.APA,
|
||||
sources: [
|
||||
{
|
||||
tag: "Bak10",
|
||||
type: SourceType.BOOK,
|
||||
authors: [{ lastName: "Baker", firstName: "Anna" }],
|
||||
title: "The Art of Pizza",
|
||||
year: 2010,
|
||||
city: "Naples",
|
||||
publisher: "Oven Press",
|
||||
},
|
||||
{
|
||||
tag: "Lee18",
|
||||
type: SourceType.JOURNAL_ARTICLE,
|
||||
authors: [
|
||||
{ lastName: "Lee", firstName: "Daniel" },
|
||||
{ lastName: "Kim", firstName: "Sora" },
|
||||
],
|
||||
title: "Crust Hydration and Bake Time",
|
||||
journalName: "Journal of Baking Science",
|
||||
year: 2018,
|
||||
volume: 12,
|
||||
issue: 4,
|
||||
pages: "233-250",
|
||||
},
|
||||
{
|
||||
tag: "Hug21",
|
||||
type: SourceType.WEBSITE,
|
||||
authors: [{ lastName: "Hughes", firstName: "Leo" }],
|
||||
title: "Stretching Dough by Hand",
|
||||
websiteName: "Pizza School",
|
||||
year: 2021,
|
||||
month: "January",
|
||||
day: 9,
|
||||
yearAccessed: 2022,
|
||||
monthAccessed: "February",
|
||||
dayAccessed: 3,
|
||||
url: "https://example.com/stretching",
|
||||
},
|
||||
{
|
||||
tag: "WPA16",
|
||||
type: SourceType.REPORT,
|
||||
corporateAuthor: "World Pizza Association",
|
||||
title: "Pizza Standards",
|
||||
year: 2016,
|
||||
city: "Rome",
|
||||
publisher: "WPA Press",
|
||||
},
|
||||
],
|
||||
}),
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({ text: "Pizza report", heading: HeadingLevel.HEADING_1 }),
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Pizza has been baked in Naples for centuries "),
|
||||
new Citation("Bak10"),
|
||||
new TextRun(". Wetter dough bakes faster "),
|
||||
new Citation({ source: "Lee18", pages: "240" }),
|
||||
new TextRun(", and is easier to stretch by hand "),
|
||||
new Citation("Hug21"),
|
||||
new TextRun("."),
|
||||
],
|
||||
}),
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("A margherita has tomato, mozzarella and basil "),
|
||||
new Citation(["WPA16", { source: "Bak10", pages: "12-14" }]),
|
||||
new TextRun("."),
|
||||
],
|
||||
}),
|
||||
new Bibliography({ title: "References" }),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Packer.toBuffer(doc).then((buffer) => {
|
||||
fs.writeFileSync("My Document.docx", buffer);
|
||||
});
|
||||
@@ -49,6 +49,7 @@
|
||||
- [Hyperlinks](usage/hyperlinks.md)
|
||||
- [Bookmarks](usage/bookmarks.md)
|
||||
- [Captions and Cross-references](usage/captions.md)
|
||||
- [Citations and Bibliography](usage/bibliography.md)
|
||||
- [Checkboxes](usage/checkboxes.md)
|
||||
- [Text Box](usage/text-box.md)
|
||||
- [WPS Text Box](usage/wps-text-box.md)
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
"docx/html": { file: "html", global: "docxHtml", after: ["docx/math"] },
|
||||
"docx/macros": { file: "macros", global: "docxMacros" },
|
||||
"docx/embedded-files": { file: "embedded-files", global: "docxEmbeddedFiles" },
|
||||
"docx/bibliography": { file: "bibliography", global: "docxBibliography" },
|
||||
};
|
||||
|
||||
// Packages from npm an example can import too, from jsDelivr at the version the docs are written for: where each is, and
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
# Citations and Bibliography
|
||||
|
||||
<!-- cspell:ignore Mabe Müller -->
|
||||
|
||||
A document can cite its sources, such as books, articles and websites, in its text, such as "(Baker, 2010)", and list them in a bibliography, in one of Word's styles of citation, such as APA, MLA or Chicago. Word does this with **References > Citations & Bibliography**, and `docx` writes the same: each citation and bibliography is written as Word writes it, in the style the document's sources are given. Word writes them again when it updates the document's fields, or when the style is changed in **References > Style**, and lists the sources in its **Source Manager**.
|
||||
|
||||
Citations and bibliographies come with the `docx` package, from `docx/bibliography`. The sources go in the document's `bibliography`:
|
||||
|
||||
```ts
|
||||
import { Document, Packer, Paragraph, TextRun } from "docx";
|
||||
import { Bibliography, Citation, CitationStyle, SourceType, createBibliography } from "docx/bibliography";
|
||||
```
|
||||
|
||||
In a page without a bundler, load `dist/bibliography.umd.cjs` after `dist/index.umd.cjs` (or `dist/bibliography.iife.js` after `dist/index.iife.js`). It adds a `docxBibliography` global, such as `docxBibliography.createBibliography({ ... })`.
|
||||
|
||||
## Example
|
||||
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
import { Bibliography, Citation, CitationStyle, SourceType, createBibliography } from "docx/bibliography";
|
||||
|
||||
const doc = new Document({
|
||||
bibliography: createBibliography({
|
||||
style: CitationStyle.APA,
|
||||
sources: [
|
||||
{
|
||||
tag: "Bak10",
|
||||
type: SourceType.BOOK,
|
||||
authors: [{ lastName: "Baker", firstName: "Anna" }],
|
||||
title: "The Art of Pizza",
|
||||
year: 2010,
|
||||
city: "Naples",
|
||||
publisher: "Oven Press",
|
||||
},
|
||||
{
|
||||
tag: "Lee18",
|
||||
type: SourceType.JOURNAL_ARTICLE,
|
||||
authors: [
|
||||
{ lastName: "Lee", firstName: "Daniel" },
|
||||
{ lastName: "Kim", firstName: "Sora" },
|
||||
],
|
||||
title: "Crust Hydration and Bake Time",
|
||||
journalName: "Journal of Baking Science",
|
||||
year: 2018,
|
||||
volume: 12,
|
||||
issue: 4,
|
||||
pages: "233-250",
|
||||
},
|
||||
],
|
||||
}),
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Pizza has been baked in Naples for centuries "),
|
||||
new Citation("Bak10"),
|
||||
new TextRun(", and wetter dough bakes faster "),
|
||||
new Citation({ source: "Lee18", pages: "240" }),
|
||||
new TextRun("."),
|
||||
],
|
||||
}),
|
||||
new Bibliography({ title: "References" }),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Sources
|
||||
|
||||
`createBibliography` takes the document's sources, and the style its citations and bibliographies are written in, which is APA, Word's default, if it isn't given:
|
||||
|
||||
| Property | Type | Notes | Description |
|
||||
| --------- | --------------- | -------- | ----------------------------------------------------------------------------- |
|
||||
| `sources` | `Source[]` | Required | The sources, such as books and websites |
|
||||
| `style` | `CitationStyle` | Optional | The style of the citations and bibliographies, `CitationStyle.APA` if not set |
|
||||
|
||||
Each source has a `tag`, which citations refer to it by and Word calls its tag name, such as "Bak10", and a `type`, one of the kinds of source Word's **Create Source** dialog has:
|
||||
|
||||
| `SourceType` | Word's type | Its main fields |
|
||||
| ------------------------- | ----------------------- | ------------------------------------------------------------------------------------ |
|
||||
| `BOOK` | Book | `authors`, `title`, `year`, `city`, `publisher`, `edition`, `volume`, `editors` |
|
||||
| `BOOK_SECTION` | Book Section | `authors`, `title`, `bookTitle`, `bookAuthors`, `pages`, `year`, `city`, `publisher` |
|
||||
| `JOURNAL_ARTICLE` | Journal Article | `authors`, `title`, `journalName`, `year`, `volume`, `issue`, `pages` |
|
||||
| `ARTICLE_IN_A_PERIODICAL` | Article in a Periodical | `authors`, `title`, `periodicalTitle`, `year`, `month`, `day`, `pages` |
|
||||
| `CONFERENCE_PROCEEDINGS` | Conference Proceedings | `authors`, `title`, `conferenceName`, `year`, `city`, `publisher`, `pages` |
|
||||
| `REPORT` | Report | `authors`, `title`, `institution`, `reportType`, `year`, `city`, `publisher` |
|
||||
| `WEBSITE` | Web site | `authors`, `title`, `websiteName`, `url`, `year`, `month`, `day`, `yearAccessed` |
|
||||
| `DOCUMENT_FROM_WEBSITE` | Document From Web site | `authors`, `title`, `websiteName`, `url`, `year`, `yearAccessed` |
|
||||
| `ELECTRONIC_SOURCE` | Electronic Source | `authors`, `title`, `publicationTitle`, `medium`, `year`, `publisher` |
|
||||
| `ART` | Art | `artists`, `title`, `institution`, `year`, `city` |
|
||||
| `SOUND_RECORDING` | Sound Recording | `composers`, `performers`, `title`, `albumTitle`, `year`, `productionCompany` |
|
||||
| `PERFORMANCE` | Performance | `writers`, `directors`, `performers`, `title`, `theater`, `year`, `city` |
|
||||
| `FILM` | Film | `directors`, `writers`, `producers`, `title`, `year`, `distributor`, `medium` |
|
||||
| `INTERVIEW` | Interview | `interviewees`, `interviewers`, `title`, `broadcastTitle`, `year`, `broadcaster` |
|
||||
| `PATENT` | Patent | `inventors`, `title`, `patentNumber`, `countryOrRegion`, `year` |
|
||||
| `CASE` | Case | `title`, `caseNumber`, `court`, `reporter`, `year` |
|
||||
| `MISCELLANEOUS` | Miscellaneous | `authors`, `title`, `publicationTitle`, `year`, `city`, `publisher` |
|
||||
|
||||
Any source can have any field, as in Word, and each style writes the fields it has for the type of source. A person, such as an author, has a `lastName`, and can have a `firstName` and a `middleName`. Styles that write initials write them from the first letter of each name, such as "J.-P." for "Jean-Paul". A source written by an organization has a `corporateAuthor` in place of its `authors`:
|
||||
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { Bibliography, Citation, SourceType, createBibliography } from "docx/bibliography";
|
||||
|
||||
const doc = new Document({
|
||||
bibliography: createBibliography({
|
||||
sources: [
|
||||
{
|
||||
tag: "WPA16",
|
||||
type: SourceType.REPORT,
|
||||
corporateAuthor: "World Pizza Association",
|
||||
title: "Pizza Standards",
|
||||
year: 2016,
|
||||
city: "Rome",
|
||||
publisher: "WPA Press",
|
||||
},
|
||||
{
|
||||
tag: "Hug21",
|
||||
type: SourceType.WEBSITE,
|
||||
authors: [{ lastName: "Hughes", firstName: "Leo" }],
|
||||
title: "Stretching Dough by Hand",
|
||||
websiteName: "Pizza School",
|
||||
url: "https://example.com/stretching",
|
||||
year: 2021,
|
||||
month: "January",
|
||||
day: 9,
|
||||
yearAccessed: 2022,
|
||||
monthAccessed: "February",
|
||||
dayAccessed: 3,
|
||||
},
|
||||
],
|
||||
}),
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({ children: [new Citation("WPA16")] }),
|
||||
new Paragraph({ children: [new Citation("Hug21")] }),
|
||||
new Bibliography(),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Each field is text as Word keeps it, and is written as it's given, so give a month as "March" rather than "3", pages as "50-62", and an edition as "2nd". A year, a day, a volume and an issue can be numbers.
|
||||
|
||||
## Citations
|
||||
|
||||
A `Citation` cites a source by its tag. It goes in a paragraph, as a run does:
|
||||
|
||||
| Property | Type | Notes | Description |
|
||||
| ------------ | --------- | -------- | ---------------------------------------------------------------------------- |
|
||||
| `source` | `string` | Required | The tag of the source cited |
|
||||
| `pages` | `string` | Optional | The pages cited, such as "50" or "50-62", which most styles write as "p. 50" |
|
||||
| `volume` | `string` | Optional | The volume cited |
|
||||
| `prefix` | `string` | Optional | Text before the source, such as "see " |
|
||||
| `suffix` | `string` | Optional | Text after the source, such as ", emphasis added" |
|
||||
| `hideAuthor` | `boolean` | Optional | Leaves out the authors, such as when they're named in the text |
|
||||
| `hideYear` | `boolean` | Optional | Leaves out the year |
|
||||
| `hideTitle` | `boolean` | Optional | Leaves out the title, in the styles that write one |
|
||||
|
||||
A citation can cite several sources together, such as "(Baker, 2010; Lee & Kim, 2018)":
|
||||
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
import { Citation, SourceType, createBibliography } from "docx/bibliography";
|
||||
|
||||
const doc = new Document({
|
||||
bibliography: createBibliography({
|
||||
sources: [
|
||||
{
|
||||
tag: "Bak10",
|
||||
type: SourceType.BOOK,
|
||||
authors: [{ lastName: "Baker", firstName: "Anna" }],
|
||||
title: "The Art of Pizza",
|
||||
year: 2010,
|
||||
},
|
||||
{
|
||||
tag: "Lee18",
|
||||
type: SourceType.JOURNAL_ARTICLE,
|
||||
authors: [
|
||||
{ lastName: "Lee", firstName: "Daniel" },
|
||||
{ lastName: "Kim", firstName: "Sora" },
|
||||
],
|
||||
title: "Crust Hydration and Bake Time",
|
||||
journalName: "Journal of Baking Science",
|
||||
year: 2018,
|
||||
},
|
||||
],
|
||||
}),
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({ children: [new TextRun("A tag: "), new Citation("Bak10")] }),
|
||||
new Paragraph({ children: [new TextRun("Pages: "), new Citation({ source: "Bak10", pages: "12-14" })] }),
|
||||
new Paragraph({ children: [new TextRun("Before it: "), new Citation({ source: "Bak10", prefix: "see " })] }),
|
||||
new Paragraph({ children: [new TextRun("As Baker writes "), new Citation({ source: "Bak10", hideAuthor: true })] }),
|
||||
new Paragraph({ children: [new TextRun("Two sources: "), new Citation(["Bak10", { source: "Lee18", pages: "240" }])] }),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
When two sources have the same first author, styles such as APA add the title to tell them apart, and when the first authors of two sources have the same last name, they add the initials, as Word does.
|
||||
|
||||
## Bibliography
|
||||
|
||||
A `Bibliography` lists every source of the document's bibliography, cited or not, sorted as the style sorts them. Give it a `title` for a heading above it, in the Heading 1 style, as Word's built-in **Bibliography**, **References** and **Works Cited** bibliographies have:
|
||||
|
||||
| Property | Type | Notes | Description |
|
||||
| -------- | -------- | -------- | --------------------------------------------------------------- |
|
||||
| `title` | `string` | Optional | A heading above the list, such as "References" or "Works Cited" |
|
||||
|
||||
Its paragraphs are in the Bibliography style, which has no formatting of its own, as in Word. Give `bibliography` in the default styles to change it:
|
||||
|
||||
```ts live
|
||||
import { Document } from "docx";
|
||||
import { Bibliography, SourceType, createBibliography } from "docx/bibliography";
|
||||
|
||||
const doc = new Document({
|
||||
styles: { default: { bibliography: { run: { size: 20, color: "444444" } } } },
|
||||
bibliography: createBibliography({
|
||||
sources: [
|
||||
{
|
||||
tag: "Bak10",
|
||||
type: SourceType.BOOK,
|
||||
authors: [{ lastName: "Baker", firstName: "Anna" }],
|
||||
title: "The Art of Pizza",
|
||||
year: 2010,
|
||||
city: "Naples",
|
||||
publisher: "Oven Press",
|
||||
},
|
||||
],
|
||||
}),
|
||||
sections: [{ children: [new Bibliography({ title: "Works Cited" })] }],
|
||||
});
|
||||
```
|
||||
|
||||
## Styles
|
||||
|
||||
`CitationStyle` has each of Word's styles, by the name Word lists it by, and its edition:
|
||||
|
||||
| `CitationStyle` | Word's style | Edition | A citation |
|
||||
| -------------------------------- | -------------------------------- | ------- | --------------- |
|
||||
| `APA` | APA | 6th | (Baker, 2010) |
|
||||
| `CHICAGO` | Chicago | 16th | (Baker 2010) |
|
||||
| `GB7714` | GB7714 | 2005 | (Baker, 2010) |
|
||||
| `GOST_NAME_SORT` | GOST - Name Sort | 2003 | (Baker, 2010) |
|
||||
| `GOST_TITLE_SORT` | GOST - Title Sort | 2003 | (Baker, 2010) |
|
||||
| `HARVARD_ANGLIA` | Harvard - Anglia | 2008 | (Baker, 2010) |
|
||||
| `IEEE` | IEEE | 2006 | [1] |
|
||||
| `ISO_690_FIRST_ELEMENT_AND_DATE` | ISO 690 - First Element and Date | 1987 | (Baker, 2010) |
|
||||
| `ISO_690_NUMERICAL_REFERENCE` | ISO 690 - Numerical Reference | 1987 | (1) |
|
||||
| `MLA` | MLA | 7th | (Baker) |
|
||||
| `SIST02` | SIST02 | 2003 | (Baker,2010) |
|
||||
| `TURABIAN` | Turabian | 6th | (Baker 2010) |
|
||||
|
||||
IEEE and ISO 690's numerical style number the sources in the order they're first cited, and IEEE writes its bibliography as a table of the numbers and the sources:
|
||||
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
import { Bibliography, Citation, CitationStyle, SourceType, createBibliography } from "docx/bibliography";
|
||||
|
||||
const doc = new Document({
|
||||
bibliography: createBibliography({
|
||||
style: CitationStyle.IEEE,
|
||||
sources: [
|
||||
{
|
||||
tag: "Bak10",
|
||||
type: SourceType.BOOK,
|
||||
authors: [{ lastName: "Baker", firstName: "Anna" }],
|
||||
title: "The Art of Pizza",
|
||||
year: 2010,
|
||||
city: "Naples",
|
||||
publisher: "Oven Press",
|
||||
},
|
||||
{
|
||||
tag: "Lee18",
|
||||
type: SourceType.JOURNAL_ARTICLE,
|
||||
authors: [
|
||||
{ lastName: "Lee", firstName: "Daniel" },
|
||||
{ lastName: "Kim", firstName: "Sora" },
|
||||
],
|
||||
title: "Crust Hydration and Bake Time",
|
||||
journalName: "Journal of Baking Science",
|
||||
year: 2018,
|
||||
volume: 12,
|
||||
issue: 4,
|
||||
pages: "233-250",
|
||||
},
|
||||
],
|
||||
}),
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Wetter dough bakes faster "),
|
||||
new Citation("Lee18"),
|
||||
new TextRun(", as it always has "),
|
||||
new Citation("Bak10"),
|
||||
new TextRun("."),
|
||||
],
|
||||
}),
|
||||
new Bibliography({ title: "References" }),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Each style is written from Word's own, with Word's English wording, so a citation or a bibliography is the same before and after Word updates it. The one difference is the order of names with accents: Word for Mac sorts some of them in an order of its own, such as "Müller" before "Mabe", and `docx` sorts a letter with an accent as the letter, so Word for Mac may put such names in another order when it updates the bibliography.
|
||||
|
||||
## Demo
|
||||
|
||||
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/bibliography/citations-and-bibliography.ts ":include")
|
||||
|
||||
_Source: https://github.com/dolanmiu/docx/blob/master/demo/bibliography/citations-and-bibliography.ts_
|
||||
@@ -1,6 +1,6 @@
|
||||
# Captions and Cross-references
|
||||
|
||||
A caption labels and numbers a table, a picture or an equation, such as "Table 1: Results". A cross-reference refers to it from elsewhere in the text, as Word's **References > Insert Caption** and **Insert Cross-reference** do.
|
||||
A caption labels and numbers a table, a picture or an equation, such as "Table 1: Results". A cross-reference refers to it from elsewhere in the text, as Word's **References > Insert Caption** and **Insert Cross-reference** do. To cite books, articles and other sources, and list them in a bibliography, see [Citations and Bibliography](usage/bibliography.md).
|
||||
|
||||
## Captions
|
||||
|
||||
|
||||
+14
-3
@@ -399,7 +399,8 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
// src/file/paragraph/math. src/text-layout measures text for docx/shapes and docx/layout, and each bundles a copy.
|
||||
// docx/html (src/html) imports docx/math by name too, for the math in HTML. docx/macros (src/macros) writes VBA
|
||||
// projects for docx's macros, and docx/embedded-files (src/embedded-files) embeds files as OLE objects.
|
||||
// src/compound-file writes the compound files both keep them in, and each bundles a copy
|
||||
// src/compound-file writes the compound files both keep them in, and each bundles a copy. docx/bibliography
|
||||
// (src/bibliography) writes citations and bibliographies. Spec helpers (src/tests) may import the entries, as specs do
|
||||
{
|
||||
files: ["src/**/*.ts"],
|
||||
ignores: [
|
||||
@@ -413,6 +414,8 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
"src/embedded-files/**",
|
||||
"src/compound-file/**",
|
||||
"src/text-layout/**",
|
||||
"src/bibliography/**",
|
||||
"src/tests/**",
|
||||
"**/*.spec.ts",
|
||||
],
|
||||
rules: {
|
||||
@@ -423,7 +426,7 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
patterns: [
|
||||
{ group: ["docx/*"], message: "docx doesn't import its optional entries, such as docx/shapes" },
|
||||
{
|
||||
regex: "(^|/)(shapes|watermarks|charts|layout|html|macros|embedded-files|compound-file|text-layout)(/|$)",
|
||||
regex: "(^|/)(shapes|watermarks|charts|layout|html|macros|embedded-files|compound-file|text-layout|bibliography)(/|$)",
|
||||
message: "docx doesn't import its optional entries, such as docx/shapes",
|
||||
},
|
||||
],
|
||||
@@ -443,6 +446,7 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
"src/embedded-files/*.ts",
|
||||
"src/compound-file/*.ts",
|
||||
"src/text-layout/*.ts",
|
||||
"src/bibliography/*.ts",
|
||||
],
|
||||
ignores: ["**/*.spec.ts"],
|
||||
rules: {
|
||||
@@ -461,7 +465,14 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["src/shapes/*/*.ts", "src/watermarks/*/*.ts", "src/charts/*/*.ts", "src/layout/*/*.ts", "src/html/*/*.ts"],
|
||||
files: [
|
||||
"src/shapes/*/*.ts",
|
||||
"src/watermarks/*/*.ts",
|
||||
"src/charts/*/*.ts",
|
||||
"src/layout/*/*.ts",
|
||||
"src/html/*/*.ts",
|
||||
"src/bibliography/*/*.ts",
|
||||
],
|
||||
ignores: ["**/*.spec.ts"],
|
||||
rules: {
|
||||
"no-restricted-imports": [
|
||||
|
||||
+15
-2
@@ -96,6 +96,16 @@
|
||||
"types": "./dist/embedded-files.d.cts",
|
||||
"default": "./dist/embedded-files.cjs"
|
||||
}
|
||||
},
|
||||
"./bibliography": {
|
||||
"import": {
|
||||
"types": "./dist/bibliography.d.ts",
|
||||
"default": "./dist/bibliography.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/bibliography.d.cts",
|
||||
"default": "./dist/bibliography.cjs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"typesVersions": {
|
||||
@@ -123,6 +133,9 @@
|
||||
],
|
||||
"embedded-files": [
|
||||
"./dist/embedded-files.d.ts"
|
||||
],
|
||||
"bibliography": [
|
||||
"./dist/bibliography.d.ts"
|
||||
]
|
||||
}
|
||||
},
|
||||
@@ -130,14 +143,14 @@
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc && vite build && vite build --config vite.entries.config.ts --mode shapes && vite build --config vite.entries.config.ts --mode watermarks && vite build --config vite.entries.config.ts --mode charts && vite build --config vite.entries.config.ts --mode math && vite build --config vite.entries.config.ts --mode layout && vite build --config vite.entries.config.ts --mode html && vite build --config vite.entries.config.ts --mode macros && vite build --config vite.entries.config.ts --mode embedded-files",
|
||||
"build": "tsc && vite build && vite build --config vite.entries.config.ts --mode shapes && vite build --config vite.entries.config.ts --mode watermarks && vite build --config vite.entries.config.ts --mode charts && vite build --config vite.entries.config.ts --mode math && vite build --config vite.entries.config.ts --mode layout && vite build --config vite.entries.config.ts --mode html && vite build --config vite.entries.config.ts --mode macros && vite build --config vite.entries.config.ts --mode embedded-files && vite build --config vite.entries.config.ts --mode bibliography",
|
||||
"test": "vitest --ui --coverage",
|
||||
"test:ci": "vitest run --coverage",
|
||||
"prepublishOnly": "npm run build --omit=dev",
|
||||
"lint": "eslint --config eslint.config.ts",
|
||||
"predemo": "npm run build",
|
||||
"demo": "tsx ./demo/index.ts",
|
||||
"typedoc": "typedoc src/index.ts src/shapes/index.ts src/watermarks/index.ts src/charts/index.ts src/math/index.ts src/layout/index.ts src/html/index.ts src/macros/index.ts src/embedded-files/index.ts --tsconfig tsconfig.typedoc.json",
|
||||
"typedoc": "typedoc src/index.ts src/shapes/index.ts src/watermarks/index.ts src/charts/index.ts src/math/index.ts src/layout/index.ts src/html/index.ts src/macros/index.ts src/embedded-files/index.ts src/bibliography/index.ts --tsconfig tsconfig.typedoc.json",
|
||||
"prettier": "prettier -l \"{src,scripts,demo,docs}/**/*.{ts,html,md}\"",
|
||||
"prettier:fix": "npm run prettier -- --write",
|
||||
"cspell": "cspell \"{src,demo,docs,scripts}/**/*.{ts,scss,html,md}\" && cspell \"./*.*\"",
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { Document, FileChild } from "docx";
|
||||
import { testStyle, xmlOf } from "tests/bibliography";
|
||||
|
||||
import { Bibliography } from "./bibliography";
|
||||
import { BibliographySources } from "./document-sources";
|
||||
import type { Source } from "./source";
|
||||
import type { StyleDefinition } from "./styles/style";
|
||||
|
||||
const SOURCES: readonly Source[] = [
|
||||
{ tag: "B", type: "book", title: "Two" },
|
||||
{ tag: "A", type: "book", title: "One" },
|
||||
];
|
||||
|
||||
const documentWith = (sources: readonly Source[], style: StyleDefinition = testStyle()): Document =>
|
||||
new Document({ bibliography: { sources: new BibliographySources(style, sources) }, sections: [] });
|
||||
|
||||
const FIELD_START =
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> BIBLIOGRAPHY </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>';
|
||||
|
||||
const FIELD_END = '<w:p><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>';
|
||||
|
||||
const PARAGRAPH = '<w:pPr><w:pStyle w:val="Bibliography"/><w:ind w:left="720" w:hanging="720"/><w:rPr><w:noProof/></w:rPr></w:pPr>';
|
||||
|
||||
describe("Bibliography", () => {
|
||||
it("is a block, so a section takes it", () => {
|
||||
expect(new Bibliography()).to.be.instanceOf(FileChild);
|
||||
});
|
||||
|
||||
it("is written as Word's bibliography content control, with a BIBLIOGRAPHY field whose result is each source in the document's style", () => {
|
||||
expect(xmlOf(new Bibliography(), documentWith(SOURCES))).to.equal(
|
||||
"<w:sdt><w:sdtPr><w:bibliography/></w:sdtPr><w:sdtContent>" +
|
||||
`<w:p>${PARAGRAPH}${FIELD_START}<w:r><w:rPr><w:noProof/></w:rPr><w:t xml:space="preserve">A </w:t></w:r>` +
|
||||
'<w:r><w:rPr><w:i/><w:iCs/><w:noProof/></w:rPr><w:t xml:space="preserve">One</w:t></w:r><w:r><w:rPr><w:noProof/></w:rPr><w:t xml:space="preserve"> </w:t></w:r></w:p>' +
|
||||
`<w:p>${PARAGRAPH}<w:r><w:rPr><w:noProof/></w:rPr><w:t xml:space="preserve">B </w:t></w:r>` +
|
||||
'<w:r><w:rPr><w:i/><w:iCs/><w:noProof/></w:rPr><w:t xml:space="preserve">Two</w:t></w:r><w:r><w:rPr><w:noProof/></w:rPr><w:t xml:space="preserve"> </w:t></w:r></w:p>' +
|
||||
`${FIELD_END}</w:sdtContent></w:sdt>`,
|
||||
);
|
||||
});
|
||||
|
||||
it("writes a title above it as Word's built-in bibliographies do, as a Heading 1, in a content control of Word's Bibliographies gallery", () => {
|
||||
const xml = xmlOf(new Bibliography({ title: "References" }), documentWith(SOURCES));
|
||||
|
||||
expect(xml).to.match(
|
||||
new RegExp(
|
||||
'^<w:sdt><w:sdtPr><w:docPartObj><w:docPartGallery w:val="Bibliographies"/><w:docPartUnique/></w:docPartObj></w:sdtPr><w:sdtContent>' +
|
||||
'<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t xml:space="preserve">References</w:t></w:r></w:p>' +
|
||||
"<w:sdt><w:sdtPr><w:bibliography/></w:sdtPr>.*</w:sdt></w:sdtContent></w:sdt>$",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("writes paragraphs with no indent for a style whose entries have none", () => {
|
||||
const style: StyleDefinition = {
|
||||
...testStyle(),
|
||||
bibliography: () => ({ paragraphs: [[{ text: "Entry" }]], hangingIndent: false }),
|
||||
};
|
||||
|
||||
expect(xmlOf(new Bibliography(), documentWith(SOURCES, style))).to.contain(
|
||||
`<w:p><w:pPr><w:pStyle w:val="Bibliography"/><w:rPr><w:noProof/></w:rPr></w:pPr>${FIELD_START}<w:r><w:rPr><w:noProof/></w:rPr><w:t xml:space="preserve">Entry</w:t></w:r></w:p>`,
|
||||
);
|
||||
});
|
||||
|
||||
it("writes a table of each source's number and entry as Word writes IEEE's", () => {
|
||||
const row = (tag: string, order: number, title: string): string =>
|
||||
`<w:tr><w:trPr><w:tblCellSpacing w:w="15" w:type="dxa"/></w:trPr><w:tc><w:tcPr><w:tcW w:w="50" w:type="pct"/><w:hideMark/></w:tcPr><w:p><w:pPr><w:pStyle w:val="Bibliography"/><w:rPr><w:noProof/></w:rPr></w:pPr><w:r><w:rPr><w:noProof/></w:rPr><w:t xml:space="preserve">[${order}] </w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/><w:hideMark/></w:tcPr><w:p><w:pPr><w:pStyle w:val="Bibliography"/><w:rPr><w:noProof/></w:rPr></w:pPr><w:r><w:rPr><w:noProof/></w:rPr><w:t xml:space="preserve">${tag} </w:t></w:r><w:r><w:rPr><w:i/><w:iCs/><w:noProof/></w:rPr><w:t xml:space="preserve">${title}</w:t></w:r><w:r><w:rPr><w:noProof/></w:rPr><w:t xml:space="preserve"> </w:t></w:r></w:p></w:tc></w:tr>`;
|
||||
|
||||
expect(xmlOf(new Bibliography(), documentWith(SOURCES, testStyle("rows")))).to.equal(
|
||||
`<w:sdt><w:sdtPr><w:bibliography/></w:sdtPr><w:sdtContent><w:p><w:pPr><w:rPr><w:noProof/></w:rPr></w:pPr>${FIELD_START}</w:p>` +
|
||||
"<w:tbl><w:tblPr>" +
|
||||
'<w:tblW w:w="5000" w:type="pct"/><w:tblCellSpacing w:w="15" w:type="dxa"/>' +
|
||||
'<w:tblCellMar><w:top w:w="15" w:type="dxa"/><w:left w:w="15" w:type="dxa"/><w:bottom w:w="15" w:type="dxa"/><w:right w:w="15" w:type="dxa"/></w:tblCellMar>' +
|
||||
'<w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/>' +
|
||||
'</w:tblPr><w:tblGrid><w:gridCol w:w="409"/><w:gridCol w:w="8617"/></w:tblGrid>' +
|
||||
`${row("A", 2, "One")}${row("B", 1, "Two")}</w:tbl><w:p><w:pPr><w:rPr><w:noProof/></w:rPr></w:pPr></w:p>${FIELD_END}</w:sdtContent></w:sdt>`,
|
||||
);
|
||||
});
|
||||
|
||||
it("writes what Word does for a document with no sources: what it says, in bold, in one paragraph with the field", () => {
|
||||
expect(xmlOf(new Bibliography(), documentWith([]))).to.equal(
|
||||
`<w:sdt><w:sdtPr><w:bibliography/></w:sdtPr><w:sdtContent><w:p>${FIELD_START}` +
|
||||
'<w:r><w:rPr><w:b/><w:bCs/><w:noProof/></w:rPr><w:t xml:space="preserve">Invalid source specified.</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p></w:sdtContent></w:sdt>',
|
||||
);
|
||||
});
|
||||
|
||||
it("throws when it is written in a document with no sources", () => {
|
||||
expect(() => xmlOf(new Bibliography(), new Document({ sections: [] }))).toThrow("needs the document's sources");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* Bibliographies: the list of a document's sources, in the style of its citations, as Word's References > Bibliography
|
||||
* inserts it.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import {
|
||||
BuilderElement,
|
||||
FileChild,
|
||||
type IContext,
|
||||
type IParagraphOptions,
|
||||
type IXmlableObject,
|
||||
Paragraph,
|
||||
TextRun,
|
||||
type XmlComponent,
|
||||
} from "docx";
|
||||
|
||||
import { documentSourcesOf } from "./document-sources";
|
||||
import { createFieldRuns, runsOf } from "./field";
|
||||
import { formatBibliography } from "./format";
|
||||
import type { FormattedText } from "./styles/formatted-text";
|
||||
|
||||
/** What Word writes, in bold, in a bibliography of a document with no sources */
|
||||
const NO_SOURCES = "Invalid source specified.";
|
||||
|
||||
/**
|
||||
* Options for a {@link Bibliography}.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export type BibliographyOptions = {
|
||||
/**
|
||||
* A heading above the list, such as "References" or "Works Cited", in the Heading 1 style, as Word's built-in
|
||||
* bibliographies have. Without one, the bibliography is the list alone, as Word's Insert Bibliography inserts it
|
||||
*/
|
||||
readonly title?: string;
|
||||
};
|
||||
|
||||
/** A paragraph with the runs given */
|
||||
const paragraphOf = (children: readonly XmlComponent[], options: IParagraphOptions = {}): Paragraph => {
|
||||
const paragraph = new Paragraph(options);
|
||||
for (const child of children) {
|
||||
paragraph.addChildElement(child);
|
||||
}
|
||||
return paragraph;
|
||||
};
|
||||
|
||||
/**
|
||||
* An entry's paragraph, in the Bibliography style, with the lines after its first indented half an inch if the style's
|
||||
* are. Its mark is kept out of spelling and grammar checks, as its runs are
|
||||
*/
|
||||
const entryOf = (children: readonly XmlComponent[], hangingIndent = false): Paragraph =>
|
||||
paragraphOf(children, {
|
||||
style: "Bibliography",
|
||||
...(hangingIndent ? { indent: { left: 720, hanging: 720 } } : {}),
|
||||
run: { noProof: true },
|
||||
});
|
||||
|
||||
const tableCellSpacing = (): XmlComponent =>
|
||||
new BuilderElement<{ readonly width: number; readonly type: string }>({
|
||||
name: "w:tblCellSpacing",
|
||||
attributes: { width: { key: "w:w", value: 15 }, type: { key: "w:type", value: "dxa" } },
|
||||
});
|
||||
|
||||
const cellOf = (width: { readonly width: number; readonly type: string }, text: FormattedText): XmlComponent =>
|
||||
new BuilderElement({
|
||||
name: "w:tc",
|
||||
children: [
|
||||
new BuilderElement({
|
||||
name: "w:tcPr",
|
||||
children: [
|
||||
new BuilderElement<{ readonly width: number; readonly type: string }>({
|
||||
name: "w:tcW",
|
||||
attributes: { width: { key: "w:w", value: width.width }, type: { key: "w:type", value: width.type } },
|
||||
}),
|
||||
new BuilderElement({ name: "w:hideMark" }),
|
||||
],
|
||||
}),
|
||||
entryOf(runsOf(text)),
|
||||
],
|
||||
});
|
||||
|
||||
/**
|
||||
* A bibliography of numbered sources, as Word writes IEEE's: a table as wide as the text, of each source's number and
|
||||
* its entry, the number's column as narrow as its numbers.
|
||||
*/
|
||||
const tableOf = (rows: readonly (readonly [FormattedText, FormattedText])[]): XmlComponent => {
|
||||
const margin = (side: string): XmlComponent =>
|
||||
new BuilderElement<{ readonly width: number; readonly type: string }>({
|
||||
name: `w:${side}`,
|
||||
attributes: { width: { key: "w:w", value: 15 }, type: { key: "w:type", value: "dxa" } },
|
||||
});
|
||||
return new BuilderElement({
|
||||
name: "w:tbl",
|
||||
children: [
|
||||
new BuilderElement({
|
||||
name: "w:tblPr",
|
||||
children: [
|
||||
new BuilderElement<{ readonly width: number; readonly type: string }>({
|
||||
name: "w:tblW",
|
||||
attributes: { width: { key: "w:w", value: 5000 }, type: { key: "w:type", value: "pct" } },
|
||||
}),
|
||||
tableCellSpacing(),
|
||||
new BuilderElement({ name: "w:tblCellMar", children: ["top", "left", "bottom", "right"].map(margin) }),
|
||||
new BuilderElement<{
|
||||
readonly value: string;
|
||||
readonly firstRow: number;
|
||||
readonly lastRow: number;
|
||||
readonly firstColumn: number;
|
||||
readonly lastColumn: number;
|
||||
readonly noHBand: number;
|
||||
readonly noVBand: number;
|
||||
}>({
|
||||
name: "w:tblLook",
|
||||
attributes: {
|
||||
value: { key: "w:val", value: "04A0" },
|
||||
firstRow: { key: "w:firstRow", value: 1 },
|
||||
lastRow: { key: "w:lastRow", value: 0 },
|
||||
firstColumn: { key: "w:firstColumn", value: 1 },
|
||||
lastColumn: { key: "w:lastColumn", value: 0 },
|
||||
noHBand: { key: "w:noHBand", value: 0 },
|
||||
noVBand: { key: "w:noVBand", value: 1 },
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
// The columns' widths Word gives them in a page of A4 or Letter, which Word works out again from the cells'
|
||||
new BuilderElement({
|
||||
name: "w:tblGrid",
|
||||
children: [409, 8617].map(
|
||||
(width) =>
|
||||
new BuilderElement<{ readonly width: number }>({
|
||||
name: "w:gridCol",
|
||||
attributes: { width: { key: "w:w", value: width } },
|
||||
}),
|
||||
),
|
||||
}),
|
||||
...rows.map(
|
||||
([label, entry]) =>
|
||||
new BuilderElement({
|
||||
name: "w:tr",
|
||||
children: [
|
||||
new BuilderElement({ name: "w:trPr", children: [tableCellSpacing()] }),
|
||||
cellOf({ width: 50, type: "pct" }, label),
|
||||
cellOf({ width: 0, type: "auto" }, entry),
|
||||
],
|
||||
}),
|
||||
),
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* The bibliography's content control and its BIBLIOGRAPHY field, whose result is the document's sources in the style of
|
||||
* its citations. The field starts in the first paragraph and ends in a paragraph of its own after the last, as Word
|
||||
* writes it.
|
||||
*/
|
||||
const createBibliographyControl = (context: IContext): XmlComponent => {
|
||||
const { style, sources } = documentSourcesOf(context);
|
||||
const bibliography = formatBibliography(style, sources);
|
||||
const [begin, instruction, separate, end] = createFieldRuns(" BIBLIOGRAPHY ", []);
|
||||
const fieldStart = [begin, instruction, separate];
|
||||
// With no sources, Word writes the field and what it says, in bold, in one paragraph with no style
|
||||
const content =
|
||||
sources.length === 0
|
||||
? [paragraphOf([...fieldStart, ...runsOf([{ text: NO_SOURCES, bold: true }]), end])]
|
||||
: "rows" in bibliography
|
||||
? // The field starts in a paragraph of its own before a table, with no style, and an empty paragraph follows
|
||||
// the table before the one the field ends in
|
||||
[
|
||||
paragraphOf(fieldStart, { run: { noProof: true } }),
|
||||
tableOf(bibliography.rows),
|
||||
paragraphOf([], { run: { noProof: true } }),
|
||||
paragraphOf([end]),
|
||||
]
|
||||
: [
|
||||
...bibliography.paragraphs.map((entry, index) =>
|
||||
entryOf([...(index === 0 ? fieldStart : []), ...runsOf(entry)], bibliography.hangingIndent),
|
||||
),
|
||||
// The field ends in a paragraph of its own, with no style
|
||||
paragraphOf([end]),
|
||||
];
|
||||
return new BuilderElement({
|
||||
name: "w:sdt",
|
||||
children: [
|
||||
new BuilderElement({ name: "w:sdtPr", children: [new BuilderElement({ name: "w:bibliography" })] }),
|
||||
new BuilderElement({ name: "w:sdtContent", children: content }),
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* A bibliography: the list of the document's sources, in the style of its citations, as Word's References >
|
||||
* Bibliography inserts it. It lists every source of the document's bibliography, cited or not, and Word writes it again
|
||||
* when it updates the document's fields, or when the style is changed.
|
||||
*
|
||||
* The document needs its sources: give it `bibliography: createBibliography({ sources })`.
|
||||
*
|
||||
* @publicApi
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // As Word's built-in "References" bibliography: a heading, then the list
|
||||
* new Bibliography({ title: "References" });
|
||||
* ```
|
||||
*/
|
||||
export class Bibliography extends FileChild {
|
||||
public constructor(private readonly options: BibliographyOptions = {}) {
|
||||
super("w:sdt");
|
||||
}
|
||||
|
||||
/**
|
||||
* With a title, written as Word's built-in bibliographies are, in a content control of Word's Bibliographies gallery,
|
||||
* with the title as a Heading 1 before the bibliography's own content control. Without one, it is that content
|
||||
* control alone
|
||||
*/
|
||||
public prepForXml(context: IContext): IXmlableObject | undefined {
|
||||
const list = createBibliographyControl(context);
|
||||
if (this.options.title === undefined) {
|
||||
return list.prepForXml(context);
|
||||
}
|
||||
return new BuilderElement({
|
||||
name: "w:sdt",
|
||||
children: [
|
||||
new BuilderElement({
|
||||
name: "w:sdtPr",
|
||||
children: [
|
||||
new BuilderElement({
|
||||
name: "w:docPartObj",
|
||||
children: [
|
||||
new BuilderElement<{ readonly value: string }>({
|
||||
name: "w:docPartGallery",
|
||||
attributes: { value: { key: "w:val", value: "Bibliographies" } },
|
||||
}),
|
||||
new BuilderElement({ name: "w:docPartUnique" }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
new BuilderElement({
|
||||
name: "w:sdtContent",
|
||||
children: [new Paragraph({ style: "Heading1", children: [new TextRun(this.options.title)] }), list],
|
||||
}),
|
||||
],
|
||||
}).prepForXml(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* The styles of citation Word has, such as APA and MLA, which a document's citations and bibliographies are written in.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { apa } from "./styles/apa";
|
||||
import { chicago } from "./styles/chicago";
|
||||
import { gb7714 } from "./styles/gb7714";
|
||||
import { gostNameSort } from "./styles/gost-name-sort";
|
||||
import { gostTitleSort } from "./styles/gost-title-sort";
|
||||
import { harvardAnglia } from "./styles/harvard-anglia";
|
||||
import { ieee } from "./styles/ieee";
|
||||
import { iso690FirstElementAndDate } from "./styles/iso-690-first-element-and-date";
|
||||
import { iso690NumericalReference } from "./styles/iso-690-numerical-reference";
|
||||
import { mla } from "./styles/mla";
|
||||
import { sist02 } from "./styles/sist02";
|
||||
import type { StyleDefinition } from "./styles/style";
|
||||
import { turabian } from "./styles/turabian";
|
||||
|
||||
/**
|
||||
* The styles of citation Word has, as Word lists them in References > Style. Each is written as Word writes it, and its
|
||||
* citation of a book by Anna Baker from 2010 is in its description.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export const CitationStyle = {
|
||||
/** APA, sixth edition: "(Baker, 2010)" */
|
||||
APA: "apa",
|
||||
/** Chicago, sixteenth edition, author-date: "(Baker 2010)" */
|
||||
CHICAGO: "chicago",
|
||||
/** GB7714, China's national standard: "(Baker, 2010)" */
|
||||
GB7714: "gb7714",
|
||||
/** GOST, Russia's national standard, with the bibliography sorted by name: "(Baker, 2010)" */
|
||||
GOST_NAME_SORT: "gostNameSort",
|
||||
/** GOST, Russia's national standard, with the bibliography sorted by title: "(Baker, 2010)" */
|
||||
GOST_TITLE_SORT: "gostTitleSort",
|
||||
/** Harvard, as Anglia Ruskin University writes it: "(Baker, 2010)" */
|
||||
HARVARD_ANGLIA: "harvardAnglia",
|
||||
/** IEEE, with the sources numbered in the order they're cited: "[1]" */
|
||||
IEEE: "ieee",
|
||||
/** ISO 690, with the first element and the date: "(Baker, 2010)" */
|
||||
ISO_690_FIRST_ELEMENT_AND_DATE: "iso690FirstElementAndDate",
|
||||
/** ISO 690, with the sources numbered in the order they're cited: "(1)" */
|
||||
ISO_690_NUMERICAL_REFERENCE: "iso690NumericalReference",
|
||||
/** MLA, seventh edition: "(Baker)" */
|
||||
MLA: "mla",
|
||||
/** SIST02, Japan's standard, in full-width punctuation: "(Baker,2010)" */
|
||||
SIST02: "sist02",
|
||||
/** Turabian, sixth edition: "(Baker 2010)" */
|
||||
TURABIAN: "turabian",
|
||||
} as const;
|
||||
|
||||
/** Each style of citation's definition */
|
||||
export const STYLE_DEFINITIONS: Readonly<Record<(typeof CitationStyle)[keyof typeof CitationStyle], StyleDefinition>> = {
|
||||
apa,
|
||||
chicago,
|
||||
gb7714,
|
||||
gostNameSort,
|
||||
gostTitleSort,
|
||||
harvardAnglia,
|
||||
ieee,
|
||||
iso690FirstElementAndDate,
|
||||
iso690NumericalReference,
|
||||
mla,
|
||||
sist02,
|
||||
turabian,
|
||||
};
|
||||
@@ -0,0 +1,113 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { Document, Paragraph, Run, TextRun } from "docx";
|
||||
import { testStyle, xmlOf } from "tests/bibliography";
|
||||
|
||||
import { Citation, citationInstructionOf } from "./citation";
|
||||
import { BibliographySources } from "./document-sources";
|
||||
import type { Source } from "./source";
|
||||
import type { StyleDefinition } from "./styles/style";
|
||||
|
||||
const SOURCES: readonly Source[] = [
|
||||
{ tag: "A", type: "book", title: "One" },
|
||||
{ tag: "B", type: "book", title: "Two" },
|
||||
];
|
||||
|
||||
const documentWith = (citation: Citation, style: StyleDefinition = testStyle()): Document =>
|
||||
new Document({
|
||||
bibliography: { sources: new BibliographySources(style, SOURCES) },
|
||||
sections: [{ children: [new Paragraph({ children: [citation] })] }],
|
||||
});
|
||||
|
||||
const field = (instruction: string, result: string): string =>
|
||||
`<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve">${instruction}</w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r>${result}<w:r><w:fldChar w:fldCharType="end"/></w:r>`;
|
||||
|
||||
describe("Citation", () => {
|
||||
it("is a run, so a paragraph takes it", () => {
|
||||
expect(new Citation("A")).to.be.instanceOf(Run);
|
||||
});
|
||||
|
||||
it("is written as Word's citation content control, with a CITATION field whose result is the citation in the document's style", () => {
|
||||
const citation = new Citation("A");
|
||||
|
||||
expect(xmlOf(new Paragraph({ children: [new TextRun("See "), citation] }), documentWith(citation))).to.equal(
|
||||
`<w:p><w:r><w:t xml:space="preserve">See </w:t></w:r><w:sdt><w:sdtPr><w:citation/></w:sdtPr><w:sdtContent>${field(
|
||||
" CITATION A \\l 1033 ",
|
||||
'<w:r><w:rPr><w:noProof/></w:rPr><w:t xml:space="preserve">(A)</w:t></w:r>',
|
||||
)}</w:sdtContent></w:sdt></w:p>`,
|
||||
);
|
||||
});
|
||||
|
||||
it("cites several sources, each with how it is cited", () => {
|
||||
const citation = new Citation(["A", { source: "B", pages: "5" }]);
|
||||
|
||||
expect(xmlOf(citation.writtenAs[0], documentWith(citation))).to.contain(
|
||||
field(
|
||||
" CITATION A \\l 1033 \\m B \\p "5" ",
|
||||
'<w:r><w:rPr><w:noProof/></w:rPr><w:t xml:space="preserve">(A; B, p. 5)</w:t></w:r>',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("cites a source with how it is cited", () => {
|
||||
const citation = new Citation({ source: "A", hideAuthor: true });
|
||||
|
||||
expect(xmlOf(citation.writtenAs[0], documentWith(citation))).to.contain('<w:t xml:space="preserve">(A, no author)</w:t>');
|
||||
});
|
||||
|
||||
it("writes the result's formatting and line breaks", () => {
|
||||
const citation = new Citation("A");
|
||||
const style: StyleDefinition = {
|
||||
...testStyle(),
|
||||
citation: () => [
|
||||
{ text: "Bold", bold: true },
|
||||
{ text: "Italic", italics: true },
|
||||
{ text: "", lineBreak: true },
|
||||
{ text: "Underlined", underline: true },
|
||||
],
|
||||
};
|
||||
|
||||
expect(xmlOf(citation.writtenAs[0], documentWith(citation, style))).to.contain(
|
||||
'<w:r><w:rPr><w:b/><w:bCs/><w:noProof/></w:rPr><w:t xml:space="preserve">Bold</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:i/><w:iCs/><w:noProof/></w:rPr><w:t xml:space="preserve">Italic</w:t></w:r>' +
|
||||
"<w:r><w:rPr><w:noProof/></w:rPr><w:br/></w:r>" +
|
||||
'<w:r><w:rPr><w:noProof/><w:u w:val="single"/></w:rPr><w:t xml:space="preserve">Underlined</w:t></w:r>',
|
||||
);
|
||||
});
|
||||
|
||||
it("throws for no source", () => {
|
||||
expect(() => new Citation([])).toThrow('A citation cites no source. Give it the tag of the source it cites, such as "Dic06"');
|
||||
});
|
||||
|
||||
it("throws when it is written in a document with no sources", () => {
|
||||
const citation = new Citation("A");
|
||||
|
||||
expect(() => xmlOf(citation.writtenAs[0], new Document({ sections: [] }))).toThrow("needs the document's sources");
|
||||
});
|
||||
});
|
||||
|
||||
describe("citationInstructionOf", () => {
|
||||
it("writes each switch of a source, in quotes, with the language after the first source's", () => {
|
||||
expect(
|
||||
citationInstructionOf([
|
||||
{
|
||||
source: "A",
|
||||
prefix: "see ",
|
||||
suffix: " (n. 2)",
|
||||
pages: "1, 5",
|
||||
volume: "2",
|
||||
hideAuthor: true,
|
||||
hideYear: true,
|
||||
hideTitle: true,
|
||||
},
|
||||
{ source: "B", volume: "3" },
|
||||
]),
|
||||
).to.equal(' CITATION A \\f "see " \\s " (n. 2)" \\p "1, 5" \\v "2" \\n \\y \\t \\l 1033 \\m B \\v "3" ');
|
||||
});
|
||||
|
||||
it("escapes quotes and backslashes in a switch, and puts a tag with a space in quotes", () => {
|
||||
expect(citationInstructionOf([{ source: 'A "B"', prefix: 'see "this" \\ ' }])).to.equal(
|
||||
' CITATION "A \\"B\\"" \\f "see \\"this\\" \\\\ " \\l 1033 ',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* Citations: references in the text to one or more of a document's sources, such as "(Baker, 2010)", as Word's
|
||||
* References > Insert Citation inserts them.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { BuilderElement, type IContext, type IXmlableObject, Run, XmlComponent } from "docx";
|
||||
|
||||
import { citedSourcesOf, documentSourcesOf } from "./document-sources";
|
||||
import { createFieldRuns, runsOf } from "./field";
|
||||
import { type CitedSourceOptions, formatCitation } from "./format";
|
||||
|
||||
/** A field's value in its instruction: in quotes, with the quotes and backslashes in it escaped, as Word writes one */
|
||||
const quoted = (value: string): string => `"${value.replace(/[\\"]/g, "\\$&")}"`;
|
||||
|
||||
/** A source's tag in a field's instruction: as it is, unless it has a space or a quote in it */
|
||||
const tagOf = (tag: string): string => (/[\s"\\]/.test(tag) ? quoted(tag) : tag);
|
||||
|
||||
/** The switches of a source of a citation, after its tag */
|
||||
const switchesOf = ({ pages, volume, prefix, suffix, hideAuthor, hideYear, hideTitle }: CitedSourceOptions): readonly string[] => [
|
||||
...(prefix !== undefined ? [`\\f ${quoted(prefix)}`] : []),
|
||||
...(suffix !== undefined ? [`\\s ${quoted(suffix)}`] : []),
|
||||
...(pages !== undefined ? [`\\p ${quoted(pages)}`] : []),
|
||||
...(volume !== undefined ? [`\\v ${quoted(volume)}`] : []),
|
||||
...(hideAuthor ? ["\\n"] : []),
|
||||
...(hideYear ? ["\\y"] : []),
|
||||
...(hideTitle ? ["\\t"] : []),
|
||||
];
|
||||
|
||||
/**
|
||||
* A citation's field instruction, such as ` CITATION Dic06 \p "50" \l 1033 `: the first source's tag and switches, the
|
||||
* language, English, and each other source after `\m`.
|
||||
*/
|
||||
export const citationInstructionOf = (cited: readonly CitedSourceOptions[]): string =>
|
||||
` CITATION ${cited
|
||||
.map((source, index) =>
|
||||
[
|
||||
index === 0 ? tagOf(source.source) : `\\m ${tagOf(source.source)}`,
|
||||
...switchesOf(source),
|
||||
...(index === 0 ? ["\\l 1033"] : []),
|
||||
].join(" "),
|
||||
)
|
||||
.join(" ")} `;
|
||||
|
||||
/**
|
||||
* The citation as Word writes it: a citation content control, with a CITATION field, whose result is the citation in
|
||||
* the style of the document's bibliography.
|
||||
*
|
||||
* ## XSD Schema
|
||||
* ```xml
|
||||
* <xsd:complexType name="CT_SdtRun">
|
||||
* <xsd:sequence>
|
||||
* <xsd:element name="sdtPr" type="CT_SdtPr" minOccurs="0" maxOccurs="1"/>
|
||||
* <xsd:element name="sdtEndPr" type="CT_SdtEndPr" minOccurs="0" maxOccurs="1"/>
|
||||
* <xsd:element name="sdtContent" type="CT_SdtContentRun" minOccurs="0" maxOccurs="1"/>
|
||||
* </xsd:sequence>
|
||||
* </xsd:complexType>
|
||||
* ```
|
||||
*/
|
||||
class CitationContentControl extends XmlComponent {
|
||||
public constructor(private readonly cited: readonly CitedSourceOptions[]) {
|
||||
super("w:sdt");
|
||||
}
|
||||
|
||||
public prepForXml(context: IContext): IXmlableObject | undefined {
|
||||
const { style, sources } = documentSourcesOf(context);
|
||||
return new BuilderElement({
|
||||
name: "w:sdt",
|
||||
children: [
|
||||
new BuilderElement({ name: "w:sdtPr", children: [new BuilderElement({ name: "w:citation" })] }),
|
||||
new BuilderElement({
|
||||
name: "w:sdtContent",
|
||||
children: createFieldRuns(citationInstructionOf(this.cited), runsOf(formatCitation(style, sources, this.cited))),
|
||||
}),
|
||||
],
|
||||
}).prepForXml(context);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A citation of one or more of the document's sources, by their tags, such as "(Baker, 2010)" in APA, as Word's
|
||||
* References > Insert Citation inserts it. It is written in the style of the document's bibliography, and Word writes
|
||||
* it again when it updates the document's fields, or when the style is changed.
|
||||
*
|
||||
* The document needs its sources: give it `bibliography: createBibliography({ sources })`.
|
||||
*
|
||||
* @publicApi
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* new Paragraph({ children: [new TextRun("Pizza is older than you think "), new Citation("Bak10")] });
|
||||
*
|
||||
* // Pages, and text before the citation
|
||||
* new Citation({ source: "Bak10", pages: "50", prefix: "see " });
|
||||
*
|
||||
* // Two sources, as one citation: "(Baker, 2010; Evans, 2019, p. 20)"
|
||||
* new Citation(["Bak10", { source: "Eva19", pages: "20" }]);
|
||||
* ```
|
||||
*/
|
||||
export class Citation extends Run {
|
||||
private readonly cited: readonly CitedSourceOptions[];
|
||||
|
||||
/**
|
||||
* @param cited - The source cited, by its tag, or with how it is cited, or several sources, cited together
|
||||
* @throws If no source is cited
|
||||
*/
|
||||
public constructor(cited: string | CitedSourceOptions | readonly (string | CitedSourceOptions)[]) {
|
||||
super({});
|
||||
const list = (Array.isArray(cited) ? cited : [cited]) as readonly (string | CitedSourceOptions)[];
|
||||
if (list.length === 0) {
|
||||
throw new Error('A citation cites no source. Give it the tag of the source it cites, such as "Dic06"');
|
||||
}
|
||||
this.cited = list.map((source) => (typeof source === "string" ? { source } : source));
|
||||
citedSourcesOf.set(this, this.cited);
|
||||
}
|
||||
|
||||
/** Written as Word's citation content control, in place of a run */
|
||||
public override get writtenAs(): readonly XmlComponent[] {
|
||||
return [new CitationContentControl(this.cited)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { xmlOf } from "tests/bibliography";
|
||||
|
||||
import { Citation } from "./citation";
|
||||
import { CitationStyle, STYLE_DEFINITIONS } from "./citation-style";
|
||||
import { createBibliography } from "./create-bibliography";
|
||||
import { BibliographySources } from "./document-sources";
|
||||
import type { Source } from "./source";
|
||||
|
||||
const BOOK: Source = {
|
||||
tag: "Bak10",
|
||||
type: "book",
|
||||
authors: [{ lastName: "Baker", firstName: "Anna" }],
|
||||
title: "The Art of Pizza",
|
||||
year: 2010,
|
||||
city: "Naples",
|
||||
publisher: "Oven Press",
|
||||
};
|
||||
|
||||
describe("createBibliography", () => {
|
||||
it("writes the sources in APA, Word's default style, when no style is given", () => {
|
||||
const bibliography = createBibliography({ sources: [BOOK] });
|
||||
|
||||
expect(bibliography.sources).to.be.instanceOf(BibliographySources);
|
||||
expect((bibliography.sources as BibliographySources).style).to.equal(STYLE_DEFINITIONS.apa);
|
||||
});
|
||||
|
||||
it("writes the sources in the style given", () => {
|
||||
const citation = new Citation("Bak10");
|
||||
const doc = new Document({
|
||||
bibliography: createBibliography({ style: CitationStyle.IEEE, sources: [BOOK] }),
|
||||
sections: [{ children: [new Paragraph({ children: [citation] })] }],
|
||||
});
|
||||
|
||||
expect(xmlOf(citation.writtenAs[0], doc)).to.contain('<w:t xml:space="preserve">[1]</w:t>');
|
||||
expect(xmlOf(doc.Bibliography!.sources, doc)).to.contain(
|
||||
'<b:Sources SelectedStyle="/IEEE2006OfficeOnline.xsl" StyleName="IEEE" Version="2006"',
|
||||
);
|
||||
});
|
||||
|
||||
it("has a definition for each style", () => {
|
||||
expect(Object.keys(STYLE_DEFINITIONS).sort()).to.deep.equal(Object.values(CitationStyle).sort());
|
||||
});
|
||||
|
||||
it("throws for a style that isn't one of CitationStyle's", () => {
|
||||
expect(() => createBibliography({ style: "harvard" as "harvardAnglia", sources: [BOOK] })).toThrow(
|
||||
"\"harvard\" isn't a style of citation. Give one of CitationStyle's, such as CitationStyle.APA",
|
||||
);
|
||||
});
|
||||
|
||||
it("throws for the name of a property every object has, which isn't a style", () => {
|
||||
expect(() => createBibliography({ style: "toString" as "apa", sources: [BOOK] })).toThrow('"toString" isn\'t a style of citation');
|
||||
expect(() => createBibliography({ style: "__proto__" as "apa", sources: [BOOK] })).toThrow(
|
||||
'"__proto__" isn\'t a style of citation',
|
||||
);
|
||||
});
|
||||
|
||||
it("throws for two sources with one tag", () => {
|
||||
expect(() => createBibliography({ sources: [BOOK, BOOK] })).toThrow('Two of the bibliography\'s sources have the tag "Bak10"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* A document's bibliography: the sources its citations and bibliographies refer to, and the style they're written in.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { DocumentBibliography } from "docx";
|
||||
|
||||
import { CitationStyle, STYLE_DEFINITIONS } from "./citation-style";
|
||||
import { BibliographySources } from "./document-sources";
|
||||
import type { Source } from "./source";
|
||||
|
||||
/**
|
||||
* Options for {@link createBibliography}.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export type DocumentBibliographyOptions = {
|
||||
/** The style the citations and bibliographies are written in, such as APA, Word's own default, which it is if not given */
|
||||
readonly style?: (typeof CitationStyle)[keyof typeof CitationStyle];
|
||||
/** The sources, such as books and websites, which Word lists in its Source Manager */
|
||||
readonly sources: readonly Source[];
|
||||
};
|
||||
|
||||
/**
|
||||
* A document's bibliography, for the document's `bibliography`: the sources its citations and bibliographies refer to,
|
||||
* and the style they're written in, as Word's References > Manage Sources and Style keep them.
|
||||
*
|
||||
* Every source is in the document's bibliographies, cited or not, as Word's are, and Word lists every source in its
|
||||
* Source Manager.
|
||||
*
|
||||
* @publicApi
|
||||
*
|
||||
* @throws If two sources have the same tag, a source has none, a source's type isn't one of {@link SourceType}'s, or the
|
||||
* style isn't one of {@link CitationStyle}'s
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const doc = new Document({
|
||||
* bibliography: createBibliography({
|
||||
* style: CitationStyle.APA,
|
||||
* sources: [
|
||||
* {
|
||||
* tag: "Bak10",
|
||||
* type: SourceType.BOOK,
|
||||
* authors: [{ lastName: "Baker", firstName: "Anna" }],
|
||||
* title: "The Art of Pizza",
|
||||
* year: 2010,
|
||||
* city: "Naples",
|
||||
* publisher: "Oven Press",
|
||||
* },
|
||||
* ],
|
||||
* }),
|
||||
* sections: [{ children: [new Paragraph({ children: [new Citation("Bak10")] }), new Bibliography({ title: "References" })] }],
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export const createBibliography = ({ style = CitationStyle.APA, sources }: DocumentBibliographyOptions): DocumentBibliography => {
|
||||
// Only the definitions' own keys, as every object has others, such as "toString"
|
||||
if (!Object.keys(STYLE_DEFINITIONS).includes(style)) {
|
||||
throw new Error(`"${style}" isn't a style of citation. Give one of CitationStyle's, such as CitationStyle.APA`);
|
||||
}
|
||||
return { sources: new BibliographySources(STYLE_DEFINITIONS[style], sources) };
|
||||
};
|
||||
@@ -0,0 +1,127 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
Bookmark,
|
||||
Document,
|
||||
ExternalHyperlink,
|
||||
Footer,
|
||||
Header,
|
||||
type ISectionOptions,
|
||||
Paragraph,
|
||||
Table,
|
||||
TableCell,
|
||||
TableRow,
|
||||
TextRun,
|
||||
} from "docx";
|
||||
import { testStyle, xmlOf } from "tests/bibliography";
|
||||
|
||||
import { Citation } from "./citation";
|
||||
import { BibliographySources, documentSourcesOf } from "./document-sources";
|
||||
import type { Source } from "./source";
|
||||
|
||||
const book = (tag: string, title?: string): Source => ({ tag, type: "book", title });
|
||||
|
||||
const fileWith = (sources: readonly Source[], section: Partial<ISectionOptions> = {}, footnotes = {}): Document =>
|
||||
new Document({
|
||||
bibliography: { sources: new BibliographySources(testStyle(), sources) },
|
||||
footnotes,
|
||||
sections: [{ children: [], ...section }],
|
||||
});
|
||||
|
||||
const orderIn = (file: Document): readonly (readonly [string, number])[] =>
|
||||
documentSourcesOf({ file, viewWrapper: file.Document, stack: [] }).sources.map(({ tag, order }) => [tag, order] as const);
|
||||
|
||||
describe("BibliographySources", () => {
|
||||
it("throws for two sources with one tag", () => {
|
||||
expect(() => new BibliographySources(testStyle(), [book("A"), book("B"), book("A")])).toThrow(
|
||||
'Two of the bibliography\'s sources have the tag "A". Give each source a tag of its own',
|
||||
);
|
||||
});
|
||||
|
||||
it("throws for a source that Word can't keep", () => {
|
||||
expect(() => new BibliographySources(testStyle(), [book("")])).toThrow("A bibliography's source has no tag");
|
||||
});
|
||||
|
||||
it("writes the sources as Word does, with its style's file, name and version, and the order they're cited in", () => {
|
||||
const file = fileWith([book("A", "One"), book("B")], {
|
||||
children: [new Paragraph({ children: [new Citation("B")] })],
|
||||
});
|
||||
|
||||
expect(xmlOf(file.Bibliography!.sources, file)).to.equal(
|
||||
'<b:Sources SelectedStyle="/TEST.XSL" StyleName="Test" Version="1" xmlns:b="http://schemas.openxmlformats.org/officeDocument/2006/bibliography" xmlns="http://schemas.openxmlformats.org/officeDocument/2006/bibliography">' +
|
||||
"<b:Source><b:Tag>A</b:Tag><b:SourceType>Book</b:SourceType><b:Title>One</b:Title><b:RefOrder>2</b:RefOrder></b:Source>" +
|
||||
"<b:Source><b:Tag>B</b:Tag><b:SourceType>Book</b:SourceType><b:RefOrder>1</b:RefOrder></b:Source>" +
|
||||
"</b:Sources>",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("documentSourcesOf", () => {
|
||||
it("numbers the sources in the order the document cites them, wherever the citations are", () => {
|
||||
const file = fileWith(
|
||||
[
|
||||
book("Body"),
|
||||
book("Table"),
|
||||
book("Link"),
|
||||
book("Bookmark"),
|
||||
book("Footnote"),
|
||||
book("Header"),
|
||||
book("Footer"),
|
||||
book("Uncited"),
|
||||
],
|
||||
{
|
||||
headers: { default: new Header({ children: [new Paragraph({ children: [new Citation("Header")] })] }) },
|
||||
footers: { default: new Footer({ children: [new Paragraph({ children: [new Citation("Footer")] })] }) },
|
||||
children: [
|
||||
new Paragraph({ children: [new TextRun("Text"), new Citation(["Body", { source: "Body", pages: "2" }])] }),
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [new TableCell({ children: [new Paragraph({ children: [new Citation("Table")] })] })],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ExternalHyperlink({ link: "https://example.com", children: [new Citation("Link")] }),
|
||||
new Bookmark({ id: "mark", children: [new Citation("Bookmark")] }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
{ 1: { children: [new Paragraph({ children: [new Citation("Footnote")] })] } },
|
||||
);
|
||||
|
||||
expect(orderIn(file)).to.deep.equal([
|
||||
["Body", 1],
|
||||
["Table", 2],
|
||||
["Link", 3],
|
||||
["Bookmark", 4],
|
||||
["Footnote", 5],
|
||||
["Header", 6],
|
||||
["Footer", 7],
|
||||
["Uncited", 8],
|
||||
]);
|
||||
});
|
||||
|
||||
it("works out a document's sources once", () => {
|
||||
const file = fileWith([book("A")]);
|
||||
const context = { file, viewWrapper: file.Document, stack: [] };
|
||||
|
||||
expect(documentSourcesOf(context)).to.equal(documentSourcesOf(context));
|
||||
});
|
||||
|
||||
it("throws for a document with no bibliography", () => {
|
||||
const file = new Document({ sections: [] });
|
||||
|
||||
expect(() => documentSourcesOf({ file, viewWrapper: file.Document, stack: [] })).toThrow(
|
||||
"A citation or a bibliography needs the document's sources. Give the Document `bibliography: createBibliography({ sources })` from docx/bibliography",
|
||||
);
|
||||
});
|
||||
|
||||
it("throws for a bibliography that isn't docx/bibliography's", () => {
|
||||
const file = new Document({ bibliography: { sources: new Paragraph("Sources") }, sections: [] });
|
||||
|
||||
expect(() => documentSourcesOf({ file, viewWrapper: file.Document, stack: [] })).toThrow("needs the document's sources");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* A document's sources: the part Word keeps them in, and the sources as its citations and bibliographies write them,
|
||||
* numbered in the order the document cites them.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { BuilderElement, type File, type IContext, type IXmlableObject, XmlComponent } from "docx";
|
||||
|
||||
import { type CitedSourceOptions, citationOrderOf } from "./format";
|
||||
import type { Source } from "./source";
|
||||
import type { StyleDefinition } from "./styles/style";
|
||||
import { type WordSource, createSourceXml, wordSourceOf } from "./word-source";
|
||||
|
||||
const BIBLIOGRAPHY_NAMESPACE = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography";
|
||||
|
||||
/** The sources each citation cites, by the citation, which a document's citations are found by */
|
||||
export const citedSourcesOf = new WeakMap<object, readonly CitedSourceOptions[]>();
|
||||
|
||||
/**
|
||||
* The tags of the sources the document's citations cite, in the order they are in its parts: its body, footnotes,
|
||||
* endnotes, headers and footers.
|
||||
*
|
||||
* A component can keep its children in any of its properties, such as a hyperlink's options or a footnote's first
|
||||
* paragraph, until it is written, so each property of each component is looked in, in order, and each object once.
|
||||
*/
|
||||
const citedTagsOf = (file: File): readonly string[] => {
|
||||
const visited = new WeakSet<object>();
|
||||
const visit = (value: unknown): readonly string[] => {
|
||||
if (typeof value !== "object" || value === null || visited.has(value) || ArrayBuffer.isView(value)) {
|
||||
return [];
|
||||
}
|
||||
visited.add(value);
|
||||
const cited = citedSourcesOf.get(value);
|
||||
if (cited) {
|
||||
return cited.map(({ source }) => source);
|
||||
}
|
||||
return (Array.isArray(value) ? value : Object.values(value)).flatMap(visit);
|
||||
};
|
||||
return [
|
||||
file.Document.View,
|
||||
file.FootNotes.View,
|
||||
file.Endnotes.View,
|
||||
...file.Headers.map((header) => header.View),
|
||||
...file.Footers.map((footer) => footer.View),
|
||||
].flatMap(visit);
|
||||
};
|
||||
|
||||
/** A document's sources, as its citations and bibliographies write them, and the style they're written in */
|
||||
export type DocumentSources = {
|
||||
readonly style: StyleDefinition;
|
||||
readonly sources: readonly WordSource[];
|
||||
};
|
||||
|
||||
/**
|
||||
* A document's sources and the style they're written in, for the document's `bibliography`: the part Word keeps them
|
||||
* in (customXml/item1.xml), which `createBibliography` makes.
|
||||
*
|
||||
* ## XSD Schema
|
||||
* ```xml
|
||||
* <xsd:complexType name="CT_Sources">
|
||||
* <xsd:sequence>
|
||||
* <xsd:element name="Source" type="CT_SourceType" minOccurs="0" maxOccurs="unbounded"/>
|
||||
* </xsd:sequence>
|
||||
* <xsd:attribute name="SelectedStyle" type="s:ST_String"/>
|
||||
* <xsd:attribute name="StyleName" type="s:ST_String"/>
|
||||
* <xsd:attribute name="URI" type="s:ST_String"/>
|
||||
* </xsd:complexType>
|
||||
* ```
|
||||
*/
|
||||
export class BibliographySources extends XmlComponent {
|
||||
// Each document's sources, numbered in the order it cites them
|
||||
private readonly documents = new WeakMap<File, DocumentSources>();
|
||||
|
||||
/**
|
||||
* @throws If a source has no tag, or the same tag as another, a type that isn't one of SourceType's, or both people and
|
||||
* an organization in one role
|
||||
*/
|
||||
public constructor(
|
||||
public readonly style: StyleDefinition,
|
||||
public readonly sources: readonly Source[],
|
||||
) {
|
||||
super("b:Sources");
|
||||
for (const source of sources) {
|
||||
wordSourceOf(source, 0);
|
||||
}
|
||||
const repeated = sources.find((source, index) => sources.findIndex(({ tag }) => tag === source.tag) !== index);
|
||||
if (repeated) {
|
||||
throw new Error(`Two of the bibliography's sources have the tag "${repeated.tag}". Give each source a tag of its own`);
|
||||
}
|
||||
}
|
||||
|
||||
/** The document's sources, numbered in the order it cites them */
|
||||
public sourcesOf(file: File): DocumentSources {
|
||||
const known = this.documents.get(file);
|
||||
if (known) {
|
||||
return known;
|
||||
}
|
||||
const order = citationOrderOf(
|
||||
this.sources.map(({ tag }) => tag),
|
||||
citedTagsOf(file),
|
||||
);
|
||||
const sources = { style: this.style, sources: this.sources.map((source) => wordSourceOf(source, order.get(source.tag)!)) };
|
||||
this.documents.set(file, sources);
|
||||
return sources;
|
||||
}
|
||||
|
||||
/**
|
||||
* Written with the file of Word's style after a slash, as Word for Mac writes it, its name and version, and each
|
||||
* source, with the order the document cites it in. Word for Windows writes a backslash, which Word for Mac doesn't
|
||||
* find the style by, so a document with one opens in APA in Word for Mac.
|
||||
*/
|
||||
public prepForXml(context: IContext): IXmlableObject | undefined {
|
||||
return new BuilderElement<{
|
||||
readonly selectedStyle: string;
|
||||
readonly styleName: string;
|
||||
readonly version: string;
|
||||
readonly prefix: string;
|
||||
readonly namespace: string;
|
||||
}>({
|
||||
name: "b:Sources",
|
||||
attributes: {
|
||||
selectedStyle: { key: "SelectedStyle", value: `/${this.style.file}` },
|
||||
styleName: { key: "StyleName", value: this.style.name },
|
||||
version: { key: "Version", value: this.style.version },
|
||||
prefix: { key: "xmlns:b", value: BIBLIOGRAPHY_NAMESPACE },
|
||||
namespace: { key: "xmlns", value: BIBLIOGRAPHY_NAMESPACE },
|
||||
},
|
||||
children: this.sourcesOf(context.file).sources.map(createSourceXml),
|
||||
}).prepForXml(context);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The sources of the document being written, which its citations and bibliographies write.
|
||||
*
|
||||
* @throws If the document has no bibliography, or one that `createBibliography` didn't make
|
||||
*/
|
||||
export const documentSourcesOf = (context: IContext): DocumentSources => {
|
||||
const sources = context.file.Bibliography?.sources;
|
||||
if (!(sources instanceof BibliographySources)) {
|
||||
throw new Error(
|
||||
"A citation or a bibliography needs the document's sources. Give the Document `bibliography: createBibliography({ sources })` from docx/bibliography",
|
||||
);
|
||||
}
|
||||
return sources.sourcesOf(context.file);
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* The fields of citations and bibliographies, written with the result `docx` works out for them, as Word writes them.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { BuilderElement, NextAttributeComponent, TextRun, XmlComponent } from "docx";
|
||||
|
||||
import type { FormattedText } from "./styles/formatted-text";
|
||||
|
||||
/** Formatted text as runs, each kept out of spelling and grammar checks, as Word writes a citation's or a bibliography's */
|
||||
export const runsOf = (text: FormattedText): readonly XmlComponent[] =>
|
||||
text.map(
|
||||
(run) =>
|
||||
new TextRun({
|
||||
...(run.lineBreak ? { break: 1 } : { text: run.text }),
|
||||
bold: run.bold,
|
||||
italics: run.italics,
|
||||
underline: run.underline ? {} : undefined,
|
||||
noProof: true,
|
||||
}),
|
||||
);
|
||||
|
||||
/** A field's instruction, with its spaces kept */
|
||||
class FieldInstruction extends XmlComponent {
|
||||
public constructor(instruction: string) {
|
||||
super("w:instrText");
|
||||
this.root.push(new NextAttributeComponent({ space: { key: "xml:space", value: "preserve" } }));
|
||||
this.root.push(instruction);
|
||||
}
|
||||
}
|
||||
|
||||
const fieldChar = (type: "begin" | "separate" | "end"): XmlComponent =>
|
||||
new BuilderElement({
|
||||
name: "w:r",
|
||||
children: [
|
||||
new BuilderElement<{ readonly type: string }>({
|
||||
name: "w:fldChar",
|
||||
attributes: { type: { key: "w:fldCharType", value: type } },
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
/**
|
||||
* A field whose result has been worked out, as runs: its start, its instruction, the result, and its end.
|
||||
*
|
||||
* @param result - The result's runs, between the field's separator and its end
|
||||
*/
|
||||
export const createFieldRuns = (instruction: string, result: readonly XmlComponent[]): readonly XmlComponent[] => [
|
||||
fieldChar("begin"),
|
||||
new BuilderElement({ name: "w:r", children: [new FieldInstruction(instruction)] }),
|
||||
fieldChar("separate"),
|
||||
...result,
|
||||
fieldChar("end"),
|
||||
];
|
||||
@@ -0,0 +1,172 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { markupOf, testStyle } from "tests/bibliography";
|
||||
|
||||
import { type CitedSourceOptions, citationOrderOf, formatBibliography, formatCitation } from "./format";
|
||||
import type { Person, Source } from "./source";
|
||||
import { wordSourceOf } from "./word-source";
|
||||
|
||||
const person = (lastName: string, firstName = "A", middleName?: string): Person => ({ lastName, firstName, middleName });
|
||||
|
||||
const book = (tag: string, authors?: readonly Person[], other: Partial<Source> = {}): Source => ({ tag, type: "book", authors, ...other });
|
||||
|
||||
/** The citation of the source with the test style, which writes the flags Word works out for it */
|
||||
const cite = (sources: readonly Source[], cited: CitedSourceOptions | readonly CitedSourceOptions[]): string =>
|
||||
markupOf(
|
||||
formatCitation(
|
||||
testStyle(),
|
||||
sources.map((source, index) => wordSourceOf(source, index + 1)),
|
||||
Array.isArray(cited) ? cited : [cited as CitedSourceOptions],
|
||||
),
|
||||
);
|
||||
|
||||
describe("formatCitation", () => {
|
||||
it("writes each source of the citation in turn, the first and the last as such", () => {
|
||||
const sources = [book("A"), book("B"), book("C")];
|
||||
|
||||
expect(cite(sources, { source: "A" })).to.equal("(A)");
|
||||
expect(cite(sources, [{ source: "A" }, { source: "B" }, { source: "C" }])).to.equal("(A; B; C)");
|
||||
});
|
||||
|
||||
it("gives the style how each source is cited", () => {
|
||||
expect(
|
||||
cite([book("A")], {
|
||||
source: "A",
|
||||
pages: "5",
|
||||
volume: "2",
|
||||
prefix: "see ",
|
||||
suffix: " (n. 2)",
|
||||
hideAuthor: true,
|
||||
hideYear: true,
|
||||
hideTitle: true,
|
||||
}),
|
||||
).to.equal("(see A, no author, no year, no title, p. 5, vol. 2 (n. 2))");
|
||||
});
|
||||
|
||||
it("reads each source's text as Word reads a style's HTML, without the spaces at its start, and joins them", () => {
|
||||
const style = testStyle();
|
||||
const sources = [wordSourceOf(book("A"), 1)];
|
||||
|
||||
expect(
|
||||
formatCitation({ ...style, citation: (cited) => [{ text: cited.first ? " (A 1" : " B) " }] }, sources, [
|
||||
{ source: "A" },
|
||||
{ source: "A" },
|
||||
]),
|
||||
).to.deep.equal([{ text: "(A 1B) " }]);
|
||||
});
|
||||
|
||||
it("throws for a source that isn't one of the bibliography's", () => {
|
||||
expect(() => cite([book("A"), book("B")], { source: "C" })).toThrow(
|
||||
'A citation cites the source "C", which isn\'t one of the bibliography\'s sources. Its sources\' tags are "A", "B"',
|
||||
);
|
||||
});
|
||||
|
||||
describe("what Word works out to tell the source apart", () => {
|
||||
it("gives a source's title when another has the same first author, of three or fewer authors", () => {
|
||||
const sources = [
|
||||
book("A", [person("Lee")]),
|
||||
book("B", [person("Lee"), person("Ray")]),
|
||||
book("C", [person("Quinn"), person("Lee")]),
|
||||
];
|
||||
|
||||
expect(cite(sources, { source: "A" })).to.equal("(A, repeated, 2 authors)");
|
||||
expect(cite(sources, { source: "B" })).to.equal("(B, repeated, 2 authors)");
|
||||
expect(cite(sources, { source: "C" })).to.equal("(C)");
|
||||
});
|
||||
|
||||
it("compares the first three authors of a source of more than three", () => {
|
||||
const four = [person("A"), person("B"), person("C"), person("D")];
|
||||
const sources = [
|
||||
book("Four", four),
|
||||
book("SameThree", [...four.slice(0, 3), person("E")]),
|
||||
book("FirstTwo", four.slice(0, 2)),
|
||||
book("Other", [person("A"), person("X"), person("Y"), person("Z")]),
|
||||
];
|
||||
|
||||
expect(cite(sources, { source: "Four" })).to.equal("(Four, repeated, 2 authors)");
|
||||
expect(cite(sources, { source: "FirstTwo" })).to.equal("(FirstTwo, repeated, 2 authors)");
|
||||
expect(cite(sources, { source: "Other" })).to.equal("(Other, 2 authors)");
|
||||
});
|
||||
|
||||
it("counts how many authors tell a source apart, from the most it shares with another", () => {
|
||||
const sources = [
|
||||
book("A", [person("A"), person("B"), person("C"), person("D")]),
|
||||
book("B", [person("A"), person("B"), person("X"), person("Y")]),
|
||||
];
|
||||
|
||||
expect(cite(sources, { source: "A" })).to.equal("(A, 3 authors)");
|
||||
});
|
||||
|
||||
it("gives initials when another source's first author has the same last name but is someone else", () => {
|
||||
const sources = [
|
||||
book("A", [person("Lee", "Ann")]),
|
||||
book("B", [person("Lee", "Bob")]),
|
||||
book("C", [person("Ray"), person("Lee", "Ann")]),
|
||||
];
|
||||
|
||||
expect(cite(sources, { source: "A" })).to.equal("(A, initials)");
|
||||
expect(cite(sources, { source: "C" })).to.equal("(C)");
|
||||
expect(cite([book("A", [person("Lee", "Ann")]), book("B", [person("Lee", "Ann", "Kay")])], { source: "A" })).to.equal(
|
||||
"(A, initials)",
|
||||
);
|
||||
});
|
||||
|
||||
it("compares the people a type of source is named by", () => {
|
||||
const sources: readonly Source[] = [
|
||||
book("Book", undefined, { editors: [person("Lee")] }),
|
||||
{ tag: "Song", type: "soundRecording", conductors: [person("Lee")] },
|
||||
{ tag: "Film", type: "film", writers: [person("Lee")] },
|
||||
{ tag: "Case", type: "case", authors: [person("Lee")] },
|
||||
];
|
||||
|
||||
expect(cite(sources, { source: "Book" })).to.equal("(Book, repeated, 2 authors)");
|
||||
expect(cite(sources, { source: "Song" })).to.equal("(Song, repeated, 2 authors)");
|
||||
expect(cite(sources, { source: "Case" })).to.equal("(Case)");
|
||||
});
|
||||
|
||||
it("doesn't compare sources named by an organization, or by nobody", () => {
|
||||
const sources = [
|
||||
book("A", undefined, { corporateAuthor: "Board" }),
|
||||
book("B", undefined, { corporateAuthor: "Board" }),
|
||||
book("C"),
|
||||
];
|
||||
|
||||
expect(cite(sources, { source: "A" })).to.equal("(A)");
|
||||
expect(cite(sources, { source: "C" })).to.equal("(C)");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("citationOrderOf", () => {
|
||||
it("numbers the sources cited in the order they're first cited, then the others in the order they're listed", () => {
|
||||
expect([...citationOrderOf(["A", "B", "C", "D"], ["C", "A", "C", "X"])]).to.deep.equal([
|
||||
["C", 1],
|
||||
["A", 2],
|
||||
["B", 3],
|
||||
["D", 4],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatBibliography", () => {
|
||||
const sources = [wordSourceOf(book("B", undefined, { title: " Two " }), 1), wordSourceOf(book("A", undefined, { title: "One" }), 2)];
|
||||
|
||||
it("writes the style's paragraphs, each read as Word reads a style's HTML", () => {
|
||||
expect(formatBibliography(testStyle(), sources)).to.deep.equal({
|
||||
paragraphs: [
|
||||
[{ text: "A " }, { text: "One", italics: true }, { text: " " }],
|
||||
[{ text: "B " }, { text: "Two ", italics: true }],
|
||||
],
|
||||
hangingIndent: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("writes the style's table, each cell read as Word reads a style's HTML", () => {
|
||||
expect(formatBibliography(testStyle("rows"), sources)).to.deep.equal({
|
||||
rows: [
|
||||
[[{ text: "[2] " }], [{ text: "A " }, { text: "One", italics: true }, { text: " " }]],
|
||||
[[{ text: "[1] " }], [{ text: "B " }, { text: "Two ", italics: true }]],
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* Writes citations and bibliographies with a style of citation, as Word does when it updates a document's fields: it
|
||||
* works out what each source cited needs to be told apart from the others, and gives the style each source of a
|
||||
* citation in turn.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type FormattedText, join, mergeRuns, readAsWord } from "./styles/formatted-text";
|
||||
import type { CitedSource, FormattedBibliography, StyleDefinition } from "./styles/style";
|
||||
import { type Role, type WordPerson, type WordSource, type WordSourceType } from "./word-source";
|
||||
|
||||
/**
|
||||
* A source a citation cites, and how: the pages or volume it cites, text before or after it, and what it leaves out.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export type CitedSourceOptions = {
|
||||
/** The tag of the source cited, such as "Dic06" */
|
||||
readonly source: string;
|
||||
/** The pages cited, such as "50" or "50-62", which most styles write as "p. 50" or "pp. 50-62" */
|
||||
readonly pages?: string;
|
||||
/** The volume cited, such as "2" */
|
||||
readonly volume?: string;
|
||||
/** Text before the source, such as "see " */
|
||||
readonly prefix?: string;
|
||||
/** Text after the source, such as ", emphasis added" */
|
||||
readonly suffix?: string;
|
||||
/** Leaves out the source's authors, such as when they're named in the text */
|
||||
readonly hideAuthor?: boolean;
|
||||
/** Leaves out the source's year */
|
||||
readonly hideYear?: boolean;
|
||||
/** Leaves out the source's title, for the styles that write it */
|
||||
readonly hideTitle?: boolean;
|
||||
};
|
||||
|
||||
// The roles whose people a style names a source by, in the order it looks for them, by type of source: Word's
|
||||
// MainContributors. Word compares the people of these roles to tell sources apart
|
||||
const MAIN_ROLES: Readonly<Record<WordSourceType, readonly Role[]>> = {
|
||||
Book: ["Author", "Editor"],
|
||||
BookSection: ["Author"],
|
||||
JournalArticle: ["Author", "Editor"],
|
||||
ArticleInAPeriodical: ["Author", "Editor"],
|
||||
ConferenceProceedings: ["Author", "Editor"],
|
||||
Report: ["Author"],
|
||||
SoundRecording: ["Composer", "Performer", "Conductor"],
|
||||
Performance: ["Writer", "Director", "Performer"],
|
||||
Art: ["Artist"],
|
||||
DocumentFromInternetSite: ["Author", "Editor"],
|
||||
InternetSite: ["Author", "Editor"],
|
||||
Film: ["ProducerName", "Writer", "Director"],
|
||||
Interview: ["Interviewee", "Editor", "Translator"],
|
||||
Patent: ["Inventor"],
|
||||
ElectronicSource: ["Author", "Editor"],
|
||||
Case: [],
|
||||
Misc: ["Author", "Editor"],
|
||||
};
|
||||
|
||||
/** The people a source is named by, or none when it is named by an organization or has no one in those roles */
|
||||
const mainPeopleOf = (source: WordSource): readonly WordPerson[] => {
|
||||
for (const role of MAIN_ROLES[source.type]) {
|
||||
const names = source.names[role];
|
||||
if (names) {
|
||||
return "people" in names ? names.people : [];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
const isSamePerson = (a: WordPerson, b: WordPerson): boolean => a.last === b.last && a.first === b.first && a.middle === b.middle;
|
||||
|
||||
/** How many of their first people two lists of people have in common */
|
||||
const commonPeople = (a: readonly WordPerson[], b: readonly WordPerson[]): number => {
|
||||
let count = 0;
|
||||
while (count < a.length && count < b.length && isSamePerson(a[count], b[count])) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
};
|
||||
|
||||
/**
|
||||
* What Word works out from a document's sources to tell a source apart in its citations: whether another source has
|
||||
* the same first author, or the same first three when it has more than three, whether another source's first author
|
||||
* has the same last name but is someone else, and how many of its authors tell it apart. Sources named by an
|
||||
* organization, or by nobody, aren't compared.
|
||||
*/
|
||||
const flagsOf = (
|
||||
source: WordSource,
|
||||
sources: readonly WordSource[],
|
||||
): Pick<CitedSource, "repeatedAuthor" | "nonUniqueLastName" | "minAuthors"> => {
|
||||
const people = mainPeopleOf(source);
|
||||
if (people.length === 0) {
|
||||
return { repeatedAuthor: false, nonUniqueLastName: false, minAuthors: 1 };
|
||||
}
|
||||
const others = sources
|
||||
.filter((other) => other !== source)
|
||||
.map(mainPeopleOf)
|
||||
.filter((other) => other.length > 0);
|
||||
const compared = people.length > 3 ? 3 : 1;
|
||||
const repeatedAuthor = others.some((other) => other.length >= compared && commonPeople(people, other) >= compared);
|
||||
const nonUniqueLastName = others.some((other) => other[0].last === people[0].last && !isSamePerson(other[0], people[0]));
|
||||
// A source whose authors don't tell it apart has its title in the citation, and two of its authors in Chicago's
|
||||
const minAuthors = repeatedAuthor ? 2 : Math.max(1, ...others.map((other) => commonPeople(people, other) + 1));
|
||||
return { repeatedAuthor, nonUniqueLastName, minAuthors };
|
||||
};
|
||||
|
||||
/**
|
||||
* Where each source is in the order the document cites them in, from 1, as Word numbers them (`b:RefOrder`): the
|
||||
* sources cited, in the order they're first cited, then the others in the order they're listed in.
|
||||
*
|
||||
* @param tags - The tags of the sources the document cites, in the order it cites them
|
||||
*/
|
||||
export const citationOrderOf = (sourceTags: readonly string[], citedTags: readonly string[]): ReadonlyMap<string, number> => {
|
||||
const order = new Map<string, number>();
|
||||
for (const tag of [...citedTags, ...sourceTags]) {
|
||||
if (!order.has(tag) && sourceTags.includes(tag)) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
order.set(tag, order.size + 1);
|
||||
}
|
||||
}
|
||||
return order;
|
||||
};
|
||||
|
||||
/**
|
||||
* A citation of one or more sources, as the style writes it: each source in turn, each read as Word reads a style's
|
||||
* HTML.
|
||||
*
|
||||
* @throws If a source cited isn't one of the sources
|
||||
*/
|
||||
export const formatCitation = (
|
||||
style: StyleDefinition,
|
||||
sources: readonly WordSource[],
|
||||
cited: readonly CitedSourceOptions[],
|
||||
): FormattedText =>
|
||||
mergeRuns(
|
||||
join(
|
||||
...cited.map((options, index) => {
|
||||
const source = sources.find((candidate) => candidate.tag === options.source);
|
||||
if (!source) {
|
||||
throw new Error(
|
||||
`A citation cites the source "${options.source}", which isn't one of the bibliography's sources. Its sources' tags are ${sources
|
||||
.map(({ tag }) => `"${tag}"`)
|
||||
.join(", ")}`,
|
||||
);
|
||||
}
|
||||
return readAsWord(
|
||||
style.citation({
|
||||
source,
|
||||
first: index === 0,
|
||||
last: index === cited.length - 1,
|
||||
...flagsOf(source, sources),
|
||||
hideAuthor: !!options.hideAuthor,
|
||||
hideYear: !!options.hideYear,
|
||||
hideTitle: !!options.hideTitle,
|
||||
pages: options.pages ?? "",
|
||||
volume: options.volume ?? "",
|
||||
prefix: options.prefix,
|
||||
suffix: options.suffix,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
/** A bibliography of the sources, as the style writes it, with each paragraph and cell read as Word reads a style's HTML */
|
||||
export const formatBibliography = (style: StyleDefinition, sources: readonly WordSource[]): FormattedBibliography => {
|
||||
const bibliography = style.bibliography(sources);
|
||||
return "rows" in bibliography
|
||||
? { rows: bibliography.rows.map(([label, entry]) => [readAsWord(label), readAsWord(entry)] as const) }
|
||||
: { paragraphs: bibliography.paragraphs.map(readAsWord), hangingIndent: bibliography.hangingIndent };
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Citations and bibliographies for docx documents: the sources a document refers to, such as books, articles and
|
||||
* websites, citations of them in its text, such as "(Baker, 2010)", and a bibliography that lists them, in one of Word's
|
||||
* styles of citation, such as APA, MLA or Chicago, as Word's References > Citations & Bibliography writes them.
|
||||
*
|
||||
* Each citation and bibliography is written as Word writes it, so it looks the same in any app, and Word writes it again
|
||||
* when it updates the document's fields, or when its style is changed in References > Style.
|
||||
*
|
||||
* Citations and bibliographies come with the `docx` package, from `docx/bibliography`. Everything else, such as the
|
||||
* document and its paragraphs, comes from `docx`. The sources go in the document's `bibliography`.
|
||||
*
|
||||
* @module
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Document, Packer, Paragraph, TextRun } from "docx";
|
||||
* import { Bibliography, Citation, CitationStyle, SourceType, createBibliography } from "docx/bibliography";
|
||||
*
|
||||
* const doc = new Document({
|
||||
* bibliography: createBibliography({
|
||||
* style: CitationStyle.APA,
|
||||
* sources: [
|
||||
* {
|
||||
* tag: "Bak10",
|
||||
* type: SourceType.BOOK,
|
||||
* authors: [{ lastName: "Baker", firstName: "Anna" }],
|
||||
* title: "The Art of Pizza",
|
||||
* year: 2010,
|
||||
* city: "Naples",
|
||||
* publisher: "Oven Press",
|
||||
* },
|
||||
* ],
|
||||
* }),
|
||||
* sections: [
|
||||
* {
|
||||
* children: [
|
||||
* new Paragraph({ children: [new TextRun("Pizza is older than it seems "), new Citation("Bak10")] }),
|
||||
* new Bibliography({ title: "References" }),
|
||||
* ],
|
||||
* },
|
||||
* ],
|
||||
* });
|
||||
*
|
||||
* const buffer = await Packer.toBuffer(doc);
|
||||
* ```
|
||||
*/
|
||||
export { Bibliography, type BibliographyOptions } from "./bibliography";
|
||||
export { Citation } from "./citation";
|
||||
export { CitationStyle } from "./citation-style";
|
||||
export { type DocumentBibliographyOptions, createBibliography } from "./create-bibliography";
|
||||
export { type CitedSourceOptions } from "./format";
|
||||
export { type Person, type Source, SourceType } from "./source";
|
||||
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* The sources that a document's citations and bibliographies refer to, as Word's Create Source dialog describes them.
|
||||
*
|
||||
* Reference: ooxml-schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
/**
|
||||
* The kinds of source Word's Create Source dialog has. Each has the fields Word asks for when it's chosen, though any
|
||||
* source can have any field. Word's own name for each, as it writes it in the document, is in brackets.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export const SourceType = {
|
||||
/** A book (`Book`) */
|
||||
BOOK: "book",
|
||||
/** A chapter or other part of a book, with its own title and authors (`BookSection`) */
|
||||
BOOK_SECTION: "bookSection",
|
||||
/** An article in a journal (`JournalArticle`) */
|
||||
JOURNAL_ARTICLE: "journalArticle",
|
||||
/** An article in a magazine or a newspaper (`ArticleInAPeriodical`) */
|
||||
ARTICLE_IN_A_PERIODICAL: "articleInAPeriodical",
|
||||
/** A paper in the proceedings of a conference (`ConferenceProceedings`) */
|
||||
CONFERENCE_PROCEEDINGS: "conferenceProceedings",
|
||||
/** A report or a thesis (`Report`) */
|
||||
REPORT: "report",
|
||||
/** A page of a website (`InternetSite`) */
|
||||
WEBSITE: "website",
|
||||
/** A document on a website, such as a PDF (`DocumentFromInternetSite`) */
|
||||
DOCUMENT_FROM_WEBSITE: "documentFromWebsite",
|
||||
/** A source on a medium other than paper, such as a CD-ROM or a database (`ElectronicSource`) */
|
||||
ELECTRONIC_SOURCE: "electronicSource",
|
||||
/** A work of art (`Art`) */
|
||||
ART: "art",
|
||||
/** A recording of music or of speech (`SoundRecording`) */
|
||||
SOUND_RECORDING: "soundRecording",
|
||||
/** A play, a concert or another performance (`Performance`) */
|
||||
PERFORMANCE: "performance",
|
||||
/** A film (`Film`) */
|
||||
FILM: "film",
|
||||
/** An interview (`Interview`) */
|
||||
INTERVIEW: "interview",
|
||||
/** A patent (`Patent`) */
|
||||
PATENT: "patent",
|
||||
/** A court case (`Case`) */
|
||||
CASE: "case",
|
||||
/** Any other source (`Misc`) */
|
||||
MISCELLANEOUS: "miscellaneous",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* A person who made a source, such as one of its authors, by their names as Word's Edit Name dialog has them.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export type Person = {
|
||||
/** The person's last name, such as "Dickens". Initials are written from the first letter of each part of a name */
|
||||
readonly lastName: string;
|
||||
/** The person's first name, such as "Charles" */
|
||||
readonly firstName?: string;
|
||||
/** The person's middle name or names, such as "John" */
|
||||
readonly middleName?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A source, such as a book or a website, that a document's citations and bibliographies refer to. Its `tag` is how a
|
||||
* `Citation` names it.
|
||||
*
|
||||
* Every field is text as Word keeps it, and each style of citation writes it as it's given: a month such as "March",
|
||||
* pages such as "50-62", and an edition such as "2nd". Which fields a style writes depends on the type of the source, and
|
||||
* each field's description says which types of source Word asks for it with.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export type Source = {
|
||||
/**
|
||||
* The name that citations refer to the source by, which Word calls its tag name, such as "Dic06". It is unique among
|
||||
* the document's sources
|
||||
*/
|
||||
readonly tag: string;
|
||||
/** The kind of source, such as a book or a website */
|
||||
readonly type: (typeof SourceType)[keyof typeof SourceType];
|
||||
|
||||
/** The authors, in order. A book or an article written by an organization has a `corporateAuthor` instead */
|
||||
readonly authors?: readonly Person[];
|
||||
/** An organization that wrote the source, such as "World Health Organization", in place of its `authors` */
|
||||
readonly corporateAuthor?: string;
|
||||
/** The editors */
|
||||
readonly editors?: readonly Person[];
|
||||
/** The translators */
|
||||
readonly translators?: readonly Person[];
|
||||
/** The authors of the book that a book section is in */
|
||||
readonly bookAuthors?: readonly Person[];
|
||||
/** The compilers, of an interview or a miscellaneous source */
|
||||
readonly compilers?: readonly Person[];
|
||||
/** The artists, of a work of art or a sound recording */
|
||||
readonly artists?: readonly Person[];
|
||||
/** The composers, of a sound recording */
|
||||
readonly composers?: readonly Person[];
|
||||
/** The conductors, of a sound recording */
|
||||
readonly conductors?: readonly Person[];
|
||||
/** The performers, of a sound recording, a performance or a film */
|
||||
readonly performers?: readonly Person[];
|
||||
/** A band or another group that performed a sound recording, in place of its `performers` */
|
||||
readonly corporatePerformer?: string;
|
||||
/** The writers, of a performance or a film */
|
||||
readonly writers?: readonly Person[];
|
||||
/** The directors, of a performance or a film */
|
||||
readonly directors?: readonly Person[];
|
||||
/** The producers, of a website, an electronic source, a sound recording, a performance or a film */
|
||||
readonly producers?: readonly Person[];
|
||||
/** The people interviewed, in an interview */
|
||||
readonly interviewees?: readonly Person[];
|
||||
/** The interviewers, of an interview */
|
||||
readonly interviewers?: readonly Person[];
|
||||
/** The inventors, of a patent */
|
||||
readonly inventors?: readonly Person[];
|
||||
/** The counsel, in a court case */
|
||||
readonly counsel?: readonly Person[];
|
||||
|
||||
/** The source's title, or the name of a web page, such as "How to Write Bibliographies" */
|
||||
readonly title?: string;
|
||||
/** A shorter title, which some styles cite the source by, such as "Bibliographies" */
|
||||
readonly shortTitle?: string;
|
||||
/** The title of the book that a book section is in */
|
||||
readonly bookTitle?: string;
|
||||
/** The name of the journal that a journal article is in */
|
||||
readonly journalName?: string;
|
||||
/** The title of the magazine or newspaper that an article in a periodical is in */
|
||||
readonly periodicalTitle?: string;
|
||||
/** The name of the conference's publication, for a paper in conference proceedings */
|
||||
readonly conferenceName?: string;
|
||||
/** The name of the website a page or a document is on, such as "Pizza School" */
|
||||
readonly websiteName?: string;
|
||||
/** The title of the publication that an electronic source, a work of art or a miscellaneous source is in */
|
||||
readonly publicationTitle?: string;
|
||||
/** The title of the album that a sound recording is on */
|
||||
readonly albumTitle?: string;
|
||||
/** The title of the broadcast that an interview was on */
|
||||
readonly broadcastTitle?: string;
|
||||
|
||||
/** The year the source was published, such as "2006" */
|
||||
readonly year?: string | number;
|
||||
/** The month the source was published, such as "March" */
|
||||
readonly month?: string;
|
||||
/** The day of the month the source was published */
|
||||
readonly day?: string | number;
|
||||
/** The year a website or a document on one was read */
|
||||
readonly yearAccessed?: string | number;
|
||||
/** The month a website or a document on one was read, such as "March" */
|
||||
readonly monthAccessed?: string;
|
||||
/** The day of the month a website or a document on one was read */
|
||||
readonly dayAccessed?: string | number;
|
||||
|
||||
/** The city it was published in, or for a court case, where the case was published */
|
||||
readonly city?: string;
|
||||
/** The state or province it was published in, such as "Illinois" */
|
||||
readonly stateOrProvince?: string;
|
||||
/** The country or region it was published in, or for a patent, the country it was granted in */
|
||||
readonly countryOrRegion?: string;
|
||||
/** The publisher, such as "Adventure Works Press" */
|
||||
readonly publisher?: string;
|
||||
/** The company that produced a website, an electronic source, a sound recording, a performance or a film */
|
||||
readonly productionCompany?: string;
|
||||
/** The company that distributed a film */
|
||||
readonly distributor?: string;
|
||||
/** The institution a report or a work of art is from */
|
||||
readonly institution?: string;
|
||||
/** The department of the institution a report is from */
|
||||
readonly department?: string;
|
||||
/** The kind of report, such as "Technical report" or "PhD thesis" */
|
||||
readonly reportType?: string;
|
||||
|
||||
/** The edition, such as "2nd" */
|
||||
readonly edition?: string;
|
||||
/** The volume, such as "III" */
|
||||
readonly volume?: string | number;
|
||||
/** How many volumes there are, such as "4" */
|
||||
readonly numberOfVolumes?: string | number;
|
||||
/** The issue of a journal or a periodical */
|
||||
readonly issue?: string | number;
|
||||
/** The pages, such as "50-62" */
|
||||
readonly pages?: string;
|
||||
/** The medium, such as "CD-ROM", "DVD" or "Manuscript" */
|
||||
readonly medium?: string;
|
||||
/** The version of a website or a document on one */
|
||||
readonly version?: string;
|
||||
/** A standard number, such as an ISBN or an ISSN */
|
||||
readonly standardNumber?: string;
|
||||
/** The address of a website or a document on one */
|
||||
readonly url?: string;
|
||||
|
||||
/** The number a sound recording was released under */
|
||||
readonly recordingNumber?: string;
|
||||
/** The theater a performance was at */
|
||||
readonly theater?: string;
|
||||
/** The broadcaster an interview was on */
|
||||
readonly broadcaster?: string;
|
||||
/** The station an interview was broadcast on */
|
||||
readonly station?: string;
|
||||
/** The kind of patent, such as "Utility patent" */
|
||||
readonly patentType?: string;
|
||||
/** The patent's number */
|
||||
readonly patentNumber?: string;
|
||||
/** The number of a court case */
|
||||
readonly caseNumber?: string;
|
||||
/** The abbreviated number of a court case, such as "567 U.S. 1" */
|
||||
readonly abbreviatedCaseNumber?: string;
|
||||
/** The court that heard a case */
|
||||
readonly court?: string;
|
||||
/** The reporter a court case is published in, such as "U.S. Reports" */
|
||||
readonly reporter?: string;
|
||||
/** Comments, which some styles write at the end of the source's entry */
|
||||
readonly comments?: string;
|
||||
};
|
||||
@@ -0,0 +1,248 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type CorpusOutput, describeWordOutput, outputOf } from "tests/bibliography";
|
||||
|
||||
import { apa } from "./apa";
|
||||
import type { CitedSourceOptions } from "../format";
|
||||
import type { Source } from "../source";
|
||||
import expected from "./fixtures/apa.json";
|
||||
|
||||
// Sources none of the corpora have, which take the style down paths it has for them. What Word's style writes for each
|
||||
// is from running Word's own XSL with libxslt and Word's English wording, as corpus s is
|
||||
const CASES: readonly {
|
||||
readonly name: string;
|
||||
readonly sources: readonly Source[];
|
||||
readonly citations: readonly (readonly CitedSourceOptions[])[];
|
||||
readonly expected: Required<CorpusOutput>;
|
||||
}[] = [
|
||||
{
|
||||
name: "a performance by an organization, with its writer",
|
||||
sources: [
|
||||
{
|
||||
tag: "P1",
|
||||
type: "performance",
|
||||
writers: [{ lastName: "Nash", firstName: "Leo" }],
|
||||
corporatePerformer: "The Ovens",
|
||||
title: "Opera",
|
||||
year: "2012",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "P1" }]],
|
||||
expected: {
|
||||
citations: ["(Nash, 2012)"],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["Nash, L. (2012). <i>Opera.</i> (The Ovens, Performer)"] },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a film with several producers, writers and directors",
|
||||
sources: [
|
||||
{
|
||||
tag: "F1",
|
||||
type: "film",
|
||||
directors: [
|
||||
{ lastName: "Cruz", firstName: "Pedro" },
|
||||
{ lastName: "Fox", firstName: "Nick" },
|
||||
],
|
||||
producers: [
|
||||
{ lastName: "Webb", firstName: "Lou" },
|
||||
{ lastName: "Hart", firstName: "Sue" },
|
||||
],
|
||||
writers: [
|
||||
{ lastName: "Ortiz", firstName: "Raul" },
|
||||
{ lastName: "Lane", firstName: "Mia" },
|
||||
],
|
||||
title: "Deep Dish",
|
||||
year: "2011",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "F1" }]],
|
||||
expected: {
|
||||
citations: ["(Webb & Hart, 2011)"],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: [
|
||||
"Webb, L., Hart, S. (Producers), Ortiz, R., Lane, M. (Writers), Cruz, P., & Fox, N. (Directors). (2011). <i>Deep Dish</i> [Motion Picture].",
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a film with a title and nobody who made it",
|
||||
sources: [{ tag: "F2", type: "film", performers: [{ lastName: "Banks", firstName: "Amy" }], title: "Deep Dish", year: "2011" }],
|
||||
citations: [[{ source: "F2" }]],
|
||||
expected: {
|
||||
citations: ["(Deep Dish, 2011)"],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["<i>Deep Dish</i> (2011). [Motion Picture]."] },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a website read on a date, with no name or address",
|
||||
sources: [{ tag: "W1", type: "website", title: "Page", yearAccessed: "2022", monthAccessed: "May", dayAccessed: "3" }],
|
||||
citations: [[{ source: "W1" }]],
|
||||
expected: {
|
||||
citations: ["(Page, n.d.)"],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["<i>Page</i>. (n.d.). Retrieved May 3, 2022"] },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a citation of pages alone",
|
||||
sources: [{ tag: "B1", type: "book", authors: [{ lastName: "Baker", firstName: "Anna" }], title: "Pizza", year: "2010" }],
|
||||
citations: [
|
||||
[{ source: "B1", pages: "5", hideAuthor: true, hideYear: true, hideTitle: true }],
|
||||
[{ source: "B1", volume: "2-3", hideAuthor: true, hideYear: true, hideTitle: true }],
|
||||
],
|
||||
expected: {
|
||||
citations: ["(p. 5)", "(vols. 2-3)"],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["Baker, A. (2010). <i>Pizza.</i> "] },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "books in several volumes",
|
||||
sources: [
|
||||
{ tag: "B2", type: "book", authors: [{ lastName: "Baker", firstName: "Anna" }], title: "Pizza", year: "2010", volume: "2-3" },
|
||||
{ tag: "B3", type: "book", authors: [{ lastName: "Baker", firstName: "Anna" }], title: "Bread", year: "2011", volume: "2, 4" },
|
||||
],
|
||||
citations: [],
|
||||
expected: {
|
||||
citations: [],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: ["Baker, A. (2010). <i>Pizza</i> (Vols. 2-3).", "Baker, A. (2011). <i>Bread</i> (Vols. 2, 4)."],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a performance with several directors and no writer",
|
||||
sources: [
|
||||
{
|
||||
tag: "P2",
|
||||
type: "performance",
|
||||
directors: [
|
||||
{ lastName: "Page", firstName: "Tim" },
|
||||
{ lastName: "Holt", firstName: "Eve" },
|
||||
],
|
||||
title: "Opera",
|
||||
year: "2012",
|
||||
},
|
||||
],
|
||||
citations: [],
|
||||
expected: {
|
||||
citations: [],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["Page, T., & Holt, E. (Directors). (2012). <i>Opera.</i> "] },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "book sections with a volume or pages and nothing else of the book",
|
||||
sources: [
|
||||
{
|
||||
tag: "S1",
|
||||
type: "bookSection",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
title: "Starters",
|
||||
bookTitle: "Menus",
|
||||
year: "2023",
|
||||
volume: "2",
|
||||
},
|
||||
{
|
||||
tag: "S2",
|
||||
type: "bookSection",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
title: "Mains",
|
||||
bookTitle: "Menus",
|
||||
year: "2024",
|
||||
volume: "2-3",
|
||||
},
|
||||
{
|
||||
tag: "S3",
|
||||
type: "bookSection",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
title: "Desserts",
|
||||
bookTitle: "Menus",
|
||||
year: "2025",
|
||||
pages: "5",
|
||||
},
|
||||
],
|
||||
citations: [],
|
||||
expected: {
|
||||
citations: [],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: [
|
||||
"Fox, A. (2023). Starters. In <i>Menus</i> (Vol. 2).",
|
||||
"Fox, A. (2024). Mains. In <i>Menus</i> (Vols. 2-3).",
|
||||
"Fox, A. (2025). Desserts. In <i>Menus</i> (p. 5).",
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "conference proceedings with no authors or editors",
|
||||
sources: [
|
||||
{
|
||||
tag: "C1",
|
||||
type: "conferenceProceedings",
|
||||
title: "Ovens",
|
||||
conferenceName: "Bake Con",
|
||||
year: "2017",
|
||||
city: "Milan",
|
||||
publisher: "IPC",
|
||||
volume: "1",
|
||||
},
|
||||
{
|
||||
tag: "C2",
|
||||
type: "conferenceProceedings",
|
||||
title: "Ovens",
|
||||
conferenceName: "Bake Con",
|
||||
year: "2017",
|
||||
city: "Milan",
|
||||
volume: "1",
|
||||
pages: "5-9",
|
||||
},
|
||||
{ tag: "C3", type: "conferenceProceedings", conferenceName: "Bake Con", publisher: "IPC", pages: "5-9" },
|
||||
],
|
||||
citations: [],
|
||||
expected: {
|
||||
citations: [],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: [
|
||||
"(n.d.). <i>Bake Con</i> (pp. 5-9). IPC.",
|
||||
"Ovens. (2017). <i>Bake Con.</i> <i>1.</i> Milan: IPC.",
|
||||
"Ovens. (2017). <i>Bake Con</i>, <i>1</i>, pp. 5-9. Milan.",
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a case with a court alone",
|
||||
sources: [{ tag: "K1", type: "case", court: "Supreme Court" }],
|
||||
citations: [],
|
||||
expected: { citations: [], bibliography: { hangingIndent: true, paragraphs: ["(Supreme Court)."] } },
|
||||
},
|
||||
{
|
||||
name: "art with a publication's title alone, and with an institution alone",
|
||||
sources: [
|
||||
{ tag: "A1", type: "art", publicationTitle: "Food in Art" },
|
||||
{ tag: "A2", type: "art", city: "Seville", institution: "Museum of Food" },
|
||||
],
|
||||
citations: [],
|
||||
expected: {
|
||||
citations: [],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["(n.d.).<i>Food in Art.</i> ", "(n.d.).Museum of Food, Seville."] },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
describe("apa", () => {
|
||||
describeWordOutput(apa, expected);
|
||||
|
||||
for (const { name, sources, citations, expected: output } of CASES) {
|
||||
it(`writes ${name} as Word does`, () => {
|
||||
expect(outputOf(apa, { sources, citations })).toEqual(output);
|
||||
});
|
||||
}
|
||||
|
||||
it("names Word's style", () => {
|
||||
expect(apa).toMatchObject({ name: "APA", file: "APASixthEditionOfficeOnline.xsl", version: "6" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,872 @@
|
||||
/**
|
||||
* APA, sixth edition: Word's `APASixthEditionOfficeOnline.xsl`, written in TypeScript.
|
||||
*
|
||||
* Citations name each source's authors and year, such as "(Baker, 2010)", with the title too when another source has
|
||||
* the same first author. The bibliography lists the sources by author, each with a hanging indent.
|
||||
*
|
||||
* Each function follows the XSL template or variable named in its description, including where that doesn't do what it
|
||||
* looks like it should, so the citations and bibliography are the ones Word writes.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
// The names of the XSL's templates and variables, and Word's own spelling of `PagesCountinousShort`
|
||||
// cspell:words Countinous ensufix JVIP MSXML PTVI PVEP PVIEP RDAFU RIDC
|
||||
import { type FormattedRun, type FormattedText, type TextLike, join, textOf } from "./formatted-text";
|
||||
import { type DatePatterns, LOCALS } from "./locals";
|
||||
import type { CitedSource, StyleDefinition } from "./style";
|
||||
import { applyItalic, sortByKey, translate, xslTemplates } from "./xsl";
|
||||
import { type Field, type Role, type WordNames, type WordPerson, type WordSource, fieldOf } from "../word-source";
|
||||
|
||||
const general = LOCALS.General;
|
||||
const strings = LOCALS.Strings;
|
||||
const style = LOCALS.APA;
|
||||
const xsl = xslTemplates(general);
|
||||
|
||||
// The most authors a citation names before "et al.", and a bibliography's entry before ". . ."
|
||||
const MAX_CITATION_AUTHORS = 5;
|
||||
const MAX_BIBLIOGRAPHY_AUTHORS = 7;
|
||||
|
||||
/**
|
||||
* Where MSXML, Word's XSLT, starts or ends a copy of a variable. Word reads a space there when it is between two
|
||||
* elements, such as two italics, or between an element and the end of the paragraph
|
||||
*/
|
||||
const BOUNDARY: FormattedRun = { text: "" };
|
||||
|
||||
/** A copy of a variable, with its boundaries (`xsl:copy-of select="$variable"`) */
|
||||
const copyOf = (text: TextLike): FormattedText => join([BOUNDARY], text, [BOUNDARY]);
|
||||
|
||||
/** The text as `apply-templates mode="outputHtml"` writes it, which leaves out its copies' boundaries */
|
||||
const withoutBoundaries = (text: TextLike): FormattedText => join(text).filter((run) => run !== BOUNDARY);
|
||||
|
||||
const isElement = (run: FormattedRun): boolean => !!(run.italics || run.bold || run.underline);
|
||||
|
||||
/** The text, with a space where Word reads one at a boundary of a copy, and the boundaries left out */
|
||||
const resolveBoundaries = (text: FormattedText): FormattedText =>
|
||||
text.flatMap((run, index) => {
|
||||
if (run !== BOUNDARY) {
|
||||
return [run];
|
||||
}
|
||||
const written = (other: FormattedRun): boolean => other !== BOUNDARY && other.text.length > 0;
|
||||
const before = text.slice(0, index).filter(written).pop();
|
||||
const after = text.slice(index + 1).find(written);
|
||||
return before && isElement(before) && (!after || isElement(after)) ? [{ text: general.Space }] : [];
|
||||
});
|
||||
|
||||
/** Whether the text has any characters, as `string-length($text) > 0` */
|
||||
const has = (text: TextLike): boolean => textOf(text).length > 0;
|
||||
|
||||
/** The people with a role, or the organization that has it, as Word keeps them */
|
||||
const namesOf = (source: WordSource, role: Role | ""): WordNames | undefined => (role ? source.names[role] : undefined);
|
||||
|
||||
/** The text of the people with a role, or of the organization, as `string-length(b:Author/b:Role)` reads it */
|
||||
const namesText = (names: WordNames | undefined): string =>
|
||||
!names ? "" : "corporate" in names ? names.corporate : names.people.map(({ last, first, middle }) => last + first + middle).join("");
|
||||
|
||||
/** How many people have a role, and none for an organization (`count(b:Author/b:Role/b:NameList/b:Person)`) */
|
||||
const peopleCountOf = (source: WordSource, role: Role): number => {
|
||||
const names = source.names[role];
|
||||
return names && "people" in names ? names.people.length : 0;
|
||||
};
|
||||
|
||||
/** How many people have a role, or 1 for an organization (`count1` of `formatManySecondary`) */
|
||||
const countOf = (names: WordNames | undefined): number => (!names ? 0 : "corporate" in names ? 1 : names.people.length);
|
||||
|
||||
/**
|
||||
* The role whose people a source is named by: its authors, or for some types its editors, composers, writers and so on,
|
||||
* whichever it has first (`MainContributors`)
|
||||
*/
|
||||
const mainContributorsOf = (source: WordSource): Role | "" => {
|
||||
const roles: Readonly<Record<WordSource["type"], readonly Role[]>> = {
|
||||
Book: ["Author", "Editor"],
|
||||
BookSection: ["Author"],
|
||||
JournalArticle: ["Author", "Editor"],
|
||||
ArticleInAPeriodical: ["Author", "Editor"],
|
||||
ConferenceProceedings: ["Author", "Editor"],
|
||||
Report: ["Author"],
|
||||
SoundRecording: ["Composer", "Performer", "Conductor"],
|
||||
Performance: ["Writer", "Director", "Performer"],
|
||||
Art: ["Artist"],
|
||||
DocumentFromInternetSite: ["Author", "Editor"],
|
||||
InternetSite: ["Author", "Editor"],
|
||||
Film: ["ProducerName", "Writer", "Director"],
|
||||
Interview: ["Interviewee", "Editor", "Translator"],
|
||||
Patent: ["Inventor"],
|
||||
ElectronicSource: ["Author", "Editor"],
|
||||
Case: [],
|
||||
Misc: ["Author", "Editor"],
|
||||
};
|
||||
return roles[source.type].find((role) => namesText(source.names[role]).length > 0) ?? "";
|
||||
};
|
||||
|
||||
/** A main author's name, such as "Dickens, C. J." (`formatMainAuthor`) */
|
||||
const formatMainAuthor = (person: WordPerson): string => xsl.formatName(person, style.MainAuthors);
|
||||
|
||||
/** Another person's name, such as "E. Hemingway" (`formatSecondaryName`) */
|
||||
const formatSecondaryName = (person: WordPerson): string => xsl.formatName(person, style.SecondaryAuthors);
|
||||
|
||||
/**
|
||||
* What comes after the person at a position of a list of people: ", " between them, ", & " before the last, unless the
|
||||
* list isn't the last one written, or ". . . " when there are more than seven and the rest are left out
|
||||
* (`formatPersonSeperator`)
|
||||
*
|
||||
* @param position - The person's position, from 1
|
||||
* @param isLast - Whether the list is the last of the lists written, which "&" is before the last person of
|
||||
*/
|
||||
const formatPersonSeperator = (position: number, count: number, isLast = true): string => {
|
||||
let separator = "";
|
||||
if (position === count - 1) {
|
||||
if (count <= MAX_BIBLIOGRAPHY_AUTHORS) {
|
||||
separator += general.AuthorsSeparator + (isLast ? style.BeforeLastAuthor + general.Space : "");
|
||||
} else {
|
||||
separator += (general.Dot + general.Space).repeat(3);
|
||||
}
|
||||
}
|
||||
if (position < count - 1 && position < MAX_BIBLIOGRAPHY_AUTHORS) {
|
||||
separator += general.AuthorsSeparator;
|
||||
}
|
||||
return separator;
|
||||
};
|
||||
|
||||
/** Whether the person at a position is written: the first six, and the last (`position() < $maxBibAuthors or position() = last()`) */
|
||||
const isWritten = (position: number, count: number): boolean => position < MAX_BIBLIOGRAPHY_AUTHORS || position === count;
|
||||
|
||||
/**
|
||||
* People in a list, each written by the format, or the organization (`formatPersonsAuthor`, and with the format of other
|
||||
* people `formatPersons`)
|
||||
*/
|
||||
const formatPersonsWith =
|
||||
(format: (person: WordPerson) => string): ((names: WordNames | undefined) => string) =>
|
||||
(names) =>
|
||||
!names
|
||||
? ""
|
||||
: "corporate" in names
|
||||
? names.corporate
|
||||
: names.people
|
||||
.map(
|
||||
(person, index) =>
|
||||
(isWritten(index + 1, names.people.length) ? format(person) : "") +
|
||||
formatPersonSeperator(index + 1, names.people.length),
|
||||
)
|
||||
.join("");
|
||||
|
||||
/** Main authors, such as "Smith, J., & Jones, M. A." (`formatPersonsAuthor`) */
|
||||
const formatPersonsAuthor = formatPersonsWith(formatMainAuthor);
|
||||
|
||||
/** Other people, such as "E. Hemingway & J. Austen" (`formatPersons`) */
|
||||
const formatPersons = formatPersonsWith(formatSecondaryName);
|
||||
|
||||
/**
|
||||
* People with a role in a list of lists, each written by the format, with "& " before a single person when they are the
|
||||
* last list after others (`formatPersons2`, and with the format of main authors `formatPersonsAuthor2`)
|
||||
*/
|
||||
const formatPersons2With =
|
||||
(format: (person: WordPerson) => string): ((names: WordNames, before: boolean, isLast: boolean) => string) =>
|
||||
(names, before, isLast) => {
|
||||
if ("corporate" in names) {
|
||||
return names.corporate;
|
||||
}
|
||||
const { people } = names;
|
||||
return people
|
||||
.map((person, index) => {
|
||||
const position = index + 1;
|
||||
const and = position === 1 && before && isLast && people.length === 1 ? style.BeforeLastAuthor + general.Space : "";
|
||||
return (
|
||||
and +
|
||||
(isWritten(position, people.length) ? format(person) : "") +
|
||||
formatPersonSeperator(position, people.length, isLast)
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
};
|
||||
|
||||
const formatPersons2 = formatPersons2With(formatSecondaryName);
|
||||
const formatPersonsAuthor2 = formatPersons2With(formatMainAuthor);
|
||||
|
||||
/** One of the lists of people of `formatManySecondary` or `formatManyMain`: its role, and its suffixes for one person or more */
|
||||
type ManyList = { readonly role: Role | ""; readonly single: string; readonly many: string };
|
||||
|
||||
// A list of no one, in place of the second or third list of people
|
||||
const NO_LIST: ManyList & { readonly names?: WordNames } = { role: "", single: "", many: "" };
|
||||
|
||||
/**
|
||||
* Up to three lists of people, each with its suffix, such as "(E. Hemingway, Ed., & J. Austen, Trans.)", in brackets
|
||||
* (`formatManySecondary`). In place of a third list, `special` is text written after the others, after "&"
|
||||
*/
|
||||
const formatManySecondary = (source: WordSource, lists: readonly ManyList[], special = ""): string => {
|
||||
const [first, second = NO_LIST, third = NO_LIST] = lists.map((list) => ({ ...list, names: namesOf(source, list.role) }));
|
||||
const count1 = countOf(first.names);
|
||||
const count2 = countOf(second.names);
|
||||
const count3 = third.role ? countOf(third.names) : special ? 1 : 0;
|
||||
if (count1 + count2 + count3 === 0) {
|
||||
return "";
|
||||
}
|
||||
const suffix = (list: ManyList, count: number): string => (count === 1 ? list.single : list.many);
|
||||
let text = style.GeneralOpen;
|
||||
if (count1 > 0) {
|
||||
text += formatPersons2(first.names!, false, count2 + count3 === 0) + suffix(first, count1);
|
||||
}
|
||||
if (count2 > 0) {
|
||||
text += (count1 > 0 ? general.AuthorsSeparator : "") + formatPersons2(second.names!, count1 > 0, count3 === 0);
|
||||
text += suffix(second, count2);
|
||||
}
|
||||
if (count3 > 0 && !special) {
|
||||
text += (count1 + count2 > 0 ? general.AuthorsSeparator : "") + formatPersons2(third.names!, count1 + count2 > 0, true);
|
||||
text += suffix(third, count3);
|
||||
} else if (special) {
|
||||
text += (count1 + count2 > 0 ? general.AuthorsSeparator + style.BeforeLastAuthor + general.Space : "") + special;
|
||||
}
|
||||
return text + style.GeneralClose;
|
||||
};
|
||||
|
||||
/** Up to three lists of main people, each with its suffix, and a dot (`formatManyMain`) */
|
||||
const formatManyMain = (source: WordSource, lists: readonly ManyList[]): string => {
|
||||
const names = lists.map((list) => namesOf(source, list.role));
|
||||
const counts = names.map(countOf);
|
||||
if (counts.every((count) => count === 0)) {
|
||||
return "";
|
||||
}
|
||||
let text = "";
|
||||
lists.forEach((list, index) => {
|
||||
if (counts[index] === 0) {
|
||||
return;
|
||||
}
|
||||
const before = counts.slice(0, index).some((count) => count > 0);
|
||||
const isLast = counts.slice(index + 1).every((count) => count === 0);
|
||||
text += (before ? general.AuthorsSeparator : "") + formatPersonsAuthor2(names[index]!, before, isLast);
|
||||
text += counts[index] === 1 ? list.single : list.many;
|
||||
});
|
||||
return text + general.Dot;
|
||||
};
|
||||
|
||||
/** The text in the style's brackets, as "(" and ")" */
|
||||
const enclose = (text: string): string => style.GeneralOpen + text + style.GeneralClose;
|
||||
|
||||
/** The text without the brackets `formatManySecondary` put around it (`substring($text, 1 + string-length($open), ...)`) */
|
||||
const withoutBrackets = (text: string): string => text.slice(style.GeneralOpen.length, text.length - style.GeneralClose.length);
|
||||
|
||||
/** A volume or pages written as one, such as "Vol. 3", or several, such as "Vols. 3-4" or "pp. 5, 9" */
|
||||
const isSeveral = (text: string): boolean => text.includes(",") || translate(text, general.Hyphens, "").length !== text.length;
|
||||
|
||||
/** A date: the source's, the one it was read on, or a court case's (`formatDateCore`) */
|
||||
const formatDateCore = (day: string, month: string, year: string, patterns: DatePatterns, displayNoDate: boolean): string =>
|
||||
year.length === 0 ? (displayNoDate ? strings.NoDateShortUnCap : "") : xsl.formatDatePrivate(day, month, year, patterns);
|
||||
|
||||
/** Two fields, with ": " between them, and a dot (`templateB`) */
|
||||
const templateB = (first: string, second: string): string => xsl.appendDot(first + (first && second ? general.EnumSeparator : "") + second);
|
||||
|
||||
/** Two fields, with ", " between them, and a dot (`templateC`) */
|
||||
const templateC = (first: string, second: string): string => xsl.appendDot(first + (first && second ? general.ListSeparator : "") + second);
|
||||
|
||||
/** Two fields, with ", " between them (`templateC2`) */
|
||||
const templateC2 = (first: string, second: string): string => first + (first && second ? general.ListSeparator : "") + second;
|
||||
|
||||
/** The city, state or province, and country or region, such as "Chicago, Illinois, United States" (`templateCSC2`) */
|
||||
const templateCSC2 = (source: WordSource): string =>
|
||||
templateC2(fieldOf(source, "City"), templateC2(fieldOf(source, "StateProvince"), fieldOf(source, "CountryRegion")));
|
||||
|
||||
/**
|
||||
* A title, a volume, an issue or an edition, and pages, of a publication, in italics but for the issue in brackets and
|
||||
* the pages, and a dot (`templateF`, and without italics for the third, `thirdNoItalic`). It is a copy of a variable
|
||||
*/
|
||||
const templateF = (first: string, second: string, third: string, fourth: string, fifth: string, thirdNoItalic: boolean): FormattedText => {
|
||||
const temp = join(
|
||||
first ? applyItalic(first) : "",
|
||||
second ? applyItalic((first ? general.ListSeparator : "") + second) : "",
|
||||
third ? (thirdNoItalic ? enclose(third) : applyItalic(enclose(third))) : "",
|
||||
fourth ? applyItalic((first || second || third ? general.ListSeparator : "") + fourth) : "",
|
||||
fifth ? (first || second || third || fourth ? general.ListSeparator : "") + fifth : "",
|
||||
);
|
||||
return join(copyOf(temp), xsl.needDot(textOf(temp)));
|
||||
};
|
||||
|
||||
/** A journal's or a periodical's title and volume in italics, its issue in brackets, and pages, and a dot (`templateG`) */
|
||||
const templateG = (first: string, second: string, third: string, fourth: string): FormattedText => {
|
||||
const temp = join(
|
||||
first ? applyItalic(first) : "",
|
||||
second ? applyItalic((first ? general.ListSeparator : "") + second) : "",
|
||||
third ? enclose(third) : "",
|
||||
fourth ? (first || second || third ? general.ListSeparator : "") + fourth : "",
|
||||
);
|
||||
return join(temp, xsl.needDot(textOf(temp)));
|
||||
};
|
||||
|
||||
/** A title in italics and another field, and a dot (`templateH`, and `templateCItalic`) */
|
||||
const templateH = (first: string, second: string): FormattedText => {
|
||||
const temp = join(first ? applyItalic(first) : "", first && second ? general.ListSeparator : "", second);
|
||||
return join(temp, xsl.needDot(textOf(temp)));
|
||||
};
|
||||
|
||||
/** "Retrieved March 3, 2006, from Site: https://…", or the parts of it the source has (`templateRDAFU`) */
|
||||
const templateRDAFU = (source: WordSource): string => {
|
||||
const dac = formatDateCore(
|
||||
fieldOf(source, "DayAccessed"),
|
||||
fieldOf(source, "MonthAccessed"),
|
||||
fieldOf(source, "YearAccessed"),
|
||||
style.DateAccessed,
|
||||
false,
|
||||
);
|
||||
const site = fieldOf(source, "InternetSiteTitle");
|
||||
const url = fieldOf(source, "URL");
|
||||
const siteAndUrl = (site ? (url ? site : xsl.appendDot(site)) : "") + (site && url ? general.EnumSeparator : "") + url;
|
||||
if (dac && siteAndUrl) {
|
||||
return textOf(xsl.stringFormat(strings.RetrievedFromCap, dac, siteAndUrl));
|
||||
}
|
||||
if (dac) {
|
||||
return textOf(xsl.stringFormat(strings.RetrievedCap, dac));
|
||||
}
|
||||
return siteAndUrl ? textOf(xsl.stringFormat(strings.FromCap, siteAndUrl)) : "";
|
||||
};
|
||||
|
||||
/** The title of a source, or what a citation names it by when it has none (`populateMain`'s `b:Title`) */
|
||||
const citationTitleOf = (source: WordSource): string => {
|
||||
const title = fieldOf(source, "Title");
|
||||
if (title) {
|
||||
return title;
|
||||
}
|
||||
const fallbacks: Partial<Record<WordSource["type"], Field>> = {
|
||||
BookSection: "BookTitle",
|
||||
ArticleInAPeriodical: "PeriodicalTitle",
|
||||
InternetSite: "InternetSiteTitle",
|
||||
DocumentFromInternetSite: "InternetSiteTitle",
|
||||
ElectronicSource: "PublicationTitle",
|
||||
Art: "PublicationTitle",
|
||||
Misc: "PublicationTitle",
|
||||
SoundRecording: "AlbumTitle",
|
||||
Interview: "BroadcastTitle",
|
||||
};
|
||||
const fallback = fallbacks[source.type];
|
||||
return fieldOf(source, "ShortTitle") || (fallback ? fieldOf(source, fallback) : "");
|
||||
};
|
||||
|
||||
/**
|
||||
* A source of a citation, such as "(Baker, 2010, p. 50" before the next source's "; " (`xsl:when test="b:Citation"`)
|
||||
*/
|
||||
const citation = (cited: CitedSource): FormattedText => {
|
||||
const { source } = cited;
|
||||
const { type } = source;
|
||||
const title0 = fieldOf(source, "ShortTitle") || citationTitleOf(source);
|
||||
const year0 = fieldOf(source, "Year");
|
||||
const patentNumber = fieldOf(source, "PatentNumber");
|
||||
const countryRegion = fieldOf(source, "CountryRegion");
|
||||
const patent = patentNumber
|
||||
? (countryRegion ? countryRegion + general.Space : "") + textOf(xsl.stringFormat(strings.PatentNumberShortCap, patentNumber))
|
||||
: "";
|
||||
|
||||
const main = namesOf(source, mainContributorsOf(source));
|
||||
let author0 = "";
|
||||
if (main && "corporate" in main) {
|
||||
author0 = main.corporate;
|
||||
} else if (main) {
|
||||
const count = main.people.length;
|
||||
main.people.forEach((person, index) => {
|
||||
const position = index + 1;
|
||||
if (position === 1) {
|
||||
author0 += xsl.formatName(person, cited.nonUniqueLastName ? style.CitationLong : style.CitationShort);
|
||||
}
|
||||
if (position > 1 && count <= MAX_CITATION_AUTHORS) {
|
||||
author0 += xsl.formatName(person, style.CitationShort);
|
||||
}
|
||||
if (count > MAX_CITATION_AUTHORS && position === 1) {
|
||||
author0 += general.ListSeparator + strings.AndOthersUnCap;
|
||||
}
|
||||
if (count <= MAX_CITATION_AUTHORS && position === count - 1) {
|
||||
author0 +=
|
||||
count === 2
|
||||
? general.Space + style.BeforeLastAuthor + general.Space
|
||||
: general.AuthorsSeparator + style.BeforeLastAuthor + general.Space;
|
||||
}
|
||||
if (count <= MAX_CITATION_AUTHORS && position < count - 1) {
|
||||
author0 += general.AuthorsSeparator;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const title = cited.hideTitle ? "" : title0;
|
||||
const year = cited.hideYear ? "" : type === "InternetSite" ? year0 || strings.NoDateShortUnCap : year0;
|
||||
const author = cited.hideAuthor ? "" : author0;
|
||||
const { volume, pages } = cited;
|
||||
const volVolume = volume
|
||||
? textOf(xsl.stringFormat(isSeveral(volume) ? strings.VolumesShortUnCap : strings.VolumeShortUnCap, volume))
|
||||
: "";
|
||||
const ppPages = pages ? (isSeveral(pages) ? strings.PagesCountinousShort : strings.PageShort) + general.Space + pages : "";
|
||||
const displayAuthor = type === "Patent" && patent ? patent : author;
|
||||
const displayTitle = !displayAuthor ? title : type === "Patent" && patent ? "" : cited.repeatedAuthor ? title : "";
|
||||
|
||||
let text = cited.first ? general.OpenBracket : "";
|
||||
text += cited.prefix ?? "";
|
||||
text += displayAuthor;
|
||||
if (displayTitle) {
|
||||
text += (displayAuthor ? general.ListSeparator : "") + displayTitle;
|
||||
}
|
||||
if (year && (author0 || title0 || year0)) {
|
||||
text += (displayAuthor || displayTitle ? general.ListSeparator : "") + year;
|
||||
}
|
||||
if (!author0 && !title0 && !year0) {
|
||||
text += source.tag;
|
||||
}
|
||||
if (volume || pages) {
|
||||
text += displayAuthor || displayTitle || year ? general.ListSeparator : "";
|
||||
text += volume && pages ? volume + general.Enum + pages : volVolume || ppPages;
|
||||
}
|
||||
text += cited.suffix ?? "";
|
||||
text += cited.last ? general.CloseBracket : general.GroupSeparator;
|
||||
return join(text);
|
||||
};
|
||||
|
||||
/** A source's key in the order of the bibliography: its main people, its year and its title (`b:SortingString`) */
|
||||
const sortingStringOf = (source: WordSource): string => {
|
||||
const main = namesOf(source, mainContributorsOf(source));
|
||||
const author = main && "corporate" in main ? main.corporate : formatPersonsAuthor(main);
|
||||
const title =
|
||||
source.type === "Patent"
|
||||
? (fieldOf(source, "CountryRegion") ? general.Space + fieldOf(source, "CountryRegion") : "") +
|
||||
(fieldOf(source, "PatentNumber") ? general.Space + fieldOf(source, "PatentNumber") : "")
|
||||
: fieldOf(source, "Title")
|
||||
? general.Space + fieldOf(source, "Title")
|
||||
: "";
|
||||
const year = fieldOf(source, "Year") ? general.Space + fieldOf(source, "Year") : "";
|
||||
if (source.type === "Case") {
|
||||
return title + year;
|
||||
}
|
||||
return author ? general.Space + author + year + title : title + year;
|
||||
};
|
||||
|
||||
/** The parts of the source's entry, joined with a space between those it has */
|
||||
const spaced = (...parts: readonly TextLike[]): FormattedText =>
|
||||
join(...parts.filter(has).flatMap((part, index) => (index === 0 ? [part] : [general.Space, part])));
|
||||
|
||||
/** A source's entry in the bibliography (`xsl:for-each select="…/b:Bibliography/b:Source"`) */
|
||||
const entryOf = (source: WordSource): FormattedText => {
|
||||
const field = (name: Field): string => fieldOf(source, name);
|
||||
const roleText = (role: Role): string => formatPersonsAuthor(source.names[role]);
|
||||
const peopleText = (role: Role): string => formatPersons(source.names[role]);
|
||||
const count = (role: Role): number => peopleCountOf(source, role);
|
||||
|
||||
const title = field("Title");
|
||||
const titleDot = xsl.appendDot(title);
|
||||
const edition = field("Edition");
|
||||
const year = field("Year");
|
||||
const issue = field("Issue");
|
||||
const pages = field("Pages");
|
||||
const volume = field("Volume");
|
||||
const bookTitle = field("BookTitle");
|
||||
const conferenceName = field("ConferenceName");
|
||||
const publisher = field("Publisher");
|
||||
const court = field("Court");
|
||||
const date = formatDateCore(field("Day"), field("Month"), year, style.Date, true);
|
||||
const dateCourt = formatDateCore(field("Day"), field("Month"), year, style.DateCourt, false);
|
||||
const ppPages = pages ? (isSeveral(pages) ? strings.PagesCountinousShort : strings.PageShort) + general.Space + pages : "";
|
||||
const prefixVolumeCap = volume
|
||||
? textOf(xsl.stringFormat(isSeveral(volume) ? strings.VolumesShortCap : strings.VolumeShortCap, volume))
|
||||
: "";
|
||||
const volumeDot = xsl.appendDot(volume);
|
||||
|
||||
const tempCSCPu = templateB(templateCSC2(source), publisher);
|
||||
const producerName = peopleText("ProducerName");
|
||||
const tempCSCPr = templateB(templateCSC2(source), producerName || field("ProductionCompany"));
|
||||
const tempCP = templateB(field("City"), publisher);
|
||||
const tempID = templateC(field("Institution"), field("Department"));
|
||||
const tempRIDC = textOf(xsl.printList([field("ThesisType"), field("Institution"), field("Department"), field("City")]));
|
||||
const tempTCSC = templateC(field("Theater"), templateCSC2(source));
|
||||
const tempICSC = templateC(field("Institution"), templateCSC2(source));
|
||||
const tempCD = templateB(field("CountryRegion"), field("Distributor"));
|
||||
const tempSC = templateC(field("Station"), field("City"));
|
||||
const tempTV = templateH(title, field("Version"));
|
||||
const tempPrP = templateH(field("BroadcastTitle"), pages);
|
||||
const tempJVIP = templateG(field("JournalName"), volume, issue, pages);
|
||||
const tempPTVI = templateG(field("PeriodicalTitle"), volume, issue, ppPages);
|
||||
const tempPVEP = templateF(field("PublicationTitle"), volume, edition, "", pages, true);
|
||||
const tempPVIEP = templateF(field("PublicationTitle"), volume, issue, edition, pages, false);
|
||||
|
||||
// The date is "n.d." when the source has no year, so it is never empty, and neither is this
|
||||
const enclosedDateDot = enclose(date) + general.Dot;
|
||||
const author = roleText("Author");
|
||||
const authorDot = xsl.appendDot(author);
|
||||
const editorLF = roleText("Editor");
|
||||
const translator = peopleText("Translator");
|
||||
const cEditors = count("Editor");
|
||||
const ensufixEditorLF = editorLF
|
||||
? editorLF + general.Space + (cEditors > 1 ? enclose(strings.EditorsShortCap) : enclose(strings.EditorShortCap))
|
||||
: "";
|
||||
const ensufixEditorLFDot = ensufixEditorLF ? ensufixEditorLF + general.Dot : "";
|
||||
const ensufixWithRole = (role: Role, single: string, many: string): string => {
|
||||
const people = roleText(role);
|
||||
return people ? people + general.Space + (count(role) > 1 ? enclose(many) : enclose(single)) + general.Dot : "";
|
||||
};
|
||||
const theAuthor = author || ensufixEditorLF;
|
||||
const theAuthorDot = xsl.appendDot(theAuthor);
|
||||
const writeEditor: Role | "" = author ? "Editor" : "";
|
||||
|
||||
const titleEditionVolumeDot = title
|
||||
? join(
|
||||
applyItalic(edition || prefixVolumeCap ? title : titleDot),
|
||||
edition || prefixVolumeCap
|
||||
? general.Space +
|
||||
style.GeneralOpen +
|
||||
(edition ? textOf(xsl.stringFormat(strings.EditionShortUnCap, edition)) : "") +
|
||||
(edition && prefixVolumeCap ? general.ListSeparator : "") +
|
||||
prefixVolumeCap +
|
||||
style.GeneralClose +
|
||||
general.Dot
|
||||
: "",
|
||||
)
|
||||
: [];
|
||||
|
||||
const theEditorAndTranslatorDot = formatManySecondary(source, [
|
||||
{
|
||||
role: writeEditor,
|
||||
single: general.ListSeparator + strings.EditorShortCap,
|
||||
many: general.ListSeparator + strings.EditorsShortCap,
|
||||
},
|
||||
{
|
||||
role: "Translator",
|
||||
single: general.ListSeparator + strings.TranslatorShortCap,
|
||||
many: general.ListSeparator + strings.TranslatorsShortCap,
|
||||
},
|
||||
]);
|
||||
const editorSuffix = general.Space + enclose(strings.EditorShortCap);
|
||||
const theEditorEnc = withoutBrackets(formatManySecondary(source, [{ role: writeEditor, single: editorSuffix, many: editorSuffix }]));
|
||||
const theBookAuthorAndEditor = formatManySecondary(source, [
|
||||
{ role: "BookAuthor", single: "", many: "" },
|
||||
{ role: "Editor", single: editorSuffix, many: general.Space + enclose(strings.EditorsShortCap) },
|
||||
]);
|
||||
const theBookAuthorAndEditor2 = theBookAuthorAndEditor ? withoutBrackets(theBookAuthorAndEditor) : "";
|
||||
const theBookAuthorAndEditorDot = theBookAuthorAndEditor ? theBookAuthorAndEditor2 + general.Dot : "";
|
||||
|
||||
const bookTitlePagesDot = bookTitle
|
||||
? volume || pages || translator || edition
|
||||
? join(
|
||||
applyItalic(bookTitle),
|
||||
general.Space +
|
||||
style.GeneralOpen +
|
||||
(translator
|
||||
? translator +
|
||||
general.ListSeparator +
|
||||
(count("Translator") > 1 ? strings.TranslatorsShortCap : strings.TranslatorShortCap)
|
||||
: "") +
|
||||
(edition
|
||||
? (translator ? general.ListSeparator : "") + textOf(xsl.stringFormat(strings.EditionShortUnCap, edition))
|
||||
: "") +
|
||||
(volume
|
||||
? (translator || edition ? general.ListSeparator : "") +
|
||||
textOf(xsl.stringFormat(isSeveral(volume) ? strings.VolumesShortCap : strings.VolumeShortCap, volume))
|
||||
: "") +
|
||||
(pages ? (translator || edition || volume ? general.ListSeparator : "") + ppPages : "") +
|
||||
style.GeneralClose +
|
||||
general.Dot,
|
||||
)
|
||||
: applyItalic(xsl.appendDot(bookTitle))
|
||||
: [];
|
||||
|
||||
const composerLF = roleText("Composer");
|
||||
const performerLF = roleText("Performer");
|
||||
const conductorLF = roleText("Conductor");
|
||||
const theAuthorSoundRecordingDot = composerLF || performerLF || conductorLF;
|
||||
const composer = peopleText("Composer");
|
||||
const performer = peopleText("Performer");
|
||||
const conductor = peopleText("Conductor");
|
||||
const secondarySoundRecordingName = composer ? performer || conductor : performer ? conductor : "";
|
||||
const thePerformerAndConductorDot = secondarySoundRecordingName
|
||||
? style.SecondaryOpen +
|
||||
textOf(xsl.stringFormat(strings.RecordedByCap, secondarySoundRecordingName)) +
|
||||
style.SecondaryClose +
|
||||
general.Dot
|
||||
: "";
|
||||
|
||||
const writer = peopleText("Writer");
|
||||
const director = peopleText("Director");
|
||||
const theAuthorPerformanceDot =
|
||||
xsl.appendDot(roleText("Writer")) ||
|
||||
ensufixWithRole("Director", strings.DirectorCap, strings.DirectorsCap) ||
|
||||
ensufixWithRole("Performer", strings.PerformerCap, strings.PerformersCap);
|
||||
const thePerformanceDirectorAndPerformerDot = formatManySecondary(source, [
|
||||
{
|
||||
role: writer ? "Director" : "",
|
||||
single: general.ListSeparator + strings.DirectorCap,
|
||||
many: general.ListSeparator + strings.DirectorsCap,
|
||||
},
|
||||
{
|
||||
role: writer || director ? "Performer" : "",
|
||||
single: general.ListSeparator + strings.PerformerCap,
|
||||
many: general.ListSeparator + strings.PerformersCap,
|
||||
},
|
||||
]);
|
||||
|
||||
const theMiscAuthorDot = authorDot || ensufixEditorLFDot;
|
||||
const theMiscEditorAndTranslatorAndCompilerDot = formatManySecondary(source, [
|
||||
{
|
||||
role: authorDot ? "Editor" : "",
|
||||
single: general.ListSeparator + strings.EditorShortCap,
|
||||
many: general.ListSeparator + strings.EditorsShortCap,
|
||||
},
|
||||
{
|
||||
role: "Translator",
|
||||
single: general.ListSeparator + strings.TranslatorShortCap,
|
||||
many: general.ListSeparator + strings.TranslatorsShortCap,
|
||||
},
|
||||
{ role: "Compiler", single: general.ListSeparator + strings.CompilerCap, many: general.ListSeparator + strings.CompilersCap },
|
||||
]);
|
||||
const filmSuffix = (word: string): string => general.Space + enclose(word);
|
||||
const theFilmProducerAndWriterAndDirectorDot = formatManyMain(source, [
|
||||
{ role: "ProducerName", single: filmSuffix(strings.ProducerCap), many: filmSuffix(strings.ProducersCap) },
|
||||
{ role: "Writer", single: filmSuffix(strings.WriterCap), many: filmSuffix(strings.WritersCap) },
|
||||
{ role: "Director", single: filmSuffix(strings.DirectorCap), many: filmSuffix(strings.DirectorsCap) },
|
||||
]);
|
||||
const interviewer: ManyList = {
|
||||
role: "Interviewer",
|
||||
single: general.ListSeparator + strings.InterviewerCap,
|
||||
many: general.ListSeparator + strings.InterviewersCap,
|
||||
};
|
||||
const theInterviewInterviewerAndEditorAndTranslator = formatManySecondary(source, [
|
||||
interviewer,
|
||||
{ role: "Editor", single: general.ListSeparator + strings.EditorCap, many: general.ListSeparator + strings.EditorsCap },
|
||||
{ role: "Translator", single: general.ListSeparator + strings.TranslatorCap, many: general.ListSeparator + strings.TranslatorsCap },
|
||||
]);
|
||||
const theInterviewInterviewer = formatManySecondary(source, [interviewer]);
|
||||
const theInternetSiteEditorAndProducerDot = formatManySecondary(
|
||||
source,
|
||||
[
|
||||
{ role: writeEditor, single: general.ListSeparator + strings.EditorCap, many: general.ListSeparator + strings.EditorsCap },
|
||||
{
|
||||
role: "ProducerName",
|
||||
single: general.ListSeparator + strings.ProducerCap,
|
||||
many: general.ListSeparator + strings.ProducersCap,
|
||||
},
|
||||
],
|
||||
field("ProductionCompany"),
|
||||
);
|
||||
|
||||
const albumTitle = field("AlbumTitle");
|
||||
const medium = field("Medium");
|
||||
const albumTitleMedium = join(
|
||||
albumTitle ? xsl.stringFormat(strings.OnAlbumTitleCap, applyItalic(albumTitle)) : "",
|
||||
albumTitle && medium ? general.Space : "",
|
||||
medium ? style.SecondaryOpen + medium + style.SecondaryClose : "",
|
||||
);
|
||||
const albumTitleMediumDot = textOf(albumTitleMedium).trim()
|
||||
? join(copyOf(albumTitleMedium), xsl.needDot(textOf(albumTitleMedium)))
|
||||
: [];
|
||||
|
||||
const conferenceNameItalic = (): FormattedText =>
|
||||
applyItalic((!volume && pages) || (!publisher && (volume || pages)) ? conferenceName : xsl.appendDot(conferenceName));
|
||||
const conferenceVolumeAndPages: readonly TextLike[] =
|
||||
volumeDot || pages
|
||||
? [
|
||||
publisher ? "" : general.ListSeparator,
|
||||
volumeDot && !pages ? join(general.Space, applyItalic(volumeDot)) : "",
|
||||
volume && pages ? join(general.Space, applyItalic(volume), general.ListSeparator, xsl.appendDot(ppPages)) : "",
|
||||
!volume && pages ? general.Space + enclose(ppPages) + general.Dot : "",
|
||||
]
|
||||
: [];
|
||||
|
||||
const before = (...parts: readonly TextLike[]): boolean => parts.some(has);
|
||||
|
||||
switch (source.type) {
|
||||
case "Book":
|
||||
return theAuthorDot
|
||||
? spaced(theAuthorDot, enclosedDateDot, titleEditionVolumeDot, theEditorAndTranslatorDot, tempCSCPu)
|
||||
: spaced(titleEditionVolumeDot, enclosedDateDot, theEditorAndTranslatorDot, tempCSCPu);
|
||||
case "BookSection": {
|
||||
const opening = authorDot ? spaced(authorDot, enclosedDateDot, titleDot) : spaced(titleDot, enclosedDateDot);
|
||||
const bookAuthors = theBookAuthorAndEditor
|
||||
? join(
|
||||
general.Space,
|
||||
xsl.stringFormat(strings.InNameCap, has(bookTitlePagesDot) ? theBookAuthorAndEditor2 : theBookAuthorAndEditorDot),
|
||||
)
|
||||
: [];
|
||||
const book = has(bookTitlePagesDot)
|
||||
? join(
|
||||
theBookAuthorAndEditor ? general.ListSeparator : general.Space,
|
||||
theBookAuthorAndEditor ? bookTitlePagesDot : xsl.stringFormat(strings.InNameCap, bookTitlePagesDot),
|
||||
)
|
||||
: [];
|
||||
const place = tempCSCPu ? general.Space + tempCSCPu : "";
|
||||
return join(opening, bookAuthors, book, place);
|
||||
}
|
||||
case "JournalArticle":
|
||||
return theAuthorDot
|
||||
? spaced(theAuthorDot, enclosedDateDot, titleDot, theEditorAndTranslatorDot, tempJVIP)
|
||||
: spaced(titleDot, enclosedDateDot, theEditorAndTranslatorDot, tempJVIP);
|
||||
case "ArticleInAPeriodical":
|
||||
return theAuthorDot
|
||||
? spaced(theAuthorDot, enclosedDateDot, titleDot, theEditorAndTranslatorDot, tempPTVI)
|
||||
: spaced(titleDot, enclosedDateDot, theEditorAndTranslatorDot, tempPTVI);
|
||||
case "ConferenceProceedings": {
|
||||
if (theAuthorDot) {
|
||||
const conference = theEditorEnc
|
||||
? join(
|
||||
general.Space,
|
||||
xsl.stringFormat(
|
||||
strings.InNameCap,
|
||||
conferenceName
|
||||
? join(theEditorEnc, general.ListSeparator, conferenceNameItalic())
|
||||
: theEditorEnc + general.Dot,
|
||||
),
|
||||
)
|
||||
: conferenceName
|
||||
? join(general.Space, conferenceNameItalic())
|
||||
: [];
|
||||
return join(
|
||||
spaced(theAuthorDot, enclosedDateDot, titleDot),
|
||||
conference,
|
||||
...conferenceVolumeAndPages,
|
||||
tempCP ? general.Space + tempCP : "",
|
||||
);
|
||||
}
|
||||
return join(
|
||||
titleDot,
|
||||
(title ? general.Space : "") + enclosedDateDot,
|
||||
conferenceName ? join(general.Space, conferenceNameItalic()) : "",
|
||||
...conferenceVolumeAndPages,
|
||||
tempCP ? general.Space + tempCP : "",
|
||||
);
|
||||
}
|
||||
case "SoundRecording":
|
||||
return theAuthorSoundRecordingDot
|
||||
? spaced(
|
||||
theAuthorSoundRecordingDot,
|
||||
enclosedDateDot,
|
||||
thePerformerAndConductorDot ? title + general.Space + thePerformerAndConductorDot : titleDot,
|
||||
albumTitleMediumDot,
|
||||
tempCSCPr,
|
||||
)
|
||||
: spaced(titleDot, enclosedDateDot, thePerformerAndConductorDot, albumTitleMediumDot, tempCSCPr);
|
||||
case "Performance":
|
||||
return theAuthorPerformanceDot
|
||||
? spaced(
|
||||
theAuthorPerformanceDot,
|
||||
enclosedDateDot,
|
||||
titleDot ? applyItalic(titleDot) : "",
|
||||
thePerformanceDirectorAndPerformerDot,
|
||||
tempTCSC,
|
||||
)
|
||||
: spaced(titleDot ? applyItalic(titleDot) : "", enclosedDateDot, tempTCSC);
|
||||
case "DocumentFromInternetSite":
|
||||
return theAuthorDot
|
||||
? spaced(theAuthorDot, enclosedDateDot, titleDot ? applyItalic(titleDot) : "", theEditorAndTranslatorDot)
|
||||
: spaced(titleDot ? applyItalic(titleDot) : "", enclosedDateDot, theEditorAndTranslatorDot);
|
||||
case "InternetSite":
|
||||
return theAuthorDot
|
||||
? spaced(theAuthorDot, enclosedDateDot, tempTV, theInternetSiteEditorAndProducerDot)
|
||||
: spaced(tempTV, enclosedDateDot, theInternetSiteEditorAndProducerDot);
|
||||
case "Case": {
|
||||
const courtAndDate = court || dateCourt ? enclose(court + (court && dateCourt ? general.Space : "") + dateCourt) : "";
|
||||
return join(
|
||||
title,
|
||||
field("CaseNumber") ? (title ? general.ListSeparator : "") + field("CaseNumber") : "",
|
||||
courtAndDate ? (title || field("CaseNumber") ? general.Space : "") + courtAndDate : "",
|
||||
title || field("CaseNumber") || court || dateCourt ? general.Dot : "",
|
||||
);
|
||||
}
|
||||
case "Patent": {
|
||||
const inventorLFDot = xsl.appendDot(roleText("Inventor"));
|
||||
const patentNumber = field("PatentNumber");
|
||||
return join(
|
||||
spaced(inventorLFDot, enclosedDateDot),
|
||||
patentNumber
|
||||
? applyItalic(
|
||||
join(
|
||||
general.Space,
|
||||
field("CountryRegion") ? field("CountryRegion") + general.Space : "",
|
||||
xsl.stringFormatDot(strings.PatentNumberShortCap, patentNumber),
|
||||
),
|
||||
)
|
||||
: "",
|
||||
);
|
||||
}
|
||||
case "Misc":
|
||||
return theMiscAuthorDot
|
||||
? spaced(
|
||||
theMiscAuthorDot,
|
||||
enclosedDateDot,
|
||||
titleDot,
|
||||
withoutBoundaries(tempPVIEP),
|
||||
theMiscEditorAndTranslatorAndCompilerDot,
|
||||
tempCSCPu,
|
||||
)
|
||||
: spaced(titleDot, enclosedDateDot, withoutBoundaries(tempPVIEP), theMiscEditorAndTranslatorAndCompilerDot, tempCSCPu);
|
||||
case "ElectronicSource":
|
||||
return theMiscAuthorDot
|
||||
? spaced(
|
||||
theMiscAuthorDot,
|
||||
enclosedDateDot,
|
||||
titleDot,
|
||||
has(tempPVEP) ? copyOf(tempPVEP) : "",
|
||||
theMiscEditorAndTranslatorAndCompilerDot,
|
||||
tempCSCPu,
|
||||
)
|
||||
: spaced(titleDot, enclosedDateDot, withoutBoundaries(tempPVEP), theMiscEditorAndTranslatorAndCompilerDot, tempCSCPu);
|
||||
case "Art": {
|
||||
const artistLFDot = xsl.appendDot(roleText("Artist"));
|
||||
const publicationTitleDot = xsl.appendDot(field("PublicationTitle"));
|
||||
return join(
|
||||
artistLFDot,
|
||||
general.Space + enclosedDateDot,
|
||||
titleDot ? join(artistLFDot ? general.Space : "", publicationTitleDot ? titleDot : applyItalic(titleDot)) : "",
|
||||
publicationTitleDot ? join(before(artistLFDot, titleDot) ? general.Space : "", applyItalic(publicationTitleDot)) : "",
|
||||
tempICSC ? (before(artistLFDot, titleDot, publicationTitleDot) ? general.Space : "") + tempICSC : "",
|
||||
);
|
||||
}
|
||||
case "Report":
|
||||
return spaced(
|
||||
authorDot,
|
||||
enclosedDateDot,
|
||||
titleDot ? applyItalic(titleDot) : "",
|
||||
...(publisher ? [tempID, tempCP] : [tempRIDC]),
|
||||
);
|
||||
case "Film":
|
||||
return join(
|
||||
theFilmProducerAndWriterAndDirectorDot
|
||||
? join(spaced(theFilmProducerAndWriterAndDirectorDot, enclosedDateDot, title ? applyItalic(title) : ""))
|
||||
: join(title ? applyItalic(title) : "", (title ? general.Space : "") + enclosedDateDot),
|
||||
general.Space + style.SecondaryOpen + strings.MotionPictureCap + style.SecondaryClose + general.Dot,
|
||||
tempCD ? general.Space + tempCD : "",
|
||||
);
|
||||
// An interview, the last of the types of source
|
||||
default: {
|
||||
const intervieweeLFDot = xsl.appendDot(roleText("Interviewee"));
|
||||
const interviewTitleDot = xsl.appendDot(title);
|
||||
const broadcasterDot = xsl.appendDot(field("Broadcaster"));
|
||||
return field("Broadcaster")
|
||||
? spaced(
|
||||
intervieweeLFDot,
|
||||
enclosedDateDot,
|
||||
interviewTitleDot,
|
||||
xsl.appendDot(field("BroadcastTitle")) ? applyItalic(xsl.appendDot(field("BroadcastTitle"))) : "",
|
||||
theInterviewInterviewer,
|
||||
broadcasterDot,
|
||||
tempSC,
|
||||
)
|
||||
: spaced(
|
||||
intervieweeLFDot,
|
||||
enclosedDateDot,
|
||||
interviewTitleDot,
|
||||
tempPrP,
|
||||
theInterviewInterviewerAndEditorAndTranslator,
|
||||
tempCSCPu,
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A source's entry: its parts, as a copy of a variable, then where it was read online, as the paragraph of the
|
||||
* bibliography is written (`xsl:element name="p"`)
|
||||
*/
|
||||
const paragraphOf = (source: WordSource): FormattedText => {
|
||||
const entry = entryOf(source);
|
||||
const retrieved = templateRDAFU(source);
|
||||
return resolveBoundaries(join(has(entry) ? join(copyOf(entry), retrieved ? general.Space : "") : "", retrieved));
|
||||
};
|
||||
|
||||
/** APA, sixth edition: Word's `APASixthEditionOfficeOnline.xsl` */
|
||||
export const apa: StyleDefinition = {
|
||||
name: "APA",
|
||||
file: "APASixthEditionOfficeOnline.xsl",
|
||||
version: "6",
|
||||
citation,
|
||||
bibliography: (sources) => ({
|
||||
paragraphs: sortByKey(sources, sortingStringOf).map(paragraphOf),
|
||||
hangingIndent: true,
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,262 @@
|
||||
/**
|
||||
* The templates Word's two styles from the Chicago Manual of Style share, Chicago (CHICAGO.XSL) and Turabian
|
||||
* (TURABIAN.XSL): they write the same citations, find the people a source is named by and sort their bibliographies in
|
||||
* the same way, and write some parts of an entry, such as the city and the publisher, alike.
|
||||
*
|
||||
* Each function follows the XSL template its description names, as both styles have it.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
// Turabian's name, and the XSL's spelling of "sufix" in the names of its variables
|
||||
// cspell:words Turabian TURABIAN sufix
|
||||
import { type FormattedText, type TextLike, join, textOf } from "./formatted-text";
|
||||
import { LOCALS } from "./locals";
|
||||
import type { CitedSource, FormattedBibliography } from "./style";
|
||||
import { sortByKey, translate, xslTemplates } from "./xsl";
|
||||
import { type Field, type Role, type WordNames, type WordSource, type WordSourceType, fieldOf } from "../word-source";
|
||||
|
||||
const { General, Strings, Chicago } = LOCALS;
|
||||
const xsl = xslTemplates(General);
|
||||
|
||||
/** The parts, when the test passes: a text that isn't empty, or true */
|
||||
export const when = (test: string | boolean, ...parts: readonly TextLike[]): FormattedText => (test ? join(...parts) : []);
|
||||
|
||||
/** A space, when any of the texts isn't empty, as the styles write one between the parts of an entry */
|
||||
export const spaceIf = (...texts: readonly string[]): string => (texts.some((text) => text.length > 0) ? General.Space : "");
|
||||
|
||||
/** ", " when any of the texts isn't empty, as a citation separates its volume or pages from what comes before them */
|
||||
const listSeparatorIf = (...texts: readonly string[]): string => (texts.some((text) => text.length > 0) ? General.ListSeparator : "");
|
||||
|
||||
/** The text with its spaces at the start and end removed, and each run of them made one space, as XPath's `normalize-space` */
|
||||
export const normalizeSpace = (text: string): string => text.replace(/[ \t\r\n]+/g, " ").trim();
|
||||
|
||||
/** A format with one text in place of %1, or "" when the text is empty, as the styles' `StringFormat` calls are guarded */
|
||||
export const formatIf = (format: string, text: string): string => (text ? textOf(xsl.stringFormat(format, text)) : "");
|
||||
|
||||
/** A volume, as "Vol. 2", or "Vols. 2-3" for more than one (the styles' choice of `VolumeShortCap` and `VolumesShortCap`) */
|
||||
export const volumeFormatOf = (volume: string, single: string, several: string): string =>
|
||||
volume.includes(",") || translate(volume, General.Hyphens, "").length !== volume.length ? several : single;
|
||||
|
||||
/**
|
||||
* The word for one or more people, such as "Trans.", then their names, and a dot (`prefixTranslatorDot` and others). Its
|
||||
* people are editors, translators, conductors, composers or compilers, who are never an organization, so the list has a
|
||||
* name only when it has people
|
||||
*/
|
||||
export const prefixed = (text: string, count: number, single: string, several: string): string =>
|
||||
text ? (count > 1 ? several : single) + General.Space + xsl.appendDot(text) : "";
|
||||
|
||||
/**
|
||||
* A list of people last name first, ", " and the word for one or more of them, such as "ed." (`sufixEditorLFDot` and
|
||||
* others). Its people are editors, compilers or translators, who are never an organization, so the list has a name only
|
||||
* when it has people
|
||||
*/
|
||||
export const suffixed = (text: string, count: number, single: string, several: string): string =>
|
||||
text ? text + General.ListSeparator + (count > 1 ? several : single) : "";
|
||||
|
||||
/** A title in quotes */
|
||||
export const quoted = (text: string): string => General.OpenQuote + text + General.CloseQuote;
|
||||
|
||||
/** The text of a role's people, their names one after another, or of its organization, as XPath reads `b:Author/b:Editor` */
|
||||
const roleTextOf = (names: WordNames | undefined): string =>
|
||||
names === undefined
|
||||
? ""
|
||||
: "corporate" in names
|
||||
? names.corporate
|
||||
: names.people.map((person) => person.last + person.first + person.middle).join("");
|
||||
|
||||
/** How many people have a role, as `count(b:Author/b:Editor/b:NameList/b:Person)` */
|
||||
export const countOf = (names: WordNames | undefined): number => (names !== undefined && "people" in names ? names.people.length : 0);
|
||||
|
||||
// The roles a source is named by, in the order the styles look for them, by type of source (`MainContributors`)
|
||||
const MAIN_CONTRIBUTORS: Readonly<Record<WordSourceType, readonly Role[]>> = {
|
||||
Book: ["Author", "Editor", "Translator"],
|
||||
BookSection: ["Author", "BookAuthor"],
|
||||
JournalArticle: ["Author", "Editor"],
|
||||
ArticleInAPeriodical: ["Author", "Editor"],
|
||||
ConferenceProceedings: ["Author"],
|
||||
Report: ["Author"],
|
||||
SoundRecording: ["Performer", "Conductor", "Composer", "Artist"],
|
||||
Performance: ["Writer", "Performer", "Director"],
|
||||
Art: ["Artist"],
|
||||
DocumentFromInternetSite: ["Author"],
|
||||
InternetSite: ["Author"],
|
||||
Film: ["Writer", "Performer", "Director"],
|
||||
Interview: ["Interviewee", "Editor", "Translator"],
|
||||
Patent: ["Inventor", "Editor", "Translator"],
|
||||
ElectronicSource: ["Author", "Editor"],
|
||||
Case: ["Author"],
|
||||
Misc: ["Author", "Editor", "Compiler", "Translator"],
|
||||
};
|
||||
|
||||
/** The role a source is named by: the first of its type's roles that has a name (`MainContributors`) */
|
||||
const mainContributorOf = (source: WordSource): Role | undefined =>
|
||||
MAIN_CONTRIBUTORS[source.type].find((role) => roleTextOf(source.names[role]).length > 0);
|
||||
|
||||
/** The people or the organization a source is named by, as `populateMain` copies them to `b:Author/b:Main` */
|
||||
export const mainOf = (source: WordSource): WordNames | undefined => {
|
||||
const role = mainContributorOf(source);
|
||||
return role === undefined ? undefined : source.names[role];
|
||||
};
|
||||
|
||||
// The field a citation's title falls back to after the short title, when the source has no title, by type of source
|
||||
// (`populateMain`, for `b:Citation`)
|
||||
const CITATION_TITLES: Readonly<Partial<Record<WordSourceType, Field>>> = {
|
||||
BookSection: "BookTitle",
|
||||
ArticleInAPeriodical: "PeriodicalTitle",
|
||||
InternetSite: "InternetSiteTitle",
|
||||
DocumentFromInternetSite: "InternetSiteTitle",
|
||||
ElectronicSource: "PublicationTitle",
|
||||
Art: "PublicationTitle",
|
||||
Misc: "PublicationTitle",
|
||||
SoundRecording: "AlbumTitle",
|
||||
Interview: "BroadcastTitle",
|
||||
};
|
||||
|
||||
/** A source's title in a citation: its title, or its short title, or the title of what it's in (`populateMain`) */
|
||||
const citationTitleOf = (source: WordSource): string => {
|
||||
const fallback = CITATION_TITLES[source.type];
|
||||
return fieldOf(source, "Title") || fieldOf(source, "ShortTitle") || (fallback === undefined ? "" : fieldOf(source, fallback));
|
||||
};
|
||||
|
||||
/** The year, or "n.d." (`getYear`) */
|
||||
export const getYear = (source: WordSource): string => fieldOf(source, "Year") || Strings.NoDateShortUnCap;
|
||||
|
||||
/** The first, the second after ": ", and the third after ", ", of those that aren't empty (`templateANoDot`) */
|
||||
export const templateANoDot = (first: string, second: string, third: string): string =>
|
||||
first + (first && second ? General.EnumSeparator : "") + second + ((first || second) && third ? General.ListSeparator : "") + third;
|
||||
|
||||
/** {@link templateANoDot}, with a dot after it (`templateA`) */
|
||||
export const templateA = (first: string, second: string, third: string): string => xsl.appendDot(templateANoDot(first, second, third));
|
||||
|
||||
/** The first and the second, with a space between them, and a dot after (`templateSpaceAB`) */
|
||||
const templateSpaceAB = (first: string, second: string): string => xsl.appendDot(first + (first && second ? General.Space : "") + second);
|
||||
|
||||
/** The first and the second, with ", " between them, and a dot after (`templateC`) */
|
||||
export const templateC = (first: string, second: string): string =>
|
||||
xsl.appendDot(first + (first && second ? General.ListSeparator : "") + second);
|
||||
|
||||
/** The first, the second after ", ", and the third after ": ", with a dot after (`templateE`) */
|
||||
export const templateE = (first: string, second: string, third: string): string =>
|
||||
xsl.appendDot(
|
||||
first + (first && second ? General.ListSeparator : "") + second + ((first || second) && third ? General.EnumSeparator : "") + third,
|
||||
);
|
||||
|
||||
/** The city, and the state or province (`templateCityStateProvince`) */
|
||||
export const templateCityStateProvince = (source: WordSource): string => {
|
||||
const city = fieldOf(source, "City");
|
||||
const state = fieldOf(source, "StateProvince");
|
||||
return city + (city && state ? General.ListSeparator : "") + state;
|
||||
};
|
||||
|
||||
/** The country and the patent's number, such as "United States Patent 7,123,456." (`templateCP`) */
|
||||
export const templateCP = (source: WordSource): string =>
|
||||
templateSpaceAB(fieldOf(source, "CountryRegion"), formatIf(Strings.PatentCap, fieldOf(source, "PatentNumber")));
|
||||
|
||||
/**
|
||||
* The items of a list, with a space before them, or nothing when the list is empty (`PrintSpaceAndList`)
|
||||
*/
|
||||
export const printSpaceAndList = (items: readonly TextLike[]): FormattedText => {
|
||||
const list = xsl.printList(items);
|
||||
return when(textOf(list), General.Space, list);
|
||||
};
|
||||
|
||||
/**
|
||||
* The text a bibliography is sorted by: the authors, a periodical's title, the title, and whether the source is named
|
||||
* by its authors, editors, compilers or translators (`b:SortingString`, from `populateMain`)
|
||||
*
|
||||
* @param formatPersonsAuthor - The style's list of a source's authors
|
||||
*/
|
||||
const sortingStringOf = (source: WordSource, formatPersonsAuthor: (names: WordNames | undefined) => string): string => {
|
||||
const role = mainContributorOf(source);
|
||||
const author = formatPersonsAuthor(mainOf(source));
|
||||
const periodicalTitle = fieldOf(source, "PeriodicalTitle");
|
||||
const title = fieldOf(source, "Title");
|
||||
const order = role === "Editor" ? "2" : role === "Compiler" ? "3" : role === "Translator" ? "4" : "1";
|
||||
return `${author && source.type !== "Case" ? ` ${author}` : ""}${
|
||||
periodicalTitle && source.type === "ArticleInAPeriodical" ? ` ${periodicalTitle}` : ""
|
||||
}${title ? ` ${title}` : ""} ${order}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* A source of a citation, such as "(Baker 2010, 50)", with its authors, the title when another source has the same
|
||||
* authors, and the year (`b:Citation`)
|
||||
*/
|
||||
export const citation = (cited: CitedSource): FormattedText => {
|
||||
const { source } = cited;
|
||||
const title0 = fieldOf(source, "ShortTitle") || citationTitleOf(source);
|
||||
const yearSimple = fieldOf(source, "Year");
|
||||
const year0 = yearSimple || Strings.NoDateShortUnCap;
|
||||
const main = mainOf(source);
|
||||
const minAuthors = cited.minAuthors > 1 ? cited.minAuthors : 1;
|
||||
const patterns = cited.nonUniqueLastName ? Chicago.CitationLong : Chicago.CitationShort;
|
||||
const people = main !== undefined && "people" in main ? main.people : [];
|
||||
const cAuthors = people.length;
|
||||
const author0 =
|
||||
main !== undefined && "corporate" in main
|
||||
? main.corporate
|
||||
: people
|
||||
.map((person, index) => {
|
||||
const position = index + 1;
|
||||
const name = cAuthors > 3 && position > minAuthors ? "" : xsl.formatName(person, patterns);
|
||||
const separator =
|
||||
cAuthors > 3 && position === minAuthors
|
||||
? General.ListSeparator + Strings.AndOthersUnCap
|
||||
: cAuthors > 3 && position > minAuthors
|
||||
? ""
|
||||
: (cAuthors - 1 === position && (cAuthors === 2 || cAuthors === 3)) || (cAuthors > 3 && position === 2)
|
||||
? General.Space + Strings.AndUnCap + General.Space
|
||||
: cAuthors > position && position < 3
|
||||
? General.AuthorsSeparator
|
||||
: "";
|
||||
return name + separator;
|
||||
})
|
||||
.join("");
|
||||
const title = cited.hideTitle ? "" : title0;
|
||||
const year = cited.hideYear ? "" : year0;
|
||||
const author = cited.hideAuthor ? "" : author0;
|
||||
const { volume, pages } = cited;
|
||||
const volVolume = formatIf(volumeFormatOf(volume, Strings.VolumeShortUnCap, Strings.VolumesShortUnCap), volume);
|
||||
const displayTitle = !author || cited.repeatedAuthor ? title : "";
|
||||
// A source with no authors, title or year is cited by its tag
|
||||
const nothing = !author0 && !title0 && !yearSimple;
|
||||
return join(
|
||||
cited.first ? General.OpenBracket : "",
|
||||
cited.prefix ?? "",
|
||||
author,
|
||||
when(displayTitle, author ? General.ListSeparator : "", displayTitle),
|
||||
nothing ? source.tag : "",
|
||||
when(year && !nothing, spaceIf(author, displayTitle), year),
|
||||
when(
|
||||
volume || pages,
|
||||
listSeparatorIf(author, displayTitle, year),
|
||||
volume && pages ? volume + General.Enum + pages : volVolume || pages,
|
||||
),
|
||||
cited.suffix ?? "",
|
||||
cited.last ? General.CloseBracket : General.ListSeparator,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* A bibliography: its sources sorted, each written as an entry with its authors, or with a dash for the authors of an
|
||||
* entry with the same authors as the one before it (`b:Bibliography`)
|
||||
*
|
||||
* @param formatPersonsAuthor - The style's list of a source's authors (`formatPersonsAuthor`)
|
||||
* @param bibliographyEntry - The style's entry of a source, given its authors or the dash
|
||||
*/
|
||||
export const bibliographyOf = (
|
||||
sources: readonly WordSource[],
|
||||
formatPersonsAuthor: (names: WordNames | undefined) => string,
|
||||
bibliographyEntry: (source: WordSource, authorMain: string) => FormattedText,
|
||||
): FormattedBibliography => {
|
||||
const sorted = sortByKey(sources, (source) => sortingStringOf(source, formatPersonsAuthor));
|
||||
const mains = sorted.map((source) => formatPersonsAuthor(mainOf(source)));
|
||||
return {
|
||||
hangingIndent: true,
|
||||
paragraphs: sorted.map((source, index) =>
|
||||
bibliographyEntry(
|
||||
source,
|
||||
index > 0 && mains[index] === mains[index - 1] && mains[index].length > 0 ? Chicago.SameAuthor : mains[index],
|
||||
),
|
||||
),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { describeWordOutput, outputOf } from "tests/bibliography";
|
||||
|
||||
import type { Person } from "../source";
|
||||
import { chicago } from "./chicago";
|
||||
import expected from "./fixtures/chicago.json";
|
||||
|
||||
const people = (prefix: string, count: number): readonly Person[] =>
|
||||
Array.from({ length: count }, (_, index) => ({ lastName: `${prefix}${index + 1}`, firstName: "Al" }));
|
||||
|
||||
describe("chicago", () => {
|
||||
describeWordOutput(chicago, expected);
|
||||
|
||||
// The expected text of these is what Word's own style, CHICAGO.XSL, writes for them
|
||||
describe("as Word's own style writes them", () => {
|
||||
it("lists the first seven of 11 or more authors or editors, then et al.", () => {
|
||||
expect(
|
||||
outputOf(chicago, {
|
||||
sources: [
|
||||
{
|
||||
tag: "Many",
|
||||
type: "book",
|
||||
authors: people("Author", 12),
|
||||
editors: people("Editor", 12),
|
||||
title: "Crowds",
|
||||
year: "2001",
|
||||
city: "Rome",
|
||||
publisher: "Press",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "Many" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(Author1, et al. 2001)"],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: [
|
||||
"Author1, Al, Al Author2, Al Author3, Al Author4, Al Author5, Al Author6, Al Author7, et al. 2001. <i>Crowds.</i> Edited by Al Editor1, Al Editor2, Al Editor3, Al Editor4, Al Editor5, Al Editor6, Al Editor7, et al. Rome: Press.",
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("writes the month a website was read in when it has no year", () => {
|
||||
expect(
|
||||
outputOf(chicago, {
|
||||
sources: [{ tag: "Web", type: "website", title: "Page", monthAccessed: "May", url: "https://example.com" }],
|
||||
citations: [[{ source: "Web" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(Page n.d.)"],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["n.d. <i>Page.</i> Accessed May. https://example.com."] },
|
||||
});
|
||||
});
|
||||
|
||||
it("writes the court of a case with no city or date", () => {
|
||||
expect(
|
||||
outputOf(chicago, {
|
||||
sources: [{ tag: "Case", type: "case", title: "A v. B", court: "High Court" }],
|
||||
citations: [[{ source: "Case" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(A v. B n.d.)"],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["<i>A v. B.</i> n.d. (High Court)."] },
|
||||
});
|
||||
});
|
||||
|
||||
it("writes the producers of an electronic source", () => {
|
||||
expect(
|
||||
outputOf(chicago, {
|
||||
sources: [
|
||||
{
|
||||
tag: "App",
|
||||
type: "electronicSource",
|
||||
authors: people("Maker", 1),
|
||||
title: "App",
|
||||
producers: people("Producer", 2),
|
||||
productionCompany: "Studio",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "App" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(Maker1 n.d.)"],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["Maker1, Al. n.d. <i>App.</i> Prods. Al Producer1 and Al Producer2."] },
|
||||
});
|
||||
});
|
||||
|
||||
it("names a miscellaneous source by its compilers when it has no authors or editors", () => {
|
||||
expect(
|
||||
outputOf(chicago, {
|
||||
sources: [{ tag: "Notes", type: "miscellaneous", compilers: people("Compiler", 2), title: "Notes", year: "2002" }],
|
||||
citations: [[{ source: "Notes" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(Compiler1 and Compiler2 2002)"],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["Compiler1, Al, and Al Compiler2, comps. 2002. “Notes.”"] },
|
||||
});
|
||||
});
|
||||
|
||||
it("names an electronic source by its translators, and writes its compilers", () => {
|
||||
expect(
|
||||
outputOf(chicago, {
|
||||
sources: [
|
||||
{
|
||||
tag: "Disc",
|
||||
type: "electronicSource",
|
||||
translators: people("Translator", 1),
|
||||
compilers: people("Compiler", 1),
|
||||
title: "Disc",
|
||||
year: "2003",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "Disc" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(Disc 2003)"],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["Translator1, Al, trans. 2003. <i>Disc.</i> Comp. Al Compiler1."] },
|
||||
});
|
||||
});
|
||||
|
||||
it("writes the editors of an interview after its broadcast, or after its title with its translators", () => {
|
||||
expect(
|
||||
outputOf(chicago, {
|
||||
sources: [
|
||||
{
|
||||
tag: "Talk",
|
||||
type: "interview",
|
||||
interviewees: people("Guest", 1),
|
||||
title: "Talk",
|
||||
broadcastTitle: "Show",
|
||||
editors: people("Editor", 1),
|
||||
year: "2004",
|
||||
},
|
||||
{
|
||||
tag: "Chat",
|
||||
type: "interview",
|
||||
interviewees: people("Guest", 1),
|
||||
title: "Chat",
|
||||
editors: people("Editor", 1),
|
||||
translators: people("Translator", 1),
|
||||
year: "2005",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "Talk" }], [{ source: "Chat" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(Guest1, Talk 2004)", "(Guest1, Chat 2005)"],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: [
|
||||
"Guest1, Al. 2005. <i>Chat</i>Edited by Al Editor1, translated by Al Translator1.",
|
||||
"Guest1, Al. 2004. “Talk.” <i>Show</i>, edited by Al Editor1.",
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("names a book by its translators, or its editors, when it has no authors", () => {
|
||||
expect(
|
||||
outputOf(chicago, {
|
||||
sources: [
|
||||
{ tag: "Tr", type: "book", translators: people("Translator", 1), title: "Translated", year: "2006" },
|
||||
{ tag: "Ed", type: "book", editors: people("Editor", 1), title: "Edited", year: "2006" },
|
||||
],
|
||||
citations: [[{ source: "Tr" }], [{ source: "Ed" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(Translator1 2006)", "(Editor1 2006)"],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: ["Editor1, Al, ed. 2006. <i>Edited.</i> ", "Translator1, Al, trans. 2006. <i>Translated.</i> "],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,876 @@
|
||||
/**
|
||||
* Chicago, the author-date style of the Chicago Manual of Style (16th edition), written from Word's own (CHICAGO.XSL).
|
||||
*
|
||||
* Each function follows the XSL template its description names, including where that doesn't do what it looks like it
|
||||
* should, so citations and bibliographies are written as Word writes them when it updates a document's fields.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
// The names of the XSL's templates and variables, which the functions and variables here keep, such as templateMDEP for
|
||||
// the month and day, edition and pages, and its spelling of "sufix"
|
||||
// cspell:words CCMD CPMD CPMDP CSPP DAUD MDEP PVIP RICP sufix Sufix Forno
|
||||
import {
|
||||
bibliographyOf,
|
||||
citation,
|
||||
countOf,
|
||||
formatIf,
|
||||
getYear,
|
||||
normalizeSpace,
|
||||
prefixed,
|
||||
printSpaceAndList,
|
||||
quoted,
|
||||
spaceIf,
|
||||
suffixed,
|
||||
templateA,
|
||||
templateANoDot,
|
||||
templateC,
|
||||
templateCP,
|
||||
templateCityStateProvince,
|
||||
templateE,
|
||||
volumeFormatOf,
|
||||
when,
|
||||
} from "./chicago-family";
|
||||
import { type FormattedText, join, textOf } from "./formatted-text";
|
||||
import { LOCALS, type NamePatterns } from "./locals";
|
||||
import type { FormattedBibliography, StyleDefinition } from "./style";
|
||||
import { applyItalic, xslTemplates } from "./xsl";
|
||||
import { type Field, type Role, type WordNames, type WordSource, type WordSourceType, fieldOf } from "../word-source";
|
||||
|
||||
const { General, Strings, Chicago, APA } = LOCALS;
|
||||
const xsl = xslTemplates(General);
|
||||
|
||||
/** A format of a date, such as "%D %M", with each %D, %M and %Y replaced by the day, month and year (`StringFormatDate`) */
|
||||
const stringFormatDate = (format: string, day: string, month: string, year: string): string =>
|
||||
format.replace(/%([DMY])/g, (_match, code: string) => (code === "D" ? day : code === "M" ? month : year));
|
||||
|
||||
/**
|
||||
* What comes after a person in a list of a source's authors: a comma, "and", or "et al." after the seventh of 11 or more
|
||||
* (`formatPersonSeparator`)
|
||||
*/
|
||||
const formatPersonSeparator = (position: number, count: number): string => {
|
||||
if (count < 11) {
|
||||
return position === count
|
||||
? ""
|
||||
: position === count - 1
|
||||
? General.ListSeparator + Strings.AndUnCap + General.Space
|
||||
: General.ListSeparator;
|
||||
}
|
||||
return position > 7 ? "" : position === 7 ? General.ListSeparator + Strings.AndOthersUnCap : General.ListSeparator;
|
||||
};
|
||||
|
||||
/** What comes after a person in a list of other contributors, such as editors (`formatPersonSeparator2`) */
|
||||
const formatPersonSeparator2 = (position: number, count: number): string => {
|
||||
if (count < 11) {
|
||||
return position === count ? "" : position === count - 1 ? General.Space + Strings.AndUnCap + General.Space : General.ListSeparator;
|
||||
}
|
||||
return position > 7 ? "" : position === 7 ? General.ListSeparator + Strings.AndOthersUnCap : General.ListSeparator;
|
||||
};
|
||||
|
||||
/**
|
||||
* People as a source's authors are listed: the first last name first, the others first name first, and only the first
|
||||
* seven of 11 or more; or the organization (`formatPersonsAuthor`)
|
||||
*/
|
||||
const formatPersonsAuthor = (names: WordNames | undefined): string => {
|
||||
if (names === undefined) {
|
||||
return "";
|
||||
}
|
||||
if ("corporate" in names) {
|
||||
return names.corporate;
|
||||
}
|
||||
const count = names.people.length;
|
||||
return names.people
|
||||
.map((person, index) => {
|
||||
const position = index + 1;
|
||||
const patterns: NamePatterns | undefined =
|
||||
position === 1 ? Chicago.MainAuthor : count < 11 || position < 8 ? Chicago.OtherAuthors : undefined;
|
||||
return (patterns === undefined ? "" : xsl.formatName(person, patterns)) + formatPersonSeparator(position, count);
|
||||
})
|
||||
.join("");
|
||||
};
|
||||
|
||||
/** People as a source's other contributors are listed, such as its editors, first name first (`formatPersons`) */
|
||||
const formatPersons = (names: WordNames | undefined): string => {
|
||||
if (names === undefined) {
|
||||
return "";
|
||||
}
|
||||
if ("corporate" in names) {
|
||||
return names.corporate;
|
||||
}
|
||||
const count = names.people.length;
|
||||
return names.people
|
||||
.map((person, index) => {
|
||||
const position = index + 1;
|
||||
return (
|
||||
(count < 11 || position < 8 ? xsl.formatName(person, Chicago.SecondaryAuthors) : "") +
|
||||
formatPersonSeparator2(position, count)
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
};
|
||||
|
||||
/** The month and the day, such as "9 January", when the source has a year and a month (`getMonthDay`) */
|
||||
const getMonthDay = (source: WordSource): string => {
|
||||
const month = fieldOf(source, "Month");
|
||||
if (!fieldOf(source, "Year") || !month) {
|
||||
return "";
|
||||
}
|
||||
const day = fieldOf(source, "Day");
|
||||
return stringFormatDate(day ? Chicago.Date.DM : General.SimpleDate.M, day, month, "");
|
||||
};
|
||||
|
||||
/**
|
||||
* The date a source was read, such as "February 3, 2022", with the pattern for the parts it has (`formatDateAccessed`,
|
||||
* with Chicago's `formatDateCore` and `formatDateCorePrivate`, which write a month and a day without a year)
|
||||
*/
|
||||
const formatDateAccessed = (source: WordSource): string => {
|
||||
const day = fieldOf(source, "DayAccessed");
|
||||
const month = fieldOf(source, "MonthAccessed");
|
||||
const year = fieldOf(source, "YearAccessed");
|
||||
const patterns = APA.DateAccessed;
|
||||
const format = !year
|
||||
? month
|
||||
? day
|
||||
? patterns.DM
|
||||
: General.SimpleDate.M
|
||||
: ""
|
||||
: !month
|
||||
? General.SimpleDate.Y
|
||||
: !day
|
||||
? patterns.MY
|
||||
: patterns.DMY;
|
||||
return stringFormatDate(format, day, month, year);
|
||||
};
|
||||
|
||||
/** The month and day, the edition and the pages, such as "5 June, Late ed.: 10-12." (`templateMDEP`) */
|
||||
const templateMDEP = (source: WordSource): string => {
|
||||
const edition = fieldOf(source, "Edition");
|
||||
return templateE(
|
||||
getMonthDay(source),
|
||||
edition ? textOf(xsl.stringFormat(Strings.EditionShortUnCap, edition)) : "",
|
||||
fieldOf(source, "Pages"),
|
||||
);
|
||||
};
|
||||
|
||||
/** The recording number and the medium, each with a dot after it (`templateRM`) */
|
||||
const templateRM = (source: WordSource): string => {
|
||||
const recordingNumber = fieldOf(source, "RecordingNumber");
|
||||
const medium = fieldOf(source, "Medium");
|
||||
return xsl.appendDot(recordingNumber) + (recordingNumber && medium ? General.Space : "") + xsl.appendDot(medium);
|
||||
};
|
||||
|
||||
/** The court, the city and the month and day, in brackets, such as "(Supreme Court, Washington 28 June)." (`templateCCMD`) */
|
||||
const templateCCMD = (source: WordSource): string => {
|
||||
const monthDay = getMonthDay(source);
|
||||
const court = fieldOf(source, "Court");
|
||||
const city = fieldOf(source, "City");
|
||||
return xsl.appendDot(
|
||||
court || city || monthDay
|
||||
? General.OpenBracket +
|
||||
court +
|
||||
(court && (city || monthDay) ? General.ListSeparator : "") +
|
||||
(city || monthDay ? city + (city && monthDay ? General.Space : "") + monthDay : "") +
|
||||
General.CloseBracket
|
||||
: "",
|
||||
);
|
||||
};
|
||||
|
||||
/** A journal's publisher, volume, issue and pages, such as "(Baking Society) 12 (4): 233-250." (`templatePVIP`) */
|
||||
const templatePVIP = (source: WordSource): string => {
|
||||
const publisher = fieldOf(source, "Publisher");
|
||||
const volume = fieldOf(source, "Volume");
|
||||
const issue = fieldOf(source, "Issue");
|
||||
const pages = fieldOf(source, "Pages");
|
||||
return xsl.appendDot(
|
||||
(publisher ? General.OpenBracket + publisher + General.CloseBracket : "") +
|
||||
(volume ? (publisher ? General.Space : "") + volume : "") +
|
||||
(issue ? (publisher || volume ? General.Space : "") + General.OpenBracket + issue + General.CloseBracket : "") +
|
||||
((volume || issue) && pages ? General.EnumSeparator : "") +
|
||||
(pages ? (publisher || volume || issue ? General.Space : "") + pages : ""),
|
||||
);
|
||||
};
|
||||
|
||||
/** The city, the publisher, and the month and day in brackets, or the pages (`templateCPMDP`) */
|
||||
const templateCPMDP = (source: WordSource): string => {
|
||||
const monthDay = getMonthDay(source);
|
||||
const pages = fieldOf(source, "Pages");
|
||||
const text = templateA(
|
||||
templateCityStateProvince(source),
|
||||
fieldOf(source, "Publisher"),
|
||||
(monthDay ? General.OpenBracket + monthDay + General.CloseBracket : "") + (pages && monthDay ? General.EnumSeparator + pages : ""),
|
||||
);
|
||||
return text + (pages && !monthDay ? (text ? General.Space : "") + xsl.appendDot(pages) : "");
|
||||
};
|
||||
|
||||
/** When a website was read, and its address, such as "Accessed February 3, 2022. https://example.com." (`templateDAUD`) */
|
||||
const templateDAUD = (source: WordSource): string => {
|
||||
const dateAccessed = formatDateAccessed(source);
|
||||
const url = fieldOf(source, "URL");
|
||||
return (
|
||||
(dateAccessed ? xsl.appendDot(textOf(xsl.stringFormat(Strings.AccessedCap, dateAccessed))) : "") +
|
||||
(url ? (dateAccessed ? General.Space : "") + xsl.appendDot(url) : "")
|
||||
);
|
||||
};
|
||||
|
||||
/** A report's type, department, institution, city and publisher, and pages (`templateRICP`) */
|
||||
const templateRICP = (source: WordSource): string =>
|
||||
textOf(
|
||||
xsl.printList([
|
||||
fieldOf(source, "ThesisType"),
|
||||
fieldOf(source, "Department"),
|
||||
fieldOf(source, "Institution"),
|
||||
templateANoDot(templateCityStateProvince(source), fieldOf(source, "Publisher"), ""),
|
||||
fieldOf(source, "Pages"),
|
||||
]),
|
||||
);
|
||||
|
||||
/**
|
||||
* A source's entry in the bibliography, as the style writes the paragraph (`b:Bibliography`)
|
||||
*
|
||||
* @param authorMain - Its authors, or a dash when they're the authors of the entry before it
|
||||
*/
|
||||
const bibliographyEntry = (source: WordSource, authorMain: string): FormattedText => {
|
||||
const field = (name: Field): string => fieldOf(source, name);
|
||||
const names = (role: Role): WordNames | undefined => source.names[role];
|
||||
const cEditors = countOf(names("Editor"));
|
||||
const cTranslators = countOf(names("Translator"));
|
||||
const cComposers = countOf(names("Composer"));
|
||||
const cCompilers = countOf(names("Compiler"));
|
||||
const cProducers = countOf(names("ProducerName"));
|
||||
const cConductors = countOf(names("Conductor"));
|
||||
|
||||
const author = formatPersonsAuthor(names("Author"));
|
||||
const compiler = formatPersons(names("Compiler"));
|
||||
const compilerLF = formatPersonsAuthor(names("Compiler"));
|
||||
const editor = formatPersons(names("Editor"));
|
||||
const editorLF = formatPersonsAuthor(names("Editor"));
|
||||
const translator = formatPersons(names("Translator"));
|
||||
const translatorLF = formatPersonsAuthor(names("Translator"));
|
||||
const performer = formatPersons(names("Performer"));
|
||||
const intervieweeLF = formatPersonsAuthor(names("Interviewee"));
|
||||
const producerName = formatPersons(names("ProducerName"));
|
||||
const interviewer = formatPersons(names("Interviewer"));
|
||||
const writer = formatPersons(names("Writer"));
|
||||
const writerLF = formatPersonsAuthor(names("Writer"));
|
||||
const director = formatPersons(names("Director"));
|
||||
const inventorLF = formatPersonsAuthor(names("Inventor"));
|
||||
const bookAuthor = formatPersons(names("BookAuthor"));
|
||||
const performerLF = formatPersonsAuthor(names("Performer"));
|
||||
const conductorLF = formatPersonsAuthor(names("Conductor"));
|
||||
const conductor = formatPersons(names("Conductor"));
|
||||
const composerLF = formatPersonsAuthor(names("Composer"));
|
||||
const composer = formatPersons(names("Composer"));
|
||||
const artist = formatPersonsAuthor(names("Artist"));
|
||||
|
||||
const writerLFDot = xsl.appendDot(writerLF);
|
||||
const monthDayDot = xsl.appendDot(getMonthDay(source));
|
||||
const yearDot = xsl.appendDot(getYear(source));
|
||||
const tempCSPP = templateA(templateCityStateProvince(source), field("Publisher"), "");
|
||||
const tempRICP = templateRICP(source);
|
||||
const tempCPMDP = templateCPMDP(source);
|
||||
const tempMDEP = templateMDEP(source);
|
||||
const tempRM = templateRM(source);
|
||||
const tempTC = templateC(field("Theater"), field("City"));
|
||||
const tempIC = templateC(field("Institution"), field("City"));
|
||||
const tempCPMD = templateA(templateCityStateProvince(source), field("Publisher"), getMonthDay(source));
|
||||
const tempSC = templateC(field("Station"), field("City"));
|
||||
const tempCP = templateCP(source);
|
||||
const tempCCMD = templateCCMD(source);
|
||||
const tempPVIP = templatePVIP(source);
|
||||
const tempDAUD = templateDAUD(source);
|
||||
|
||||
const titleDot = xsl.appendDot(field("Title"));
|
||||
const albumTitleDot = xsl.appendDot(field("AlbumTitle"));
|
||||
const pagesDot = xsl.appendDot(field("Pages"));
|
||||
const bookTitleDot = xsl.appendDot(field("BookTitle"));
|
||||
const conferenceNameDot = xsl.appendDot(field("ConferenceName"));
|
||||
const broadcasterDot = xsl.appendDot(field("Broadcaster"));
|
||||
const interviewTitle = field("Title");
|
||||
const publisher = field("Publisher");
|
||||
const publicationTitle = field("PublicationTitle");
|
||||
const publicationTitleDot = xsl.appendDot(publicationTitle);
|
||||
const institutionDot = xsl.appendDot(field("Institution"));
|
||||
const journalName = field("JournalName");
|
||||
const journalNameDot = xsl.appendDot(journalName);
|
||||
const internetSiteTitleDot = xsl.appendDot(field("InternetSiteTitle"));
|
||||
const mediumDot = xsl.appendDot(field("Medium"));
|
||||
const issueDot = xsl.appendDot(field("Issue"));
|
||||
const distributorDot = xsl.appendDot(field("Distributor"));
|
||||
const numberVolumesDot = xsl.appendDot(formatIf(Strings.VolumesAfterShortUnCap, field("NumberVolumes")));
|
||||
const noIssueDot = xsl.appendDot(formatIf(Strings.NumberShortUnCap, field("Issue")));
|
||||
const editionDot = xsl.appendDot(field("Edition"));
|
||||
const broadcastTitle = field("BroadcastTitle");
|
||||
const versionDot = xsl.appendDot(field("Version"));
|
||||
const broadcastTitleDot = xsl.appendDot(broadcastTitle);
|
||||
const periodicalTitle = field("PeriodicalTitle");
|
||||
const periodicalTitleDot = xsl.appendDot(periodicalTitle);
|
||||
const productionCompany = field("ProductionCompany");
|
||||
const volume = field("Volume");
|
||||
|
||||
const prefixVersionDot = versionDot ? Strings.VersionShortCap + General.Space + versionDot : "";
|
||||
const prefixEditorDot = prefixed(editor, cEditors, Strings.EditorShortCap, Strings.EditorShortCap);
|
||||
const prefixTranslatorDot = prefixed(translator, cTranslators, Strings.TranslatorShortCap, Strings.TranslatorsShortCap);
|
||||
const sufixEditorLFDot = suffixed(editorLF, cEditors, Strings.EditorShortUnCap, Strings.EditorsShortUnCap);
|
||||
const prefixConductorDot = prefixed(conductor, cConductors, Strings.ConductorShortCap, Strings.ConductorsShortCap);
|
||||
const prefixComposerDot = prefixed(composer, cComposers, Strings.ComposerShortCap, Strings.ComposersShortCap);
|
||||
const prefixCompilerDot = prefixed(compiler, cCompilers, Strings.CompilerShortCap, Strings.CompilersShortCap);
|
||||
const sufixCompilerLFDot = suffixed(compilerLF, cCompilers, Strings.CompilerShortUnCap, Strings.CompilersShortUnCap);
|
||||
const sufixTranslatorLFDot = suffixed(translatorLF, cTranslators, Strings.TranslatorShortUnCap, Strings.TranslatorsShortUnCap);
|
||||
|
||||
const prefixVolume = formatIf(volumeFormatOf(volume, Strings.VolumeShortCap, Strings.VolumesShortCap), volume);
|
||||
const prefixVolumeDot = xsl.appendDot(prefixVolume);
|
||||
// The volume, and "in" the book's title in italics, which is written with its formatting
|
||||
const bookTitle = field("BookTitle");
|
||||
const inBook = bookTitleDot !== "" && prefixVolumeDot !== "";
|
||||
const volumeBookTitle = join(
|
||||
prefixVolume,
|
||||
inBook ? General.ListSeparator : "",
|
||||
bookTitle ? xsl.stringFormat(inBook ? Strings.InNameUnCap : Strings.InNameCap, applyItalic(bookTitle)) : "",
|
||||
);
|
||||
const theCapShortPrefixVolumeDot = prefixVolumeDot;
|
||||
|
||||
const prodDot = xsl.appendDot(producerName || productionCompany);
|
||||
const prod = producerName || productionCompany;
|
||||
const prefixProdDot =
|
||||
producerName || productionCompany
|
||||
? (cProducers > 1
|
||||
? Strings.ProducersShortCap + General.Space
|
||||
: cProducers === 1
|
||||
? Strings.ProducerShortCap + General.Space
|
||||
: "") + prodDot
|
||||
: "";
|
||||
|
||||
const authorDot = xsl.appendDot(author);
|
||||
const sectionAuthorDot = authorDot;
|
||||
const bookAuthorDot = xsl.appendDot(bookAuthor);
|
||||
const performerLFDot = xsl.appendDot(performerLF);
|
||||
const artistDot = xsl.appendDot(artist);
|
||||
const interviewerDot = xsl.appendDot(interviewer);
|
||||
const intervieweeLFDot = xsl.appendDot(intervieweeLF);
|
||||
const conductorLFDot = xsl.appendDot(conductorLF);
|
||||
const inventorLFDot = xsl.appendDot(inventorLF);
|
||||
const writerDot = xsl.appendDot(writer);
|
||||
const composerLFDot = xsl.appendDot(composerLF);
|
||||
|
||||
const theAuthorSufixDot = xsl.appendDot(
|
||||
author
|
||||
? authorMain
|
||||
: editorLF &&
|
||||
["Book", "Misc", "ArticleInAPeriodical", "ConferenceProceedings", "InternetSite", "DocumentFromInternetSite"].includes(
|
||||
source.type,
|
||||
)
|
||||
? suffixed(editorLF, cEditors, Strings.EditorShortUnCap, Strings.EditorsShortUnCap)
|
||||
: compilerLF && source.type === "Misc"
|
||||
? suffixed(compilerLF, cCompilers, Strings.CompilerShortUnCap, Strings.CompilersShortUnCap)
|
||||
: translatorLF && (source.type === "Book" || source.type === "Misc")
|
||||
? suffixed(translatorLF, cTranslators, Strings.TranslatorShortUnCap, Strings.TranslatorsShortUnCap)
|
||||
: "",
|
||||
);
|
||||
|
||||
const theUnCapLongByAuthor = formatIf(Strings.ByUnCap, bookAuthor);
|
||||
const theCapLongByAuthor = formatIf(Strings.ByCap, bookAuthor);
|
||||
const theCapLongPrefixEditorDot = xsl.appendDot(author ? formatIf(Strings.EditedByCap, editor) : "");
|
||||
const theCapLongPrefixCompilerDot = xsl.appendDot(author || editor ? formatIf(Strings.CompiledByCap, compiler) : "");
|
||||
const theCapLongPrefixTranslatorDot = xsl.appendDot(author || editor || compiler ? formatIf(Strings.TranslatedByCap, translator) : "");
|
||||
const theCapLongPrefixEditedBy = formatIf(Strings.EditedByCap, editor);
|
||||
const theCapLongPrefixEditedByDot = xsl.appendDot(theCapLongPrefixEditedBy);
|
||||
const theUnCapLongPrefixEditedBy = formatIf(Strings.EditedByUnCap, editor);
|
||||
const theUnCapLongPrefixEditedByDot = xsl.appendDot(theUnCapLongPrefixEditedBy);
|
||||
const theCapLongPrefixTranslatedBy = formatIf(Strings.TranslatedByCap, translator);
|
||||
const theCapLongPrefixTranslatedByDot = xsl.appendDot(theCapLongPrefixTranslatedBy);
|
||||
const theUnCapLongPrefixTranslatedBy = formatIf(Strings.TranslatedByUnCap, translator);
|
||||
const theUnCapLongPrefixTranslatedByDot = xsl.appendDot(theUnCapLongPrefixTranslatedBy);
|
||||
|
||||
const theCPAuthorSufixDot = xsl.appendDot(
|
||||
author ? authorMain : suffixed(editorLF, cEditors, Strings.EditorShortUnCap, Strings.EditorsShortUnCap),
|
||||
);
|
||||
// The style writes the editors of conference proceedings, and of others, with the same variable as a book's
|
||||
const theCPCapLongPrefixEditorDot = theCapLongPrefixEditorDot;
|
||||
const theCapLongPrefixDirectedByDot = xsl.appendDot(formatIf(Strings.DirectedByCap, director));
|
||||
const theCapLongPrefixPerformedByDot = xsl.appendDot(formatIf(Strings.PerformedByCap, performer));
|
||||
const theCapLongPrefixProducedByDot = xsl.appendDot(formatIf(Strings.ProducedByCap, prod));
|
||||
|
||||
const entries: Readonly<Record<WordSourceType, () => FormattedText>> = {
|
||||
Book: () =>
|
||||
join(
|
||||
theAuthorSufixDot,
|
||||
when(yearDot, spaceIf(theAuthorSufixDot), yearDot),
|
||||
when(titleDot, spaceIf(theAuthorSufixDot, yearDot), applyItalic(titleDot)),
|
||||
when(editionDot, spaceIf(theAuthorSufixDot, yearDot, titleDot), editionDot),
|
||||
when(theCapLongPrefixEditorDot, spaceIf(theAuthorSufixDot, yearDot, titleDot, editionDot), theCapLongPrefixEditorDot),
|
||||
when(
|
||||
theCapLongPrefixTranslatorDot,
|
||||
spaceIf(theAuthorSufixDot, yearDot, titleDot, theCapLongPrefixEditorDot, editionDot),
|
||||
theCapLongPrefixTranslatorDot,
|
||||
),
|
||||
when(
|
||||
theCapShortPrefixVolumeDot,
|
||||
spaceIf(theAuthorSufixDot, yearDot, titleDot, theCapLongPrefixEditorDot, theCapLongPrefixTranslatorDot, editionDot),
|
||||
theCapShortPrefixVolumeDot,
|
||||
),
|
||||
when(
|
||||
numberVolumesDot,
|
||||
spaceIf(
|
||||
theAuthorSufixDot,
|
||||
yearDot,
|
||||
titleDot,
|
||||
theCapLongPrefixEditorDot,
|
||||
theCapLongPrefixTranslatorDot,
|
||||
theCapShortPrefixVolumeDot,
|
||||
editionDot,
|
||||
),
|
||||
numberVolumesDot,
|
||||
),
|
||||
when(
|
||||
tempCSPP,
|
||||
spaceIf(
|
||||
theAuthorSufixDot,
|
||||
yearDot,
|
||||
titleDot,
|
||||
theCapLongPrefixEditorDot,
|
||||
theCapLongPrefixTranslatorDot,
|
||||
theCapShortPrefixVolumeDot,
|
||||
editionDot,
|
||||
numberVolumesDot,
|
||||
),
|
||||
tempCSPP,
|
||||
),
|
||||
),
|
||||
ConferenceProceedings: () =>
|
||||
join(
|
||||
theCPAuthorSufixDot,
|
||||
when(yearDot, spaceIf(theCPAuthorSufixDot), yearDot),
|
||||
when(titleDot, spaceIf(theCPAuthorSufixDot, yearDot), quoted(titleDot)),
|
||||
when(theCPCapLongPrefixEditorDot, spaceIf(theCPAuthorSufixDot, yearDot, titleDot), theCPCapLongPrefixEditorDot),
|
||||
when(
|
||||
conferenceNameDot,
|
||||
spaceIf(theCPAuthorSufixDot, yearDot, titleDot, theCPCapLongPrefixEditorDot),
|
||||
applyItalic(conferenceNameDot),
|
||||
),
|
||||
when(tempCSPP, spaceIf(theCPAuthorSufixDot, yearDot, titleDot, theCPCapLongPrefixEditorDot, conferenceNameDot), tempCSPP),
|
||||
when(
|
||||
pagesDot,
|
||||
spaceIf(theCPAuthorSufixDot, yearDot, titleDot, theCPCapLongPrefixEditorDot, conferenceNameDot, tempCSPP),
|
||||
pagesDot,
|
||||
),
|
||||
),
|
||||
BookSection: () =>
|
||||
join(
|
||||
sectionAuthorDot,
|
||||
when(yearDot, spaceIf(sectionAuthorDot), yearDot),
|
||||
volume
|
||||
? when(
|
||||
titleDot,
|
||||
spaceIf(sectionAuthorDot, yearDot),
|
||||
applyItalic(titleDot),
|
||||
spaceIf(sectionAuthorDot, yearDot, titleDot, bookAuthorDot),
|
||||
)
|
||||
: join(
|
||||
when(titleDot, spaceIf(sectionAuthorDot, yearDot), quoted(titleDot)),
|
||||
spaceIf(sectionAuthorDot, yearDot, titleDot, bookAuthorDot),
|
||||
),
|
||||
printSpaceAndList([
|
||||
volume
|
||||
? when(textOf(volumeBookTitle), volumeBookTitle)
|
||||
: bookTitle
|
||||
? xsl.stringFormat(Strings.InNameCap, applyItalic(bookTitle))
|
||||
: "",
|
||||
!volume && !bookTitleDot ? theCapLongByAuthor : theUnCapLongByAuthor,
|
||||
!volume && !bookTitleDot && !theCapLongByAuthor ? theCapLongPrefixEditedBy : theUnCapLongPrefixEditedBy,
|
||||
theUnCapLongPrefixTranslatedBy,
|
||||
field("Pages"),
|
||||
]),
|
||||
when(
|
||||
tempCSPP,
|
||||
spaceIf(sectionAuthorDot, yearDot, titleDot, bookAuthorDot, bookTitleDot, prefixEditorDot, prefixTranslatorDot, volume),
|
||||
tempCSPP,
|
||||
),
|
||||
),
|
||||
JournalArticle: () =>
|
||||
join(
|
||||
authorDot || sufixEditorLFDot,
|
||||
when(yearDot, spaceIf(authorDot, sufixEditorLFDot), yearDot),
|
||||
when(titleDot, spaceIf(authorDot, sufixEditorLFDot, yearDot), quoted(titleDot)),
|
||||
when(
|
||||
theCPCapLongPrefixEditorDot && authorDot,
|
||||
spaceIf(authorDot, sufixEditorLFDot, yearDot, titleDot),
|
||||
theCPCapLongPrefixEditorDot,
|
||||
),
|
||||
when(
|
||||
journalName,
|
||||
spaceIf(authorDot, sufixEditorLFDot, yearDot, titleDot),
|
||||
applyItalic(tempPVIP ? journalName : journalNameDot),
|
||||
),
|
||||
when(tempPVIP, spaceIf(authorDot, sufixEditorLFDot, yearDot, titleDot, journalName), tempPVIP),
|
||||
),
|
||||
Report: () =>
|
||||
join(
|
||||
authorDot,
|
||||
when(yearDot, spaceIf(authorDot), yearDot),
|
||||
when(titleDot, spaceIf(authorDot, yearDot), publisher ? applyItalic(titleDot) : quoted(titleDot)),
|
||||
when(tempRICP, spaceIf(authorDot, yearDot, titleDot), tempRICP),
|
||||
),
|
||||
SoundRecording: () => {
|
||||
const titles = (titleSpace: string, albumSpace: string): FormattedText =>
|
||||
join(
|
||||
when(titleDot && albumTitleDot, titleSpace, quoted(titleDot)),
|
||||
when(titleDot && !albumTitleDot, titleSpace, applyItalic(titleDot)),
|
||||
when(albumTitleDot, albumSpace, applyItalic(albumTitleDot)),
|
||||
);
|
||||
if (performerLF) {
|
||||
return join(
|
||||
performerLFDot,
|
||||
when(yearDot, General.Space, yearDot),
|
||||
titles(General.Space, General.Space),
|
||||
when(prefixConductorDot, General.Space, prefixConductorDot),
|
||||
when(prefixComposerDot, General.Space, prefixComposerDot),
|
||||
when(tempRM, General.Space, tempRM),
|
||||
);
|
||||
}
|
||||
return conductorLFDot
|
||||
? join(
|
||||
conductorLFDot,
|
||||
when(yearDot, General.Space, yearDot),
|
||||
titles(General.Space, General.Space),
|
||||
when(prefixComposerDot, General.Space, prefixComposerDot),
|
||||
when(tempRM, General.Space, tempRM),
|
||||
)
|
||||
: join(
|
||||
composerLFDot,
|
||||
when(yearDot, spaceIf(composerLFDot), yearDot),
|
||||
titles(spaceIf(composerLFDot), spaceIf(composerLFDot, yearDot, titleDot)),
|
||||
when(tempRM, spaceIf(composerLFDot, yearDot, titleDot, albumTitleDot), tempRM),
|
||||
);
|
||||
},
|
||||
Performance: () =>
|
||||
join(
|
||||
writerLFDot,
|
||||
when(yearDot, spaceIf(writerLFDot), yearDot),
|
||||
when(titleDot, spaceIf(writerLFDot, yearDot), applyItalic(titleDot)),
|
||||
when(theCapLongPrefixDirectedByDot, spaceIf(writerLFDot, yearDot, titleDot), theCapLongPrefixDirectedByDot),
|
||||
when(
|
||||
theCapLongPrefixPerformedByDot,
|
||||
spaceIf(writerLFDot, yearDot, titleDot, theCapLongPrefixDirectedByDot),
|
||||
theCapLongPrefixPerformedByDot,
|
||||
),
|
||||
when(
|
||||
tempTC,
|
||||
spaceIf(writerLFDot, yearDot, titleDot, theCapLongPrefixDirectedByDot, theCapLongPrefixPerformedByDot),
|
||||
tempTC,
|
||||
),
|
||||
when(
|
||||
monthDayDot,
|
||||
spaceIf(writerLFDot, yearDot, titleDot, theCapLongPrefixDirectedByDot, theCapLongPrefixPerformedByDot, tempTC),
|
||||
monthDayDot,
|
||||
),
|
||||
),
|
||||
Art: () =>
|
||||
publicationTitle
|
||||
? join(
|
||||
normalizeSpace(artistDot),
|
||||
when(yearDot, spaceIf(artistDot), yearDot),
|
||||
when(titleDot, spaceIf(artistDot, yearDot), quoted(titleDot)),
|
||||
when(institutionDot, spaceIf(artistDot, yearDot, titleDot), institutionDot),
|
||||
when(publicationTitleDot, spaceIf(artistDot, yearDot, titleDot, institutionDot), applyItalic(publicationTitleDot)),
|
||||
when(tempCSPP, spaceIf(artistDot, yearDot, titleDot, institutionDot, publicationTitle), tempCSPP),
|
||||
)
|
||||
: join(
|
||||
normalizeSpace(artistDot),
|
||||
when(yearDot, spaceIf(artistDot), yearDot),
|
||||
when(titleDot, spaceIf(artistDot, yearDot), applyItalic(titleDot)),
|
||||
when(tempIC, spaceIf(artistDot, yearDot, titleDot), tempIC),
|
||||
),
|
||||
DocumentFromInternetSite: () =>
|
||||
join(
|
||||
theAuthorSufixDot,
|
||||
when(yearDot, spaceIf(theAuthorSufixDot), yearDot),
|
||||
when(titleDot, spaceIf(theAuthorSufixDot, yearDot), quoted(titleDot)),
|
||||
when(prefixVersionDot, spaceIf(theAuthorSufixDot, yearDot, titleDot), prefixVersionDot),
|
||||
when(internetSiteTitleDot, spaceIf(theAuthorSufixDot, yearDot, titleDot, versionDot), applyItalic(internetSiteTitleDot)),
|
||||
when(
|
||||
theCPCapLongPrefixEditorDot,
|
||||
spaceIf(theAuthorSufixDot, yearDot, titleDot, versionDot, internetSiteTitleDot),
|
||||
theCPCapLongPrefixEditorDot,
|
||||
),
|
||||
when(
|
||||
prodDot,
|
||||
spaceIf(theAuthorSufixDot, yearDot, titleDot, versionDot, internetSiteTitleDot, theCPCapLongPrefixEditorDot),
|
||||
prodDot,
|
||||
),
|
||||
when(
|
||||
monthDayDot,
|
||||
spaceIf(theAuthorSufixDot, yearDot, titleDot, versionDot, internetSiteTitleDot, theCPCapLongPrefixEditorDot, prodDot),
|
||||
monthDayDot,
|
||||
),
|
||||
),
|
||||
InternetSite: () =>
|
||||
join(
|
||||
theAuthorSufixDot,
|
||||
when(yearDot, spaceIf(theAuthorSufixDot), yearDot),
|
||||
when(titleDot, spaceIf(theAuthorSufixDot, yearDot), applyItalic(titleDot)),
|
||||
when(theCPCapLongPrefixEditorDot, spaceIf(theAuthorSufixDot, yearDot, titleDot), theCPCapLongPrefixEditorDot),
|
||||
when(prefixVersionDot, spaceIf(theAuthorSufixDot, yearDot, titleDot, theCPCapLongPrefixEditorDot), prefixVersionDot),
|
||||
when(prodDot, spaceIf(theAuthorSufixDot, yearDot, titleDot, theCPCapLongPrefixEditorDot, versionDot), prodDot),
|
||||
when(
|
||||
monthDayDot,
|
||||
spaceIf(theAuthorSufixDot, yearDot, titleDot, theCPCapLongPrefixEditorDot, versionDot, prodDot),
|
||||
monthDayDot,
|
||||
),
|
||||
),
|
||||
Patent: () =>
|
||||
join(
|
||||
inventorLFDot,
|
||||
when(yearDot, spaceIf(inventorLFDot), yearDot),
|
||||
when(titleDot, spaceIf(inventorLFDot, yearDot), titleDot),
|
||||
when(prefixEditorDot, spaceIf(inventorLFDot, yearDot, titleDot), prefixEditorDot),
|
||||
when(prefixTranslatorDot, spaceIf(inventorLFDot, yearDot, titleDot, prefixEditorDot), prefixTranslatorDot),
|
||||
when(tempCP, spaceIf(inventorLFDot, yearDot, titleDot, prefixEditorDot, prefixTranslatorDot), tempCP),
|
||||
when(monthDayDot, spaceIf(inventorLFDot, yearDot, titleDot, prefixEditorDot, prefixTranslatorDot, tempCP), monthDayDot),
|
||||
),
|
||||
Case: () =>
|
||||
join(
|
||||
when(titleDot, applyItalic(titleDot)),
|
||||
when(yearDot, spaceIf(titleDot), yearDot),
|
||||
when(field("CaseNumber"), spaceIf(titleDot, yearDot), field("CaseNumber")),
|
||||
when(tempCCMD, spaceIf(titleDot, yearDot, field("CaseNumber")), tempCCMD),
|
||||
),
|
||||
Misc: () =>
|
||||
join(
|
||||
theAuthorSufixDot,
|
||||
when(yearDot, spaceIf(theAuthorSufixDot), yearDot),
|
||||
when(titleDot, spaceIf(theAuthorSufixDot, yearDot), quoted(titleDot)),
|
||||
when(publicationTitleDot, spaceIf(theAuthorSufixDot, yearDot, titleDot), applyItalic(publicationTitleDot)),
|
||||
when(prefixVolumeDot, spaceIf(theAuthorSufixDot, yearDot, titleDot, publicationTitleDot), prefixVolumeDot),
|
||||
when(noIssueDot, spaceIf(theAuthorSufixDot, yearDot, titleDot, publicationTitleDot, prefixVolumeDot), noIssueDot),
|
||||
when(
|
||||
theCPCapLongPrefixEditorDot,
|
||||
spaceIf(theAuthorSufixDot, yearDot, titleDot, publicationTitleDot, prefixVolumeDot, issueDot),
|
||||
theCPCapLongPrefixEditorDot,
|
||||
),
|
||||
when(
|
||||
theCapLongPrefixTranslatorDot,
|
||||
spaceIf(
|
||||
theAuthorSufixDot,
|
||||
yearDot,
|
||||
titleDot,
|
||||
publicationTitleDot,
|
||||
prefixVolumeDot,
|
||||
issueDot,
|
||||
theCPCapLongPrefixEditorDot,
|
||||
),
|
||||
theCapLongPrefixTranslatorDot,
|
||||
),
|
||||
when(
|
||||
theCapLongPrefixCompilerDot,
|
||||
spaceIf(
|
||||
theAuthorSufixDot,
|
||||
yearDot,
|
||||
titleDot,
|
||||
publicationTitleDot,
|
||||
prefixVolumeDot,
|
||||
issueDot,
|
||||
theCPCapLongPrefixEditorDot,
|
||||
theCapLongPrefixTranslatorDot,
|
||||
),
|
||||
theCapLongPrefixCompilerDot,
|
||||
),
|
||||
when(
|
||||
tempCPMD,
|
||||
spaceIf(
|
||||
theAuthorSufixDot,
|
||||
yearDot,
|
||||
titleDot,
|
||||
publicationTitleDot,
|
||||
prefixVolumeDot,
|
||||
issueDot,
|
||||
theCPCapLongPrefixEditorDot,
|
||||
theCapLongPrefixTranslatorDot,
|
||||
theCapLongPrefixCompilerDot,
|
||||
),
|
||||
tempCPMD,
|
||||
),
|
||||
when(
|
||||
pagesDot,
|
||||
spaceIf(
|
||||
theAuthorSufixDot,
|
||||
yearDot,
|
||||
titleDot,
|
||||
publicationTitleDot,
|
||||
prefixVolumeDot,
|
||||
issueDot,
|
||||
theCPCapLongPrefixEditorDot,
|
||||
theCapLongPrefixTranslatorDot,
|
||||
theCapLongPrefixCompilerDot,
|
||||
tempCPMD,
|
||||
),
|
||||
pagesDot,
|
||||
),
|
||||
),
|
||||
ElectronicSource: () => {
|
||||
// The authors, or else the editors, the translators or the compilers, last name first
|
||||
const lfAuthor = authorDot || sufixEditorLFDot || sufixTranslatorLFDot || sufixCompilerLFDot;
|
||||
const before = [lfAuthor, yearDot, titleDot, publicationTitleDot, editionDot, prefixVolumeDot, mediumDot];
|
||||
return join(
|
||||
lfAuthor,
|
||||
when(yearDot, spaceIf(lfAuthor), yearDot),
|
||||
when(titleDot && publicationTitleDot, spaceIf(lfAuthor, yearDot), quoted(titleDot)),
|
||||
when(titleDot && !publicationTitleDot, spaceIf(lfAuthor, yearDot), applyItalic(titleDot)),
|
||||
when(publicationTitleDot, spaceIf(lfAuthor, yearDot, titleDot), applyItalic(publicationTitleDot)),
|
||||
when(editionDot, spaceIf(lfAuthor, yearDot, titleDot, publicationTitleDot), editionDot),
|
||||
when(prefixVolumeDot, spaceIf(lfAuthor, yearDot, titleDot, publicationTitleDot, editionDot), prefixVolumeDot),
|
||||
when(mediumDot, spaceIf(lfAuthor, yearDot, titleDot, publicationTitleDot, editionDot, prefixVolumeDot), mediumDot),
|
||||
when(authorDot && theCPCapLongPrefixEditorDot, spaceIf(...before), theCPCapLongPrefixEditorDot),
|
||||
when(theCapLongPrefixTranslatorDot && (authorDot || sufixEditorLFDot), spaceIf(...before), theCapLongPrefixTranslatorDot),
|
||||
when(prefixCompilerDot && (authorDot || sufixEditorLFDot || sufixTranslatorLFDot), spaceIf(...before), prefixCompilerDot),
|
||||
when(prefixProdDot, spaceIf(...before), prefixProdDot),
|
||||
when(tempCPMD, spaceIf(...before, prefixProdDot), tempCPMD),
|
||||
);
|
||||
},
|
||||
ArticleInAPeriodical: () =>
|
||||
join(
|
||||
theAuthorSufixDot,
|
||||
when(periodicalTitle && !theAuthorSufixDot, applyItalic(periodicalTitleDot)),
|
||||
when(yearDot, spaceIf(theAuthorSufixDot, periodicalTitle), yearDot),
|
||||
when(titleDot, spaceIf(theAuthorSufixDot, periodicalTitle, yearDot), quoted(titleDot)),
|
||||
when(periodicalTitle && theAuthorSufixDot, General.Space, applyItalic(tempMDEP ? periodicalTitle : periodicalTitleDot)),
|
||||
// The style writes a space before them in every other case, as its other tests all ask for a year, which an
|
||||
// entry always has
|
||||
when(tempMDEP, theAuthorSufixDot && periodicalTitle ? General.ListSeparator : General.Space, tempMDEP),
|
||||
),
|
||||
Film: () =>
|
||||
join(
|
||||
when(writerDot, writerLFDot),
|
||||
when(yearDot, spaceIf(writerLFDot), yearDot),
|
||||
when(titleDot, spaceIf(writerDot, yearDot), applyItalic(titleDot)),
|
||||
when(mediumDot, spaceIf(writerDot, yearDot, titleDot), mediumDot),
|
||||
when(theCapLongPrefixDirectedByDot, spaceIf(writerDot, yearDot, titleDot, mediumDot), theCapLongPrefixDirectedByDot),
|
||||
when(
|
||||
theCapLongPrefixProducedByDot,
|
||||
spaceIf(writerDot, yearDot, titleDot, theCapLongPrefixDirectedByDot, mediumDot),
|
||||
theCapLongPrefixProducedByDot,
|
||||
),
|
||||
when(
|
||||
theCapLongPrefixPerformedByDot,
|
||||
spaceIf(writerDot, yearDot, titleDot, theCapLongPrefixDirectedByDot, theCapLongPrefixProducedByDot, mediumDot),
|
||||
theCapLongPrefixPerformedByDot,
|
||||
),
|
||||
when(
|
||||
distributorDot,
|
||||
spaceIf(
|
||||
writerDot,
|
||||
yearDot,
|
||||
titleDot,
|
||||
theCapLongPrefixDirectedByDot,
|
||||
theCapLongPrefixProducedByDot,
|
||||
theCapLongPrefixPerformedByDot,
|
||||
mediumDot,
|
||||
),
|
||||
distributorDot,
|
||||
),
|
||||
),
|
||||
Interview: () => {
|
||||
const interviewTitleDot = titleDot;
|
||||
const start = join(
|
||||
when(intervieweeLFDot, interviewerDot ? intervieweeLF : intervieweeLFDot),
|
||||
when(
|
||||
interviewerDot,
|
||||
intervieweeLFDot ? General.ListSeparator : "",
|
||||
xsl.stringFormatDot(intervieweeLFDot ? Strings.InterviewByUnCap : Strings.InterviewByCap, interviewer),
|
||||
),
|
||||
when(yearDot, spaceIf(interviewerDot, intervieweeLFDot), yearDot),
|
||||
when(
|
||||
interviewTitle,
|
||||
spaceIf(interviewerDot, intervieweeLFDot, yearDot),
|
||||
broadcastTitleDot
|
||||
? join(intervieweeLFDot ? General.Space : "", quoted(interviewTitleDot))
|
||||
: join(spaceIf(intervieweeLFDot, broadcastTitleDot), applyItalic(interviewTitle)),
|
||||
),
|
||||
);
|
||||
if (field("Broadcaster")) {
|
||||
return join(
|
||||
start,
|
||||
when(
|
||||
broadcastTitleDot,
|
||||
spaceIf(interviewerDot, intervieweeLFDot, yearDot, interviewTitle),
|
||||
applyItalic(broadcastTitleDot),
|
||||
),
|
||||
when(
|
||||
broadcasterDot,
|
||||
spaceIf(interviewerDot, intervieweeLFDot, yearDot, interviewTitle, broadcastTitleDot),
|
||||
broadcasterDot,
|
||||
),
|
||||
when(
|
||||
tempSC,
|
||||
spaceIf(interviewerDot, intervieweeLFDot, yearDot, interviewTitle, broadcastTitleDot, broadcasterDot),
|
||||
tempSC,
|
||||
),
|
||||
when(
|
||||
monthDayDot,
|
||||
spaceIf(interviewerDot, intervieweeLFDot, yearDot, interviewTitle, broadcastTitleDot, broadcasterDot, tempSC),
|
||||
monthDayDot,
|
||||
),
|
||||
);
|
||||
}
|
||||
return join(
|
||||
start,
|
||||
when(
|
||||
broadcastTitleDot,
|
||||
spaceIf(interviewerDot, intervieweeLFDot, yearDot, interviewTitle),
|
||||
applyItalic(editor || translator ? broadcastTitle : broadcastTitleDot),
|
||||
),
|
||||
when(
|
||||
theCapLongPrefixEditedByDot,
|
||||
broadcastTitleDot
|
||||
? join(
|
||||
General.ListSeparator,
|
||||
theCapLongPrefixTranslatedByDot ? theUnCapLongPrefixEditedBy : theUnCapLongPrefixEditedByDot,
|
||||
)
|
||||
: theCapLongPrefixTranslatedByDot
|
||||
? theCapLongPrefixEditedBy
|
||||
: theCapLongPrefixEditedByDot,
|
||||
),
|
||||
when(
|
||||
theCapLongPrefixTranslatedByDot,
|
||||
broadcastTitleDot || theCapLongPrefixEditedByDot
|
||||
? join(General.ListSeparator, theUnCapLongPrefixTranslatedByDot)
|
||||
: theCapLongPrefixTranslatedByDot,
|
||||
),
|
||||
when(
|
||||
tempCPMDP,
|
||||
spaceIf(
|
||||
interviewerDot,
|
||||
intervieweeLFDot,
|
||||
yearDot,
|
||||
interviewTitle,
|
||||
broadcastTitleDot,
|
||||
theCapLongPrefixTranslatedByDot,
|
||||
theCapLongPrefixEditedByDot,
|
||||
),
|
||||
tempCPMDP,
|
||||
),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const entry = entries[source.type]();
|
||||
if (tempDAUD) {
|
||||
return join(entry, General.Space, tempDAUD);
|
||||
}
|
||||
// Word's XSLT writes a line break after the entry, which Word reads as a space, when the entry ends with an element,
|
||||
// such as a title in italics
|
||||
const last = entry[entry.length - 1];
|
||||
return last.italics ? join(entry, General.Space) : entry;
|
||||
};
|
||||
|
||||
/**
|
||||
* Chicago, the author-date style of the Chicago Manual of Style, as Word writes it: citations such as "(Baker 2010, 50)",
|
||||
* and a bibliography of entries such as "Baker, Anna. 2010. *The Art of Pizza.* Naples: Forno Press.", with a dash for
|
||||
* the authors of an entry with the same authors as the one before it.
|
||||
*/
|
||||
export const chicago: StyleDefinition = {
|
||||
name: "Chicago",
|
||||
file: "CHICAGO.XSL",
|
||||
version: "16",
|
||||
citation,
|
||||
bibliography: (sources: readonly WordSource[]): FormattedBibliography =>
|
||||
bibliographyOf(sources, formatPersonsAuthor, bibliographyEntry),
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { LINE_BREAK, bold, formatted, italic, join, mergeRuns, readAsWord, textOf, underline } from "./formatted-text";
|
||||
|
||||
describe("formatted text", () => {
|
||||
it("is runs, from plain text or runs", () => {
|
||||
expect(formatted("Pizza")).to.deep.equal([{ text: "Pizza" }]);
|
||||
expect(formatted("")).to.deep.equal([]);
|
||||
expect(formatted([{ text: "Pizza", bold: true }])).to.deep.equal([{ text: "Pizza", bold: true }]);
|
||||
});
|
||||
|
||||
it("joins parts, and formats them as HTML's <i>, <b> and <u> do", () => {
|
||||
expect(join("A ", italic("B ", bold("C")), underline("D"))).to.deep.equal([
|
||||
{ text: "A " },
|
||||
{ text: "B ", italics: true },
|
||||
{ text: "C", bold: true, italics: true },
|
||||
{ text: "D", underline: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it("reads as its text, without its formatting or line breaks", () => {
|
||||
expect(textOf("Pizza")).to.equal("Pizza");
|
||||
expect(textOf(join("A", LINE_BREAK, italic("B")))).to.equal("AB");
|
||||
});
|
||||
});
|
||||
|
||||
describe("readAsWord", () => {
|
||||
it("collapses each run of spaces, tabs and line feeds into one space, as HTML does", () => {
|
||||
expect(readAsWord(join("A \t\n B", italic(" C"), " ", bold(" D")))).to.deep.equal([
|
||||
{ text: "A B" },
|
||||
{ text: " C", italics: true },
|
||||
{ text: " " },
|
||||
{ text: "D", bold: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops the spaces at the start of the paragraph and after a line break", () => {
|
||||
expect(readAsWord(join(" A", LINE_BREAK, " B"))).to.deep.equal([{ text: "A" }, { text: "", lineBreak: true }, { text: "B" }]);
|
||||
});
|
||||
|
||||
it("joins runs with the same formatting, and drops empty ones", () => {
|
||||
expect(readAsWord([{ text: "A" }, { text: "" }, { text: "B", bold: false }, { text: "C", italics: true }])).to.deep.equal([
|
||||
{ text: "AB" },
|
||||
{ text: "C", italics: true },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeRuns", () => {
|
||||
it("joins runs with the same formatting, without changing their spaces", () => {
|
||||
expect(mergeRuns([{ text: "A " }, { text: " B" }, { text: "C", italics: true }, ...LINE_BREAK, { text: "D" }])).to.deep.equal([
|
||||
{ text: "A B" },
|
||||
{ text: "C", italics: true },
|
||||
{ text: "", lineBreak: true },
|
||||
{ text: "D" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Text with formatting, as a style of citation writes a citation or a bibliography's entries: runs of text, each bold,
|
||||
* italic or underlined, or a line break.
|
||||
*
|
||||
* Word's styles write HTML, which Word reads into runs. The styles here write runs, which are read the same way by
|
||||
* {@link readAsWord}: spaces collapse, as they do in HTML.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
/** A run of text with its formatting, or a line break */
|
||||
export type FormattedRun = {
|
||||
readonly text: string;
|
||||
readonly bold?: boolean;
|
||||
readonly italics?: boolean;
|
||||
readonly underline?: boolean;
|
||||
/** A line break, in place of text, as an HTML `<br>` */
|
||||
readonly lineBreak?: boolean;
|
||||
};
|
||||
|
||||
/** Text with formatting: its runs, in order */
|
||||
export type FormattedText = readonly FormattedRun[];
|
||||
|
||||
/** Plain text, or text with formatting */
|
||||
export type TextLike = string | FormattedText;
|
||||
|
||||
/** Text with formatting, from plain text or text with formatting */
|
||||
export const formatted = (text: TextLike): FormattedText => (typeof text === "string" ? (text ? [{ text }] : []) : text);
|
||||
|
||||
/** The parts, one after another */
|
||||
export const join = (...parts: readonly TextLike[]): FormattedText => parts.flatMap(formatted);
|
||||
|
||||
/** The text, in italics, as HTML's `<i>` */
|
||||
export const italic = (...parts: readonly TextLike[]): FormattedText => join(...parts).map((run) => ({ ...run, italics: true }));
|
||||
|
||||
/** The text, in bold, as HTML's `<b>` */
|
||||
export const bold = (...parts: readonly TextLike[]): FormattedText => join(...parts).map((run) => ({ ...run, bold: true }));
|
||||
|
||||
/** The text, underlined, as HTML's `<u>` */
|
||||
export const underline = (...parts: readonly TextLike[]): FormattedText => join(...parts).map((run) => ({ ...run, underline: true }));
|
||||
|
||||
/** A line break, as HTML's `<br>` */
|
||||
export const LINE_BREAK: FormattedText = [{ text: "", lineBreak: true }];
|
||||
|
||||
/** The text without its formatting, as an XSL style reads the string value of what it has written */
|
||||
export const textOf = (text: TextLike): string => (typeof text === "string" ? text : text.map((run) => run.text).join(""));
|
||||
|
||||
const sameFormat = (a: FormattedRun, b: FormattedRun): boolean =>
|
||||
!a.lineBreak && !b.lineBreak && !!a.bold === !!b.bold && !!a.italics === !!b.italics && !!a.underline === !!b.underline;
|
||||
|
||||
/**
|
||||
* The runs as Word reads a style's HTML into a paragraph: each run of spaces, tabs and line feeds becomes one space, and
|
||||
* there is none at the start of the paragraph or after a line break, as in HTML. Runs with the same formatting are
|
||||
* joined, and empty ones dropped.
|
||||
*/
|
||||
export const readAsWord = (text: TextLike): FormattedText => {
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const runs: FormattedRun[] = [];
|
||||
// Whether the text so far ends with a space, or is at the start of the paragraph or of a line
|
||||
let atSpace = true;
|
||||
for (const run of formatted(text)) {
|
||||
if (run.lineBreak) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
runs.push(run);
|
||||
atSpace = true;
|
||||
continue;
|
||||
}
|
||||
let collapsed = run.text.replace(/[ \t\r\n]+/g, " ");
|
||||
if (atSpace && collapsed.startsWith(" ")) {
|
||||
collapsed = collapsed.slice(1);
|
||||
}
|
||||
if (!collapsed) {
|
||||
continue;
|
||||
}
|
||||
atSpace = collapsed.endsWith(" ");
|
||||
const last = runs[runs.length - 1];
|
||||
if (last && sameFormat(last, run)) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
runs[runs.length - 1] = { ...last, text: last.text + collapsed };
|
||||
} else {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
runs.push({ ...run, text: collapsed });
|
||||
}
|
||||
}
|
||||
return runs;
|
||||
};
|
||||
|
||||
/** The runs, with runs next to each other that have the same formatting joined, as Word joins a citation's sources */
|
||||
export const mergeRuns = (text: TextLike): FormattedText =>
|
||||
formatted(text).reduce<readonly FormattedRun[]>((runs, run) => {
|
||||
const last = runs[runs.length - 1];
|
||||
return last && sameFormat(last, run) ? [...runs.slice(0, -1), { ...last, text: last.text + run.text }] : [...runs, run];
|
||||
}, []);
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { describeWordOutput } from "tests/bibliography";
|
||||
|
||||
import expected from "./fixtures/gb7714.json";
|
||||
import { gb7714 } from "./gb7714";
|
||||
|
||||
describe("gb7714", () => {
|
||||
it("is Word's GB7714", () => {
|
||||
expect(gb7714).toMatchObject({ name: "GB7714", file: "GB.XSL", version: "2005" });
|
||||
});
|
||||
|
||||
describeWordOutput(gb7714, expected);
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* The GB7714 style of citation, written from Word's (GB.XSL). It is Word's ISO 690 by first element and date but for a
|
||||
* few of its templates: it cites a source by its tag when the source has no author or year, and writes a space after a
|
||||
* website's version and date, and a report's department and institution, by different fields.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { firstElementBibliography, firstElementCitation } from "./iso-690-family";
|
||||
import type { StyleDefinition } from "./style";
|
||||
|
||||
/** GB7714, as Word writes it */
|
||||
export const gb7714: StyleDefinition = {
|
||||
name: "GB7714",
|
||||
file: "GB.XSL",
|
||||
version: "2005",
|
||||
citation: firstElementCitation("GB7714"),
|
||||
bibliography: firstElementBibliography("GB7714"),
|
||||
};
|
||||
@@ -0,0 +1,501 @@
|
||||
/**
|
||||
* The templates of Word's two GOST styles, GOST - Name Sort (GostName.XSL) and GOST - Title Sort (GostTitle.XSL), which
|
||||
* write citations and bibliographies as the Russian standard GOST 7.1 has them, such as "Dickens Charles John How to
|
||||
* Write Bibliographies [Book]. - Chicago : Adventure Works Press, 2006."
|
||||
*
|
||||
* The two styles are the same but for how an entry starts and how the bibliography is sorted. GOST - Name Sort starts an
|
||||
* entry with its authors in bold, and leaves out the people who are those authors from the rest of it. GOST - Title Sort
|
||||
* starts it with its title in bold, and names its authors after the title.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type FormattedText, bold, join, textOf } from "./formatted-text";
|
||||
import { LOCALS } from "./locals";
|
||||
import type { CitedSource } from "./style";
|
||||
import { translate, xslTemplates } from "./xsl";
|
||||
import {
|
||||
type Field,
|
||||
type Role,
|
||||
type WordNames,
|
||||
type WordPerson,
|
||||
type WordSource,
|
||||
type WordSourceType,
|
||||
fieldOf,
|
||||
peopleOf,
|
||||
} from "../word-source";
|
||||
|
||||
const { General, Gost, Strings, SourceNames } = LOCALS;
|
||||
const xsl = xslTemplates(General);
|
||||
|
||||
// The style's constants (constGost_*), each the wording it is made of
|
||||
const NON_BREAKING_SPACE = General.NonBreakingSpace;
|
||||
const SOURCE_TYPE_OPEN = General.Space + Gost.GeneralOpen;
|
||||
const SOURCE_TYPE_CLOSE = Gost.GeneralClose;
|
||||
const SHORT_TITLE_HEADER = NON_BREAKING_SPACE + General.Equal + General.Space;
|
||||
const COLON_SEPARATOR = NON_BREAKING_SPACE + General.EnumSeparator;
|
||||
const SEMICOLON_SEPARATOR = NON_BREAKING_SPACE + General.GroupSeparator;
|
||||
const HYPHEN_SECTION_HEADER = General.Dot + NON_BREAKING_SPACE + General.FromToDash + General.Space;
|
||||
const SLASH_HEADER = NON_BREAKING_SPACE + Gost.OneSlash + General.Space;
|
||||
const COLLECTION_NAME_HEADER = NON_BREAKING_SPACE + Gost.TwoSlash + General.Space;
|
||||
const PERSON_AND_OTHERS = General.Space + Gost.GeneralOpen + Strings.AndOthersUnCap + Gost.GeneralClose;
|
||||
const SINE_LOCO = Gost.GeneralOpen + Strings.SineLocoShort + Gost.GeneralClose;
|
||||
const SINE_NOMINE = Gost.GeneralOpen + Strings.SineNomineShort + Gost.GeneralClose;
|
||||
|
||||
/** Which of the two styles is writing: GOST - Name Sort, or GOST - Title Sort */
|
||||
export type GostSort = "name" | "title";
|
||||
|
||||
/**
|
||||
* The roles a type of source is named by, in the order they're looked for (`MainContributors`). GOST looks for more
|
||||
* roles than Word does to tell sources apart
|
||||
*/
|
||||
const MAIN_ROLES: Readonly<Record<WordSourceType, readonly Role[]>> = {
|
||||
Book: ["Author", "Editor", "Translator"],
|
||||
BookSection: ["Author"],
|
||||
JournalArticle: ["Author", "Editor"],
|
||||
ArticleInAPeriodical: ["Author"],
|
||||
ConferenceProceedings: ["Author"],
|
||||
Report: ["Author"],
|
||||
SoundRecording: ["Artist", "Performer", "Composer", "Conductor", "ProducerName"],
|
||||
Performance: ["Writer", "Director", "Performer", "ProducerName"],
|
||||
Art: ["Artist"],
|
||||
DocumentFromInternetSite: ["Author"],
|
||||
InternetSite: ["Author"],
|
||||
Film: ["Director", "Writer", "Performer", "ProducerName"],
|
||||
Interview: ["Interviewee"],
|
||||
Patent: ["Inventor"],
|
||||
ElectronicSource: ["Author", "Editor", "ProducerName", "Translator"],
|
||||
Case: ["Author", "Counsel"],
|
||||
Misc: ["Author", "Editor", "Compiler", "Translator"],
|
||||
};
|
||||
|
||||
/** The string value of the people with a role, or the organization: their names one after another, as XPath reads it */
|
||||
const stringOf = (names: WordNames): string =>
|
||||
"corporate" in names ? names.corporate : names.people.map(({ last, first, middle }) => last + first + middle).join("");
|
||||
|
||||
/** The people a source is named by (`b:Author/b:Main`, as `populateMain` writes it), an organization, or no one */
|
||||
type Main = { readonly people: readonly WordPerson[]; readonly corporate: string };
|
||||
|
||||
/** The people or organization a source is named by: those of the first of its type's roles it has a name in (`populateMain`) */
|
||||
export const mainOf = (source: WordSource): Main => {
|
||||
const role = MAIN_ROLES[source.type].find((candidate) => {
|
||||
const candidateNames = source.names[candidate];
|
||||
return candidateNames !== undefined && stringOf(candidateNames).length > 0;
|
||||
});
|
||||
const names = role === undefined ? undefined : source.names[role];
|
||||
if (names === undefined) {
|
||||
return { people: [], corporate: "" };
|
||||
}
|
||||
return "corporate" in names ? { people: [], corporate: names.corporate } : { people: names.people, corporate: "" };
|
||||
};
|
||||
|
||||
const stringOfMain = (main: Main): string => (main.corporate ? main.corporate : stringOf({ people: main.people }));
|
||||
|
||||
/**
|
||||
* The separator after a person of a list of people (`formatPersonSeparator`): " [et al.]" after the first of four or more,
|
||||
* a comma between the others, and "and" before the last
|
||||
*/
|
||||
const formatPersonSeparator = (position: number, count: number): string => {
|
||||
if (count > 3) {
|
||||
return PERSON_AND_OTHERS;
|
||||
}
|
||||
if (count - 1 > position) {
|
||||
return General.ListSeparator;
|
||||
}
|
||||
return position === count - 1 ? General.Space + Strings.AndUnCap + General.Space : "";
|
||||
};
|
||||
|
||||
/**
|
||||
* People with a role, last name first (`formatPersons`). Of four or more, only the first is written, with " [et al.]".
|
||||
* The template writes an organization in their place, which its callers here write themselves
|
||||
*/
|
||||
export const formatPersons = (people: readonly WordPerson[]): string => {
|
||||
const count = people.length;
|
||||
const shown = count >= 4 ? people.slice(0, 1) : people;
|
||||
return shown.map((person, index) => xsl.formatName(person, Gost.Authors) + formatPersonSeparator(index + 1, count)).join("");
|
||||
};
|
||||
|
||||
/**
|
||||
* The people with a role, after the role's abbreviation, such as "ed. Hall Grace", when one of them has a last name
|
||||
* (`formatEditor`, `formatTranslator` and the like)
|
||||
*/
|
||||
const formatRole = (source: WordSource, role: Role, header: string): string => {
|
||||
const people = peopleOf(source, role);
|
||||
return people.some(({ last }) => last.length > 0) ? `${header}${General.Space}${formatPersons(people)}` : "";
|
||||
};
|
||||
|
||||
/** The performers after "perf.", or the group that performed (`formatPerformer`) */
|
||||
const formatPerformer = (source: WordSource): string => {
|
||||
const names = source.names.Performer;
|
||||
return names !== undefined && "corporate" in names
|
||||
? `${Strings.PerformerShortUnCap}${General.Space}${names.corporate}`
|
||||
: formatRole(source, "Performer", Strings.PerformerShortUnCap);
|
||||
};
|
||||
|
||||
/** The authors after "auth.", or the organization the source is named by (`formatAuthor`) */
|
||||
const formatAuthor = (source: WordSource, main: Main): string => {
|
||||
if (main.corporate) {
|
||||
return `${Strings.AuthorShortUnCap}${General.Space}${main.corporate}`;
|
||||
}
|
||||
const people = peopleOf(source, "Author");
|
||||
return people.length > 0 ? `${Strings.AuthorShortUnCap}${General.Space}${formatPersons(people)}` : "";
|
||||
};
|
||||
|
||||
/** The volume, such as "Vol. 3", or "Vols. 2-3" for more than one (the `volVolume` variable) */
|
||||
const formatVolume = (volume: string, single: string, plural: string): string => {
|
||||
if (volume.length === 0) {
|
||||
return "";
|
||||
}
|
||||
const format = volume.includes(",") ? plural : translate(volume, General.Hyphens, "") === volume ? single : plural;
|
||||
return textOfFormat(format, volume);
|
||||
};
|
||||
|
||||
/** The pages, such as "p. 5", or "pp. 10-20" for more than one */
|
||||
const formatPages = (pages: string): string => {
|
||||
if (pages.length === 0) {
|
||||
return "";
|
||||
}
|
||||
const prefix = pages.includes(",")
|
||||
? Strings.PagesCountinousShort
|
||||
: translate(pages, General.Hyphens, "") === pages
|
||||
? Strings.PageShort
|
||||
: Strings.PagesCountinousShort;
|
||||
return `${prefix}${General.Space}${pages}`;
|
||||
};
|
||||
|
||||
const textOfFormat = (format: string, parameter: string): string =>
|
||||
xsl
|
||||
.stringFormat(format, parameter)
|
||||
.map((run) => run.text)
|
||||
.join("");
|
||||
|
||||
/** Parts joined by a separator, each written only when it isn't empty */
|
||||
const separated = (separator: string, ...parts: readonly string[]): string => parts.filter((part) => part.length > 0).join(separator);
|
||||
|
||||
/** Up to four parts with " : " between them (`formatColonElement`) */
|
||||
const formatColonElement = (...parts: readonly string[]): string => separated(COLON_SEPARATOR, ...parts);
|
||||
|
||||
/**
|
||||
* Where a source was published and by whom, such as "Chicago : Press", with "[s.l.]" or "[s.n.]" for one that's missing
|
||||
* (`formatLocationElement`). With neither, it is the source's distributor
|
||||
*/
|
||||
const formatLocationElement = (
|
||||
source: WordSource,
|
||||
location: string,
|
||||
publisher: string,
|
||||
{ distributor = "", noLocation = false }: { readonly distributor?: string; readonly noLocation?: boolean } = {},
|
||||
): string => {
|
||||
if (location.length === 0 && publisher.length === 0) {
|
||||
// The template reads the source's distributor here, rather than the one it's given
|
||||
return formatColonElement("", "", fieldOf(source, "Distributor"));
|
||||
}
|
||||
return formatColonElement(
|
||||
noLocation ? "" : location.length === 0 ? SINE_LOCO : location,
|
||||
publisher.length === 0 ? SINE_NOMINE : publisher,
|
||||
distributor,
|
||||
);
|
||||
};
|
||||
|
||||
/** A section after " - ", such as ". - Chicago : Press, 2006", or nothing when both its parts are empty (`formatHyphenSection`) */
|
||||
const formatHyphenSection = (first: string, second = ""): string =>
|
||||
first.length === 0 && second.length === 0 ? "" : HYPHEN_SECTION_HEADER + separated(General.ListSeparator, first, second);
|
||||
|
||||
/** A date, such as "14 March 2018", or nothing without a year (`formatDateMonthYear` and `formatDateCore`) */
|
||||
const formatDate = (day: string, month: string, year: string): string =>
|
||||
year.length === 0 ? "" : xsl.formatDatePrivate(day, month, year, Gost.Date);
|
||||
|
||||
/**
|
||||
* The people responsible for the source, other than the ones it's named by, after " / ", in brackets when there are more
|
||||
* than two kinds of them (`formatPrimaryResponsibilities`). How many there are counts the kinds the source has, less one
|
||||
* for the people it's named by in GOST - Name Sort
|
||||
*/
|
||||
const formatPrimaryResponsibilities = (count: number, first = "", second = "", third = ""): string =>
|
||||
(count > 0 ? SLASH_HEADER : "") +
|
||||
(count > 2 ? Gost.GeneralOpen : "") +
|
||||
first +
|
||||
(first !== "" && count > 1 ? SEMICOLON_SEPARATOR : "") +
|
||||
second +
|
||||
((first === "" && count > 1) || count > 2 ? SEMICOLON_SEPARATOR : "") +
|
||||
third +
|
||||
(count > 2 ? Gost.GeneralClose : "");
|
||||
|
||||
/**
|
||||
* The people responsible for the source's publication, such as its editors, and the collection it is in, after " // "
|
||||
* (`formatSecondaryResponsibilities`)
|
||||
*/
|
||||
const formatSecondaryResponsibilities = (collection: string, ...elements: readonly string[]): string => {
|
||||
const written = elements.filter((element) => element.length > 0);
|
||||
if (collection.length > 0) {
|
||||
return COLLECTION_NAME_HEADER + collection + written.map((element) => SLASH_HEADER + element).join("");
|
||||
}
|
||||
return written.length > 0 ? SLASH_HEADER + written.join(SLASH_HEADER) : "";
|
||||
};
|
||||
|
||||
/** The roles each type counts as primary responsibilities (`getNonEmpty_*_PrimSectionsCount`) */
|
||||
const PRIMARY_ROLES: Readonly<Record<WordSourceType, readonly Role[]>> = {
|
||||
Book: ["Author"],
|
||||
BookSection: ["Author"],
|
||||
JournalArticle: ["Author"],
|
||||
ArticleInAPeriodical: ["Author"],
|
||||
ConferenceProceedings: ["Author"],
|
||||
Report: ["Author"],
|
||||
SoundRecording: ["Composer", "Artist"],
|
||||
Performance: ["Writer", "Performer", "Director"],
|
||||
Art: ["Artist"],
|
||||
DocumentFromInternetSite: ["Author"],
|
||||
InternetSite: ["Author"],
|
||||
Film: ["Writer", "Performer", "Director"],
|
||||
Interview: ["Interviewee"],
|
||||
Patent: ["Inventor"],
|
||||
ElectronicSource: ["Author"],
|
||||
Case: ["Author"],
|
||||
Misc: ["Author"],
|
||||
};
|
||||
|
||||
/**
|
||||
* How many of its type's roles that count as primary responsibilities the source has people or an organization in. GOST
|
||||
* - Name Sort doesn't count an organization as a book section's author, as its template counts only people
|
||||
*/
|
||||
const countOf = (source: WordSource, sort: GostSort): number =>
|
||||
PRIMARY_ROLES[source.type].filter((role) => {
|
||||
const names = source.names[role];
|
||||
return names !== undefined && ("corporate" in names ? sort === "title" || source.type !== "BookSection" : names.people.length > 0);
|
||||
}).length;
|
||||
|
||||
const field = (source: WordSource, name: Field): string => fieldOf(source, name);
|
||||
|
||||
/** Text after " : ", such as a report's type, when it isn't empty */
|
||||
const colonHeaded = (text: string): string => (text.length > 0 ? COLON_SEPARATOR + text : "");
|
||||
|
||||
/**
|
||||
* A source's entry in a bibliography (the `b:Bibliography` part of the template that matches `/`): who it's by, its
|
||||
* title and type, the people responsible for it, where and when it was published, then its comments and its standard
|
||||
* number, each after " - ", and a dot.
|
||||
*/
|
||||
export const formatEntry = (source: WordSource, sort: GostSort): FormattedText => {
|
||||
const main = mainOf(source);
|
||||
const mainString = stringOfMain(main);
|
||||
// GOST - Name Sort leaves out the people of a role who are the people the source is named by
|
||||
const unlessMain = (role: Role, write: () => string): string => {
|
||||
const names = source.names[role];
|
||||
return sort === "title" || (names !== undefined && stringOf(names) !== mainString) ? write() : "";
|
||||
};
|
||||
const authors = unlessMain("Author", () => formatAuthor(source, main));
|
||||
const editors = unlessMain("Editor", () => formatRole(source, "Editor", Strings.EditorShortUnCap));
|
||||
const translators = unlessMain("Translator", () => formatRole(source, "Translator", Strings.TranslatorShortUnCap));
|
||||
const artists = unlessMain("Artist", () => formatRole(source, "Artist", Strings.ArtistShortUnCap));
|
||||
const composers = unlessMain("Composer", () => formatRole(source, "Composer", Strings.ComposerShortUnCapIso));
|
||||
const conductors = unlessMain("Conductor", () => formatRole(source, "Conductor", Strings.ConductorShortUnCap));
|
||||
const performers = unlessMain("Performer", () => formatPerformer(source));
|
||||
const writers = unlessMain("Writer", () => formatRole(source, "Writer", Strings.WriterShortUnCap));
|
||||
const directors = unlessMain("Director", () => formatRole(source, "Director", Strings.DirectorShortUnCap));
|
||||
const producers = unlessMain("ProducerName", () => formatRole(source, "ProducerName", Strings.ProducerShortUnCap));
|
||||
const interviewees = unlessMain("Interviewee", () => formatRole(source, "Interviewee", Strings.IntervieweeShortUnCap));
|
||||
const compilers = unlessMain("Compiler", () => formatRole(source, "Compiler", Strings.CompilerShortUnCapIso));
|
||||
const inventors = unlessMain("Inventor", () => formatRole(source, "Inventor", Strings.InventorShortUnCap));
|
||||
const counsel = unlessMain("Counsel", () => formatRole(source, "Counsel", Strings.CounselShortUnCap));
|
||||
const bookAuthors = unlessMain("BookAuthor", () => formatRole(source, "BookAuthor", Strings.BookAuthorShortUnCap));
|
||||
|
||||
const volume = formatVolume(field(source, "Volume"), Strings.VolumeShortCap, Strings.VolumesShortCap);
|
||||
const pages = formatPages(field(source, "Pages"));
|
||||
const date = formatDate(field(source, "Day"), field(source, "Month"), field(source, "Year"));
|
||||
const city = field(source, "City");
|
||||
const publisher = field(source, "Publisher");
|
||||
const productionCompany = field(source, "ProductionCompany");
|
||||
|
||||
const cityPublisherYear = formatHyphenSection(formatLocationElement(source, city, publisher), field(source, "Year"));
|
||||
const cityPublisherDate = formatHyphenSection(formatLocationElement(source, city, publisher), date);
|
||||
const issueVolume = formatHyphenSection(formatColonElement(field(source, "Issue"), volume));
|
||||
const pagesSection = formatHyphenSection(pages);
|
||||
const editionSection = formatHyphenSection(field(source, "Edition"));
|
||||
const volumeSection = formatHyphenSection(volume);
|
||||
const accessedSection = formatHyphenSection(
|
||||
formatDate(field(source, "DayAccessed"), field(source, "MonthAccessed"), field(source, "YearAccessed")),
|
||||
);
|
||||
|
||||
// GOST - Name Sort leaves out the people the source is named by from how many primary responsibilities it has
|
||||
const mainSections = sort === "name" && (main.people.length > 0 || main.corporate.length > 0) ? 1 : 0;
|
||||
// GOST - Title Sort names the authors among them
|
||||
const primaryAuthors = sort === "title" ? authors : "";
|
||||
const primary = (first = "", second = "", third = ""): string =>
|
||||
formatPrimaryResponsibilities(countOf(source, sort) - mainSections, first, second, third);
|
||||
|
||||
// Each type's own sections, after its titles
|
||||
const sectionsOf: Readonly<Record<WordSourceType, () => string>> = {
|
||||
Book: () =>
|
||||
primary(primaryAuthors) +
|
||||
formatSecondaryResponsibilities("", editors, translators) +
|
||||
cityPublisherYear +
|
||||
formatHyphenSection(formatColonElement(field(source, "Edition"), volume, field(source, "NumberVolumes"), pages)),
|
||||
BookSection: () =>
|
||||
primary(primaryAuthors) +
|
||||
formatSecondaryResponsibilities(field(source, "BookTitle"), bookAuthors, editors, translators) +
|
||||
cityPublisherYear +
|
||||
formatHyphenSection(formatColonElement(field(source, "Edition"), volume, field(source, "NumberVolumes"))),
|
||||
JournalArticle: () =>
|
||||
primary(primaryAuthors) +
|
||||
formatSecondaryResponsibilities(field(source, "JournalName"), editors) +
|
||||
cityPublisherDate +
|
||||
issueVolume +
|
||||
pagesSection,
|
||||
ArticleInAPeriodical: () =>
|
||||
primary(primaryAuthors) +
|
||||
formatSecondaryResponsibilities(field(source, "PeriodicalTitle"), editors) +
|
||||
cityPublisherDate +
|
||||
editionSection +
|
||||
issueVolume +
|
||||
pagesSection,
|
||||
ConferenceProceedings: () =>
|
||||
primary(primaryAuthors) +
|
||||
formatSecondaryResponsibilities(field(source, "ConferenceName"), editors) +
|
||||
cityPublisherYear +
|
||||
volumeSection +
|
||||
pagesSection,
|
||||
Report: () =>
|
||||
colonHeaded(field(source, "ThesisType")) +
|
||||
primary(primaryAuthors) +
|
||||
formatSecondaryResponsibilities("", separated(SEMICOLON_SEPARATOR, field(source, "Department"), field(source, "Institution"))) +
|
||||
cityPublisherYear +
|
||||
pagesSection,
|
||||
SoundRecording: () =>
|
||||
colonHeaded(field(source, "Medium")) +
|
||||
primary(artists, composers) +
|
||||
formatSecondaryResponsibilities(field(source, "AlbumTitle"), conductors, performers, producers) +
|
||||
formatHyphenSection(formatLocationElement(source, city, productionCompany), field(source, "Year")),
|
||||
Performance: () =>
|
||||
primary(writers, performers, directors) +
|
||||
formatSecondaryResponsibilities("", producers) +
|
||||
formatHyphenSection(
|
||||
formatLocationElement(source, separated(SEMICOLON_SEPARATOR, field(source, "Theater"), city), productionCompany),
|
||||
date,
|
||||
),
|
||||
Art: () => primary(artists) + formatHyphenSection(formatLocationElement(source, city, field(source, "Institution"))),
|
||||
DocumentFromInternetSite: () =>
|
||||
primary(primaryAuthors) +
|
||||
formatSecondaryResponsibilities(field(source, "InternetSiteTitle"), editors, producers) +
|
||||
formatHyphenSection(productionCompany, date) +
|
||||
formatHyphenSection(field(source, "Version")) +
|
||||
accessedSection +
|
||||
formatHyphenSection(field(source, "URL")),
|
||||
InternetSite: () =>
|
||||
primary(primaryAuthors) +
|
||||
formatSecondaryResponsibilities(field(source, "InternetSiteTitle"), editors, producers) +
|
||||
formatHyphenSection(productionCompany, date) +
|
||||
accessedSection +
|
||||
formatHyphenSection(field(source, "URL")),
|
||||
Film: () =>
|
||||
primary(writers, performers, directors) +
|
||||
formatSecondaryResponsibilities("", producers) +
|
||||
formatHyphenSection(
|
||||
formatLocationElement(source, "", productionCompany, { distributor: field(source, "Distributor"), noLocation: true }),
|
||||
field(source, "Year"),
|
||||
),
|
||||
Interview: () =>
|
||||
// GOST - Title Sort's template writes them only when one of the first three isn't empty, so not translators alone
|
||||
(sort === "title" && interviewees + compilers + editors === ""
|
||||
? ""
|
||||
: formatSecondaryResponsibilities("", interviewees, compilers, editors, translators)) +
|
||||
formatHyphenSection(
|
||||
formatLocationElement(
|
||||
source,
|
||||
city,
|
||||
separated(SEMICOLON_SEPARATOR, field(source, "Broadcaster"), field(source, "Station"), publisher),
|
||||
),
|
||||
date,
|
||||
) +
|
||||
pagesSection,
|
||||
Patent: () =>
|
||||
colonHeaded(field(source, "PatentNumber")) +
|
||||
colonHeaded(field(source, "Type")) +
|
||||
primary(inventors) +
|
||||
formatSecondaryResponsibilities("", editors, translators) +
|
||||
formatHyphenSection(field(source, "CountryRegion"), date),
|
||||
ElectronicSource: () =>
|
||||
primary(authors) +
|
||||
formatSecondaryResponsibilities("", editors, producers, translators) +
|
||||
formatHyphenSection(formatLocationElement(source, city, separated(SEMICOLON_SEPARATOR, publisher, productionCompany)), date) +
|
||||
editionSection +
|
||||
volumeSection,
|
||||
Case: () =>
|
||||
colonHeaded(field(source, "CaseNumber")) +
|
||||
colonHeaded(field(source, "AbbreviatedCaseNumber")) +
|
||||
primary(authors) +
|
||||
formatSecondaryResponsibilities("", counsel) +
|
||||
formatHyphenSection(formatLocationElement(source, city, field(source, "Court")), date),
|
||||
Misc: () =>
|
||||
primary(authors) +
|
||||
formatSecondaryResponsibilities(field(source, "PublicationTitle"), compilers, editors, translators) +
|
||||
cityPublisherDate +
|
||||
editionSection +
|
||||
volumeSection +
|
||||
pagesSection,
|
||||
};
|
||||
|
||||
const { type } = source;
|
||||
const typeName =
|
||||
type === "InternetSite" || type === "DocumentFromInternetSite"
|
||||
? SOURCE_TYPE_OPEN + Strings.OnlineCap + SOURCE_TYPE_CLOSE
|
||||
: type === "Misc" || type === "ElectronicSource" || type === "Film"
|
||||
? field(source, "Medium") && SOURCE_TYPE_OPEN + field(source, "Medium") + SOURCE_TYPE_CLOSE
|
||||
: SOURCE_TYPE_OPEN + SourceNames[type] + SOURCE_TYPE_CLOSE;
|
||||
const titles =
|
||||
typeName +
|
||||
(type === "ElectronicSource" && field(source, "PublicationTitle") ? SHORT_TITLE_HEADER + field(source, "PublicationTitle") : "") +
|
||||
(type === "Case" && field(source, "Reporter") ? SHORT_TITLE_HEADER + field(source, "Reporter") : "") +
|
||||
(field(source, "ShortTitle") ? SHORT_TITLE_HEADER + field(source, "ShortTitle") : "");
|
||||
const head =
|
||||
sort === "name"
|
||||
? join(bold(main.corporate ? main.corporate : formatPersons(main.people)), General.Space, field(source, "Title"))
|
||||
: bold(field(source, "Title"));
|
||||
const text = join(
|
||||
head,
|
||||
titles,
|
||||
sectionsOf[type](),
|
||||
formatHyphenSection(field(source, "Comments")),
|
||||
formatHyphenSection(field(source, "StandardNumber")),
|
||||
);
|
||||
// An entry of nothing but spaces, such as a miscellaneous source with no fields, is left empty, with no dot. A
|
||||
// non-breaking space isn't a space to XPath's normalize-space
|
||||
return /^[ \t\r\n]*$/.test(textOf(text)) ? [] : join(text, General.Dot);
|
||||
};
|
||||
|
||||
/**
|
||||
* A source of a citation (the `b:Citation` part of the template that matches `/`), such as "(Baker, 2010 p. 50)": the
|
||||
* last name of the first of the people it's named by, with ", et al." when there are more, its year, and the volume or
|
||||
* pages cited. It is its tag when it has neither people nor a year
|
||||
*/
|
||||
export const formatCitation = ({
|
||||
source,
|
||||
first,
|
||||
last,
|
||||
hideAuthor,
|
||||
hideYear,
|
||||
pages,
|
||||
volume,
|
||||
prefix,
|
||||
suffix,
|
||||
}: CitedSource): FormattedText => {
|
||||
const main = mainOf(source);
|
||||
const author0 = main.corporate
|
||||
? main.corporate
|
||||
: main.people.length === 0
|
||||
? ""
|
||||
: xsl.formatName(main.people[0], Gost.CitationShort) +
|
||||
(main.people.length > 1 ? General.AuthorsSeparator + Strings.AndOthersUnCap : "");
|
||||
const year0 = fieldOf(source, "Year");
|
||||
const author = hideAuthor ? "" : author0;
|
||||
const year = hideYear ? "" : year0;
|
||||
const volumeCited = formatVolume(volume, Strings.VolumeShortUnCap, Strings.VolumesShortUnCap);
|
||||
const pagesCited = formatPages(pages);
|
||||
return join(
|
||||
first ? General.OpenBracket : "",
|
||||
prefix ?? "",
|
||||
author,
|
||||
year ? (author ? General.ListSeparator : "") + year : "",
|
||||
author0 === "" && year0 === "" ? source.tag : "",
|
||||
volume || pages
|
||||
? (author || year ? General.Space : "") + (volume && pages ? volume + General.Enum + pages : volumeCited || pagesCited)
|
||||
: "",
|
||||
suffix ?? "",
|
||||
last ? General.CloseBracket : General.GroupSeparator,
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { describeWordOutput, markupOf } from "tests/bibliography";
|
||||
|
||||
import expected from "./fixtures/gost-name-sort.json";
|
||||
import { gostNameSort } from "./gost-name-sort";
|
||||
import { formatCitation } from "../format";
|
||||
import { wordSourceOf } from "../word-source";
|
||||
|
||||
describe("gostNameSort", () => {
|
||||
describeWordOutput(gostNameSort, expected);
|
||||
|
||||
// Expected values from Word's style, run with libxslt and Word's English wording
|
||||
it("writes the pages or volume cited on their own, with the author and the year left out", () => {
|
||||
const sources = [wordSourceOf({ tag: "Bk", type: "book", authors: [{ lastName: "Lee", firstName: "Ann" }], year: 2001 }, 1)];
|
||||
expect(markupOf(formatCitation(gostNameSort, sources, [{ source: "Bk", hideAuthor: true, hideYear: true, pages: "5" }]))).toBe(
|
||||
"(p. 5)",
|
||||
);
|
||||
expect(markupOf(formatCitation(gostNameSort, sources, [{ source: "Bk", hideAuthor: true, hideYear: true, volume: "2" }]))).toBe(
|
||||
"(vol. 2)",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Word's GOST - Name Sort style (GostName.XSL): citations such as "(Baker, 2010 p. 50)", and a bibliography of entries
|
||||
* such as "**Dickens Charles John** How to Write Bibliographies [Book]. - Chicago : Adventure Works Press, 2006.", each
|
||||
* starting with its authors in bold, sorted by them.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { formatCitation, formatEntry, formatPersons, mainOf } from "./gost-family";
|
||||
import type { StyleDefinition } from "./style";
|
||||
import { sortByKey } from "./xsl";
|
||||
import { type WordSource, fieldOf } from "../word-source";
|
||||
|
||||
/** What the bibliography is sorted by (`b:SortingString`, as `populateMain` writes it): the authors, then the title */
|
||||
const sortingStringOf = (source: WordSource): string => {
|
||||
const main = mainOf(source);
|
||||
const author = main.corporate ? main.corporate : formatPersons(main.people);
|
||||
const title = fieldOf(source, "Title");
|
||||
return (author ? ` ${author}` : "") + (title ? ` ${title}` : "");
|
||||
};
|
||||
|
||||
/**
|
||||
* Word's GOST - Name Sort style.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export const gostNameSort: StyleDefinition = {
|
||||
name: "GOST - Name Sort",
|
||||
file: "GostName.XSL",
|
||||
version: "2003",
|
||||
citation: formatCitation,
|
||||
bibliography: (sources) => ({
|
||||
hangingIndent: false,
|
||||
paragraphs: sortByKey(sources, sortingStringOf).map((source) => formatEntry(source, "name")),
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { describeWordOutput, markupOf } from "tests/bibliography";
|
||||
|
||||
import expected from "./fixtures/gost-title-sort.json";
|
||||
import { gostNameSort } from "./gost-name-sort";
|
||||
import { gostTitleSort } from "./gost-title-sort";
|
||||
import { formatBibliography } from "../format";
|
||||
import type { Source } from "../source";
|
||||
import type { FormattedBibliography } from "./style";
|
||||
import { wordSourceOf } from "../word-source";
|
||||
|
||||
const paragraphsOf = (bibliography: FormattedBibliography): readonly string[] =>
|
||||
"paragraphs" in bibliography ? bibliography.paragraphs.map(markupOf) : [];
|
||||
|
||||
describe("gostTitleSort", () => {
|
||||
describeWordOutput(gostTitleSort, expected);
|
||||
|
||||
// Expected values from Word's styles, run with libxslt and Word's English wording
|
||||
describe("where its template differs from GOST - Name Sort's", () => {
|
||||
const sources: readonly Source[] = [
|
||||
{ tag: "Iv", type: "interview", title: "Talk", translators: [{ lastName: "Ross", firstName: "Bob" }], year: 2001 },
|
||||
{ tag: "Bs", type: "bookSection", corporateAuthor: "Board", title: "Part", bookTitle: "Whole", year: 2002 },
|
||||
];
|
||||
const wordSources = sources.map((source, index) => wordSourceOf(source, index + 1));
|
||||
|
||||
it("leaves out an interview's translators when it has no one else responsible for it", () => {
|
||||
expect(paragraphsOf(formatBibliography(gostTitleSort, wordSources))).toContain("<b>Talk</b> [Interview].\u00a0- 2001.");
|
||||
expect(paragraphsOf(formatBibliography(gostNameSort, wordSources))).toContain(
|
||||
"Talk [Interview]\u00a0/ trans. Ross Bob.\u00a0- 2001.",
|
||||
);
|
||||
});
|
||||
|
||||
it("counts an organization as a book section's author", () => {
|
||||
expect(paragraphsOf(formatBibliography(gostTitleSort, wordSources))).toContain(
|
||||
"<b>Part</b> [Book Section]\u00a0/ auth. Board\u00a0// Whole.\u00a0- 2002.",
|
||||
);
|
||||
expect(paragraphsOf(formatBibliography(gostNameSort, wordSources))).toContain(
|
||||
"<b>Board</b> Part [Book Section]\u00a0// Whole.\u00a0- 2002.",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Word's GOST - Title Sort style (GostTitle.XSL): citations such as "(Baker, 2010 p. 50)", and a bibliography of entries
|
||||
* such as "**How to Write Bibliographies** [Book] / auth. Dickens Charles John. - Chicago : Adventure Works Press,
|
||||
* 2006.", each starting with its title in bold, sorted by it.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { formatCitation, formatEntry, mainOf } from "./gost-family";
|
||||
import type { StyleDefinition } from "./style";
|
||||
import { sortByKey } from "./xsl";
|
||||
import { type WordSource, fieldOf } from "../word-source";
|
||||
|
||||
/**
|
||||
* The sources sorted by title, then by the last, first and middle names of the first of the people they're named by
|
||||
* (`sortedList`). Each sort keeps the order of the one before for sources it doesn't tell apart, so sorting by the last
|
||||
* key first sorts by them all
|
||||
*/
|
||||
const sorted = (sources: readonly WordSource[]): readonly WordSource[] => {
|
||||
const person = (source: WordSource): { readonly last: string; readonly first: string; readonly middle: string } =>
|
||||
mainOf(source).people[0] ?? { last: "", first: "", middle: "" };
|
||||
return [
|
||||
(source: WordSource): string => person(source).middle,
|
||||
(source: WordSource): string => person(source).first,
|
||||
(source: WordSource): string => person(source).last,
|
||||
(source: WordSource): string => fieldOf(source, "Title"),
|
||||
].reduce((list, key) => sortByKey(list, key), sources);
|
||||
};
|
||||
|
||||
/**
|
||||
* Word's GOST - Title Sort style.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export const gostTitleSort: StyleDefinition = {
|
||||
name: "GOST - Title Sort",
|
||||
file: "GostTitle.XSL",
|
||||
version: "2003",
|
||||
citation: formatCitation,
|
||||
bibliography: (sources) => ({
|
||||
hangingIndent: false,
|
||||
paragraphs: sorted(sources).map((source) => formatEntry(source, "title")),
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,254 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type CorpusOutput, describeWordOutput, outputOf } from "tests/bibliography";
|
||||
|
||||
import { harvardAnglia } from "./harvard-anglia";
|
||||
import type { CitedSourceOptions } from "../format";
|
||||
import type { Source } from "../source";
|
||||
import expected from "./fixtures/harvard-anglia.json";
|
||||
|
||||
// Sources none of the corpora have, which take the style down paths it has for them. What Word's style writes for each
|
||||
// is from running Word's own XSL with libxslt and Word's English wording, as corpus s is
|
||||
const CASES: readonly {
|
||||
readonly name: string;
|
||||
readonly sources: readonly Source[];
|
||||
readonly citations: readonly (readonly CitedSourceOptions[])[];
|
||||
readonly expected: Required<CorpusOutput>;
|
||||
}[] = [
|
||||
{
|
||||
name: "authors with middle names, or with only some of their names",
|
||||
sources: [
|
||||
{
|
||||
tag: "B1",
|
||||
type: "book",
|
||||
authors: [
|
||||
{ lastName: "Hall", firstName: "Ann", middleName: "Mary Jean-Paul" },
|
||||
{ lastName: "Fox", firstName: "Bob" },
|
||||
],
|
||||
title: "Bread",
|
||||
year: "2010",
|
||||
},
|
||||
{
|
||||
tag: "B2",
|
||||
type: "book",
|
||||
authors: [
|
||||
{ lastName: "Lee", firstName: "Jean-Paul", middleName: "Ann Marie" },
|
||||
{ lastName: "Ray", firstName: "Cy" },
|
||||
{ lastName: "Moss", firstName: "Dee" },
|
||||
{ lastName: "Kim", firstName: "Eve" },
|
||||
{ lastName: "Ward", firstName: "Max" },
|
||||
],
|
||||
title: "Crust",
|
||||
year: "2011",
|
||||
},
|
||||
{
|
||||
tag: "B3",
|
||||
type: "book",
|
||||
authors: [
|
||||
{ lastName: "", middleName: "Lu" },
|
||||
{ lastName: "Ray", firstName: "Cy" },
|
||||
{ lastName: "Moss", firstName: "Dee" },
|
||||
{ lastName: "Kim", firstName: "Eve" },
|
||||
{ lastName: "Ward", firstName: "Max" },
|
||||
],
|
||||
title: "Dough",
|
||||
year: "2012",
|
||||
},
|
||||
{
|
||||
tag: "B4",
|
||||
type: "book",
|
||||
authors: [{ lastName: "Hall" }, { lastName: "Fox", firstName: "Bob" }],
|
||||
title: "Flour",
|
||||
year: "2013",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "B1" }], [{ source: "B2" }], [{ source: "B3" }], [{ source: "B4" }]],
|
||||
expected: {
|
||||
citations: ["(Hall & Fox, 2010)", "(Lee, et al., 2011)", "(Ray, et al., 2012)", "(Hall & Fox, 2013)"],
|
||||
bibliography: {
|
||||
hangingIndent: false,
|
||||
paragraphs: [
|
||||
"Hall, A. M. J.-P. & Fox, B., 2010. <i>Bread. </i>s.l.:s.n.",
|
||||
"Hall & Fox, B., 2013. <i>Flour. </i>s.l.:s.n.",
|
||||
"Lee, J.-P.A. M. et al., 2011. <i>Crust. </i>s.l.:s.n.",
|
||||
"L. et al., 2012. <i>Dough. </i>s.l.:s.n.",
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "books listed by their editors, with only some of their names",
|
||||
sources: [
|
||||
{ tag: "E1", type: "book", editors: [{ lastName: "Hall" }], title: "Bread", year: "2010" },
|
||||
{ tag: "E2", type: "book", editors: [{ lastName: "Hall", middleName: "Ann" }], title: "Crust", year: "2011" },
|
||||
{ tag: "E3", type: "book", editors: [{ lastName: "", firstName: "Gil", middleName: "Lee" }], title: "Dough", year: "2012" },
|
||||
{
|
||||
tag: "E4",
|
||||
type: "book",
|
||||
editors: [
|
||||
{ lastName: "", middleName: "Lu" },
|
||||
{ lastName: "Ray", firstName: "Cy" },
|
||||
{ lastName: "Moss", firstName: "Dee" },
|
||||
{ lastName: "Kim", firstName: "Eve" },
|
||||
{ lastName: "Ward", firstName: "Max" },
|
||||
],
|
||||
title: "Flour",
|
||||
year: "2013",
|
||||
},
|
||||
{
|
||||
tag: "E5",
|
||||
type: "book",
|
||||
editors: [
|
||||
{ lastName: "", firstName: "Ann", middleName: "Lu" },
|
||||
{ lastName: "", middleName: "Bo" },
|
||||
{ lastName: "Ray", firstName: "Cy", middleName: "Dee" },
|
||||
],
|
||||
title: "Salt",
|
||||
year: "2014",
|
||||
},
|
||||
],
|
||||
citations: [],
|
||||
expected: {
|
||||
citations: [],
|
||||
bibliography: {
|
||||
hangingIndent: false,
|
||||
paragraphs: [
|
||||
"A. L., B. & Ray, C. D. eds., 2014. <i>Salt. </i>s.l.:s.n.",
|
||||
"G. L. ed., 2012. <i>Dough. </i>s.l.:s.n.",
|
||||
"Hall ed., 2010. <i>Bread. </i>s.l.:s.n.",
|
||||
"Hall, A. ed., 2011. <i>Crust. </i>s.l.:s.n.",
|
||||
"L. et al. eds., 2013. <i>Flour. </i>s.l.:s.n.",
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a patent by an organization",
|
||||
sources: [{ tag: "P1", type: "patent", corporateAuthor: "Oven Works", title: "Oven", year: "2015", patentNumber: "123" }],
|
||||
citations: [[{ source: "P1" }]],
|
||||
expected: {
|
||||
citations: ["(Oven Works, 2015)"],
|
||||
bibliography: { hangingIndent: false, paragraphs: ["Oven Works, 2015. <i>Oven. </i>s.l. Patent No. 123."] },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "book sections with editors, with only some of their names",
|
||||
sources: [
|
||||
{
|
||||
tag: "S1",
|
||||
type: "bookSection",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
editors: [{ lastName: "Hall", middleName: "Ann" }],
|
||||
title: "Starters",
|
||||
bookTitle: "Menus",
|
||||
year: "2020",
|
||||
},
|
||||
{
|
||||
tag: "S2",
|
||||
type: "bookSection",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
editors: [{ lastName: "", firstName: "Gil" }],
|
||||
title: "Mains",
|
||||
bookTitle: "Menus",
|
||||
year: "2021",
|
||||
},
|
||||
{
|
||||
tag: "S3",
|
||||
type: "bookSection",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
editors: [
|
||||
{ lastName: "", firstName: "Gil", middleName: "Lee" },
|
||||
{ lastName: "Ray", firstName: "Cy" },
|
||||
{ lastName: "Moss", firstName: "Dee" },
|
||||
{ lastName: "Kim", firstName: "Eve" },
|
||||
{ lastName: "Ward", firstName: "Max" },
|
||||
],
|
||||
title: "Sides",
|
||||
bookTitle: "Menus",
|
||||
year: "2022",
|
||||
},
|
||||
{
|
||||
tag: "S4",
|
||||
type: "bookSection",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
editors: [
|
||||
{ lastName: "Hall" },
|
||||
{ lastName: "Ray", firstName: "Cy" },
|
||||
{ lastName: "Moss", firstName: "Dee" },
|
||||
{ lastName: "Kim", firstName: "Eve" },
|
||||
{ lastName: "Ward", firstName: "Max" },
|
||||
],
|
||||
title: "Sauces",
|
||||
bookTitle: "Menus",
|
||||
year: "2023",
|
||||
},
|
||||
{
|
||||
tag: "S5",
|
||||
type: "bookSection",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
editors: [
|
||||
{ lastName: "", firstName: "Ann" },
|
||||
{ lastName: "Ray", middleName: "Bo" },
|
||||
{ lastName: "", middleName: "Cy" },
|
||||
],
|
||||
title: "Desserts",
|
||||
bookTitle: "Menus",
|
||||
year: "2024",
|
||||
},
|
||||
],
|
||||
citations: [],
|
||||
expected: {
|
||||
citations: [],
|
||||
bibliography: {
|
||||
hangingIndent: false,
|
||||
paragraphs: [
|
||||
"Fox, A., 2020. Starters. In: A. Hall, ed. <i>Menus. </i>s.l.:s.n.",
|
||||
"Fox, A., 2021. Mains. In: G. ed. <i>Menus. </i>s.l.:s.n.",
|
||||
"Fox, A., 2022. Sides. In: G. L. et al. eds. <i>Menus. </i>s.l.:s.n.",
|
||||
"Fox, A., 2023. Sauces. In: Hall, et al. eds. <i>Menus. </i>s.l.:s.n.",
|
||||
"Fox, A., 2024. Desserts. In: A., B. Ray & C., eds. <i>Menus. </i>s.l.:s.n.",
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a film with several directors, with only some of their names",
|
||||
sources: [
|
||||
{
|
||||
tag: "F1",
|
||||
type: "film",
|
||||
directors: [
|
||||
{ lastName: "", firstName: "Pedro" },
|
||||
{ lastName: "Fox", middleName: "Lu" },
|
||||
{ lastName: "", firstName: "Ann", middleName: "Bo" },
|
||||
],
|
||||
title: "Deep Dish",
|
||||
year: "2011",
|
||||
countryOrRegion: "Italy",
|
||||
productionCompany: "Pan",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "F1" }]],
|
||||
expected: {
|
||||
citations: ["(Deep Dish, 2011)"],
|
||||
bibliography: {
|
||||
hangingIndent: false,
|
||||
paragraphs: ["<i>Deep Dish. </i>2011. [Film] Directed by Pedro, Lu Fox, Ann Bo.Italy: Pan."],
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
describe("harvard-anglia", () => {
|
||||
describeWordOutput(harvardAnglia, expected);
|
||||
|
||||
for (const { name, sources, citations, expected: output } of CASES) {
|
||||
it(`writes ${name} as Word does`, () => {
|
||||
expect(outputOf(harvardAnglia, { sources, citations })).toEqual(output);
|
||||
});
|
||||
}
|
||||
|
||||
it("names Word's style", () => {
|
||||
expect(harvardAnglia).toMatchObject({ name: "Harvard - Anglia", file: "HarvardAnglia2008OfficeOnline.xsl", version: "2008" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,719 @@
|
||||
/**
|
||||
* Harvard - Anglia: Word's `HarvardAnglia2008OfficeOnline.xsl`, written in TypeScript.
|
||||
*
|
||||
* Citations name each source's authors and year, such as "(Baker, 2010)". The bibliography lists the sources by author,
|
||||
* each with its year after the authors, such as "Baker, A., 2010. The Art of Pizza. London: Baker Books.".
|
||||
*
|
||||
* Each function follows the XSL template or variable named in its description, including where that doesn't do what it
|
||||
* looks like it should, so the citations and bibliography are the ones Word writes.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
// The names of the XSL's templates and parameters
|
||||
// cspell:words Hypen templ Unavailale
|
||||
import { type FormattedText, LINE_BREAK, italic, join, textOf, underline } from "./formatted-text";
|
||||
import { LOCALS } from "./locals";
|
||||
import type { CitedSource, StyleDefinition } from "./style";
|
||||
import { sortByKey, translate, xslTemplates } from "./xsl";
|
||||
import {
|
||||
type Role,
|
||||
type WordNames,
|
||||
type WordPerson,
|
||||
type WordSource,
|
||||
type WordSourceType,
|
||||
fieldOf,
|
||||
organizationOf,
|
||||
peopleOf,
|
||||
} from "../word-source";
|
||||
|
||||
const general = LOCALS.General;
|
||||
const strings = LOCALS.Strings;
|
||||
const xsl = xslTemplates(general);
|
||||
// The wording the style reads from APA's: the "&" before the last person, and the square brackets
|
||||
const apaWording = LOCALS.APA;
|
||||
|
||||
/** "&" with a space each side, between the last two people (`templ_prop_BeforeLastAuthor`) */
|
||||
const AND = general.Space + apaWording.BeforeLastAuthor + general.Space;
|
||||
|
||||
/** What the bibliography names a source by when it has nobody to name it by, which the style writes as it is */
|
||||
const ANONYMOUS = "Anon., ";
|
||||
|
||||
/** The roles a source is named by, in the order the style looks for them (`MainContributors`, `MainImportantContributors`) */
|
||||
const MAIN_CONTRIBUTORS: Readonly<Record<WordSourceType, readonly Role[]>> = {
|
||||
Book: ["Author", "Editor"],
|
||||
BookSection: ["Author", "Editor"],
|
||||
ConferenceProceedings: ["Author", "Editor"],
|
||||
Misc: ["Author", "Editor"],
|
||||
JournalArticle: ["Author", "Editor"],
|
||||
ArticleInAPeriodical: ["Author", "Editor"],
|
||||
InternetSite: ["Author"],
|
||||
ElectronicSource: ["Author"],
|
||||
Report: ["Author"],
|
||||
DocumentFromInternetSite: ["Author"],
|
||||
SoundRecording: ["Composer", "Conductor", "Performer"],
|
||||
Performance: ["Writer"],
|
||||
Art: ["Artist"],
|
||||
Interview: ["Interviewee"],
|
||||
Patent: ["Inventor"],
|
||||
Case: [],
|
||||
Film: [],
|
||||
};
|
||||
|
||||
/** The text of the people with a role, or of the organization, as `string-length(b:Author/b:Role)` reads it */
|
||||
const namesText = (names: WordNames | undefined): string =>
|
||||
!names ? "" : "corporate" in names ? names.corporate : names.people.map(({ last, first, middle }) => last + first + middle).join("");
|
||||
|
||||
/** The first of the roles the source is named by that has anybody's name in it */
|
||||
const mainContributorsOf = (source: WordSource): Role | undefined =>
|
||||
MAIN_CONTRIBUTORS[source.type].find((role) => namesText(source.names[role]) !== "");
|
||||
|
||||
/** The text with each part replaced, left to right (`FindReplaceString`) */
|
||||
const findReplaceString = (originalString: string, stringToBeReplaced: string, stringReplacement: string): string =>
|
||||
originalString.split(stringToBeReplaced).join(stringReplacement);
|
||||
|
||||
/** The text without the spaces, tabs and line breaks at its end (`right-trim`) */
|
||||
const rightTrim = (s: string): string => s.replace(/[ \t\r\n]+$/, "");
|
||||
|
||||
/** The text without the spaces at its start (`left-trim`) */
|
||||
const leftTrim = (s: string): string => s.replace(/^ +/, "");
|
||||
|
||||
/** The initials of a name, each with a dot, such as "M. A." of "Mary Ann" (`splitAuthorSpace`) */
|
||||
const splitAuthorSpace = (first: string): string => {
|
||||
const space = first.indexOf(" ");
|
||||
return space < 0
|
||||
? first.slice(0, 1) + general.Dot
|
||||
: first.slice(0, space).slice(0, 1) + general.Dot + general.Space + splitAuthorSpace(leftTrim(first.slice(space + 1)));
|
||||
};
|
||||
|
||||
/** The initials of a name with hyphens, such as "J.-P." of "Jean-Paul" (`HandleHypenInAuthor`) */
|
||||
const handleHypenInAuthor = (authour: string, retVal = ""): string => {
|
||||
const dash = general.FromToDash;
|
||||
const initial = !authour.startsWith(dash) && retVal === "" ? authour.slice(0, 1) + general.Dot : "";
|
||||
const index = authour.indexOf(dash);
|
||||
if (index < 0) {
|
||||
return initial + retVal;
|
||||
}
|
||||
const after = authour.slice(index + dash.length);
|
||||
return initial + handleHypenInAuthor(after, retVal + dash + after.slice(0, 1) + general.Dot);
|
||||
};
|
||||
|
||||
/** The initials of each word of a name with hyphens, such as "M. J.-P." of "Mary Jean-Paul" (`HandleSPaceHypenInAuthor`) */
|
||||
const handleSpaceHypenInAuthor = (author: string): string => {
|
||||
const space = author.indexOf(" ");
|
||||
return space < 0
|
||||
? handleHypenInAuthor(author)
|
||||
: handleHypenInAuthor(author.slice(0, space)) + general.Space + handleSpaceHypenInAuthor(leftTrim(author.slice(space + 1)));
|
||||
};
|
||||
|
||||
/** The initials of a first or middle name, with or without hyphens (`xsl:when test="contains(b:First,$prop_APA_FromToDash)"`) */
|
||||
const initialsOf = (name: string): string =>
|
||||
name.includes(general.FromToDash) ? handleSpaceHypenInAuthor(rightTrim(name)) : splitAuthorSpace(rightTrim(name));
|
||||
|
||||
/**
|
||||
* People, last name first, such as "Smith, J. & Jones, M. A., ", or the first of five or more and "et al., " (the
|
||||
* people of `BibDisplayAuthor`, which `BibDisplayArtist`, `BibDisplayAuthorSoundRec` and the others write the same way)
|
||||
*/
|
||||
const bibDisplayPeople = (people: readonly WordPerson[]): string => {
|
||||
if (people.length >= 5) {
|
||||
const [{ last, first, middle }] = people;
|
||||
return (
|
||||
(last ? last + general.ListSeparator : "") +
|
||||
// A first name with a hyphen has no space after it, so what follows it runs on, as in "Lee, J.-P.et al., "
|
||||
(first ? initialsOf(first) + (first.includes(general.FromToDash) ? "" : general.Space) : "") +
|
||||
(middle ? initialsOf(middle) + general.Space : "") +
|
||||
strings.AndOthersUnCap +
|
||||
general.ListSeparator
|
||||
);
|
||||
}
|
||||
return people
|
||||
.map(({ last, first, middle }, index) => {
|
||||
const beforeLast = index === people.length - 2;
|
||||
return (
|
||||
(last ? last + (!first && !middle && beforeLast ? AND : general.ListSeparator) : "") +
|
||||
(first ? initialsOf(first) + (middle ? general.Space : beforeLast ? AND : general.ListSeparator) : "") +
|
||||
(middle ? initialsOf(middle) + (beforeLast ? AND : general.ListSeparator) : "")
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
};
|
||||
|
||||
/**
|
||||
* The editors, last name first, such as "Hall, G., ed." or "Garcia, L. & Nguyen, B. eds.", which a source with no
|
||||
* authors is listed by (`BibDisplayEditorNL`)
|
||||
*/
|
||||
const bibDisplayEditorNL = (editors: readonly WordPerson[]): string => {
|
||||
const [{ last, first, middle }] = editors;
|
||||
if (editors.length === 1) {
|
||||
return (
|
||||
(last ? last + (first || middle ? general.ListSeparator : general.Space) : "") +
|
||||
(first ? initialsOf(first) + (middle ? general.Space : general.ListSeparator) : "") +
|
||||
(middle ? initialsOf(middle) + general.Space : "") +
|
||||
strings.EditorShortUnCap
|
||||
);
|
||||
}
|
||||
if (editors.length >= 5) {
|
||||
return (
|
||||
(last ? last + general.ListSeparator : "") +
|
||||
(first ? initialsOf(first) + general.Space : "") +
|
||||
(middle ? initialsOf(middle) + general.Space : "") +
|
||||
strings.AndOthersUnCap +
|
||||
general.Space +
|
||||
strings.UnCapEditorsShort
|
||||
);
|
||||
}
|
||||
return (
|
||||
editors
|
||||
.map((editor, index) => {
|
||||
const beforeLast = index === editors.length - 2;
|
||||
const after = index === editors.length - 1 ? general.Space : general.ListSeparator;
|
||||
// Its "&" after a last name is only for an editor with no last name, so it never writes one
|
||||
return (
|
||||
(editor.last ? editor.last + general.ListSeparator : "") +
|
||||
(editor.first ? initialsOf(editor.first) + (editor.middle ? general.Space : beforeLast ? AND : after) : "") +
|
||||
(editor.middle ? initialsOf(editor.middle) + (beforeLast ? AND : after) : "")
|
||||
);
|
||||
})
|
||||
.join("") + strings.UnCapEditorsShort
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* The authors, or else the organization that is the author, or else when it is asked for the editors, or "Anon., "
|
||||
* (`BibDisplayAuthor`, and its `DisplayEditorIfAuthorUnavailale`)
|
||||
*/
|
||||
const bibDisplayAuthor = (source: WordSource, displayEditorIfAuthorUnavailable = false): string => {
|
||||
const authors = peopleOf(source, "Author");
|
||||
const corporate = organizationOf(source, "Author");
|
||||
const editors = peopleOf(source, "Editor");
|
||||
if (authors.length) {
|
||||
return bibDisplayPeople(authors);
|
||||
}
|
||||
if (corporate) {
|
||||
return corporate + general.ListSeparator;
|
||||
}
|
||||
return editors.length && displayEditorIfAuthorUnavailable ? bibDisplayEditorNL(editors) + general.ListSeparator : ANONYMOUS;
|
||||
};
|
||||
|
||||
/**
|
||||
* The people with a role, or "Anon., " (`BibDisplayArtist`, and `BibDisplayAuthorPerformance` and
|
||||
* `BibDisplayAuthorInterview` with the writers and interviewees)
|
||||
*/
|
||||
const bibDisplayArtist = (people: readonly WordPerson[]): string => (people.length ? bibDisplayPeople(people) : ANONYMOUS);
|
||||
|
||||
/** The inventors, or else the organization that is the author, or "Anon., " (`BibDisplayAuthorPatent`) */
|
||||
const bibDisplayAuthorPatent = (source: WordSource): string => {
|
||||
const inventors = peopleOf(source, "Inventor");
|
||||
const corporate = organizationOf(source, "Author");
|
||||
return inventors.length ? bibDisplayPeople(inventors) : corporate ? corporate + general.ListSeparator : ANONYMOUS;
|
||||
};
|
||||
|
||||
/** The composers, or else the conductors or the performers, or the organization that performs, or "Anon., " (`BibDisplayAuthorSoundRec`) */
|
||||
const bibDisplayAuthorSoundRec = (source: WordSource): string => {
|
||||
const people = [peopleOf(source, "Composer"), peopleOf(source, "Conductor"), peopleOf(source, "Performer")].find((list) => list.length);
|
||||
const corporate = organizationOf(source, "Performer");
|
||||
return people ? bibDisplayPeople(people) : corporate ? corporate + general.ListSeparator : ANONYMOUS;
|
||||
};
|
||||
|
||||
/**
|
||||
* The editors of the book a section is in, first name first, such as "G. Hall, ed. ", when the section has authors
|
||||
* (`BibDisplayEditor`)
|
||||
*/
|
||||
const bibDisplayEditor = (source: WordSource): string => {
|
||||
const editors = peopleOf(source, "Editor");
|
||||
if (!peopleOf(source, "Author").length && !organizationOf(source, "Author")) {
|
||||
return "";
|
||||
}
|
||||
const [{ last, first, middle }] = editors;
|
||||
if (editors.length === 1) {
|
||||
return (
|
||||
(first ? splitAuthorSpace(rightTrim(first)) + general.Space : "") +
|
||||
(middle ? splitAuthorSpace(rightTrim(middle)) + general.Space : "") +
|
||||
(last ? last + general.ListSeparator : "") +
|
||||
strings.EditorShortUnCap +
|
||||
general.Space
|
||||
);
|
||||
}
|
||||
if (editors.length >= 5) {
|
||||
return (
|
||||
(first ? splitAuthorSpace(rightTrim(first)) + general.Space : "") +
|
||||
(middle ? splitAuthorSpace(rightTrim(middle)) + general.Space : "") +
|
||||
(last ? last + general.ListSeparator : "") +
|
||||
strings.AndOthersUnCap +
|
||||
general.Space +
|
||||
strings.UnCapEditorsShort +
|
||||
general.Space
|
||||
);
|
||||
}
|
||||
return (
|
||||
editors
|
||||
.map((editor, index) => {
|
||||
const beforeLast = index === editors.length - 2;
|
||||
const end = beforeLast ? AND : general.ListSeparator;
|
||||
return (
|
||||
(editor.first
|
||||
? splitAuthorSpace(rightTrim(editor.first)) + (!editor.middle && !editor.last ? end : general.Space)
|
||||
: "") +
|
||||
(editor.middle ? splitAuthorSpace(rightTrim(editor.middle)) + (!editor.last ? end : general.Space) : "") +
|
||||
(editor.last ? editor.last + end : "")
|
||||
);
|
||||
})
|
||||
.join("") +
|
||||
strings.UnCapEditorsShort +
|
||||
general.Space
|
||||
);
|
||||
};
|
||||
|
||||
/** "Directed by John Smith. ", or by several directors, when the film has any (`BibDisplayDirector`) */
|
||||
const bibDisplayDirector = (source: WordSource): string => {
|
||||
const directors = peopleOf(source, "Director");
|
||||
const directorName = directors
|
||||
.map(({ last, first, middle }, index) => {
|
||||
const isLast = index === directors.length - 1;
|
||||
// A first or middle name that ends the last of several directors has a dot and no space, as in "Ann Bo.Italy"
|
||||
const end = !isLast ? general.ListSeparator : directors.length === 1 ? general.Dot + general.Space : general.Dot;
|
||||
return (
|
||||
(first ? first + (last || middle ? general.Space : end) : "") +
|
||||
(middle ? middle + (last ? general.Space : end) : "") +
|
||||
(last ? last + (isLast ? general.Dot + general.Space : general.ListSeparator) : "")
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
return directorName ? findReplaceString(strings.DirectedByCap, "%1", directorName) : "";
|
||||
};
|
||||
|
||||
/** The year and a dot, or "n.d.", and a space (`BibDisplayYear`) */
|
||||
const bibDisplayYear = (source: WordSource): string =>
|
||||
(fieldOf(source, "Year") ? fieldOf(source, "Year") + general.Dot : strings.NoDateShortUnCap) + general.Space;
|
||||
|
||||
/** A case's year in brackets, or "(n.d.)", with a dot when it has no reporter, and a space (`BibDisplayYearCase`) */
|
||||
const bibDisplayYearCase = (source: WordSource): string =>
|
||||
general.OpenBracket +
|
||||
(fieldOf(source, "Year") || strings.NoDateShortUnCap) +
|
||||
general.CloseBracket +
|
||||
(fieldOf(source, "Reporter") ? "" : general.Dot) +
|
||||
general.Space;
|
||||
|
||||
/** An interview's date, such as "(3 May 2010).", or its year, or "n.d." (`BibDisplayDayMonthYear`) */
|
||||
const bibDisplayDayMonthYear = (source: WordSource): string => {
|
||||
const day = fieldOf(source, "Day");
|
||||
const month = fieldOf(source, "Month");
|
||||
const year = fieldOf(source, "Year");
|
||||
if (!year) {
|
||||
return strings.NoDateShortUnCap;
|
||||
}
|
||||
return month
|
||||
? general.OpenBracket + (day ? day + general.Space : "") + month + general.Space + year + general.CloseBracket + general.Dot
|
||||
: year + general.Dot;
|
||||
};
|
||||
|
||||
/** The title, a dot and a space (`BibDisplayTitle`) */
|
||||
const bibDisplayTitle = (source: WordSource): string =>
|
||||
fieldOf(source, "Title") ? rightTrim(fieldOf(source, "Title")) + general.Dot + general.Space : "";
|
||||
|
||||
/** The title and a space (`BibDisplayTitleInt`, and `BibDisplayTitleCase`, which is the same) */
|
||||
const bibDisplayTitleInt = (source: WordSource): string => (fieldOf(source, "Title") ? fieldOf(source, "Title") + general.Space : "");
|
||||
|
||||
/** The title, a comma and a space (`BibDisplayTitleES`) */
|
||||
const bibDisplayTitleES = (source: WordSource): string =>
|
||||
fieldOf(source, "Title") ? fieldOf(source, "Title") + general.ListSeparator + general.Space : "";
|
||||
|
||||
/** A section's title and a dot, and a space when it has authors (`BibDisplayTitleBC`) */
|
||||
const bibDisplayTitleBC = (source: WordSource): string =>
|
||||
fieldOf(source, "Title") ? fieldOf(source, "Title") + general.Dot + (peopleOf(source, "Author").length ? general.Space : "") : "";
|
||||
|
||||
/** The title of the book a section is in, a dot and a space (`BibDisplayBookTitle`) */
|
||||
const bibDisplayBookTitle = (source: WordSource): string =>
|
||||
fieldOf(source, "BookTitle") ? fieldOf(source, "BookTitle") + general.Dot + general.Space : "";
|
||||
|
||||
/** The journal's name, and a comma when more follows or else a dot (`BibDisplayJournalName`) */
|
||||
const bibDisplayJournalName = (source: WordSource): string => {
|
||||
const more = ["Month", "Pages", "Volume", "Issue"] as const;
|
||||
return fieldOf(source, "JournalName")
|
||||
? fieldOf(source, "JournalName") +
|
||||
(more.some((field) => fieldOf(source, field)) ? general.ListSeparator + general.Space : general.Dot)
|
||||
: "";
|
||||
};
|
||||
|
||||
/** The volume and issue, such as "7(2)", "Volume 7" or "Issue 2", and a comma before pages or else a dot */
|
||||
const volumeAndIssueOf = (source: WordSource): string => {
|
||||
const volume = fieldOf(source, "Volume");
|
||||
const issue = fieldOf(source, "Issue");
|
||||
const end = fieldOf(source, "Pages") ? general.ListSeparator : general.Dot;
|
||||
if (volume) {
|
||||
return (
|
||||
(issue ? volume + general.OpenBracket + issue + general.CloseBracket : findReplaceString(strings.VolumeCap, "%1", volume)) + end
|
||||
);
|
||||
}
|
||||
// "Issue" is the style's own
|
||||
return issue ? `Issue${general.Space}${issue}${end}` : "";
|
||||
};
|
||||
|
||||
/** A journal article's date, then its volume and issue (`BibDisplayVolumeIssueJA`) */
|
||||
const bibDisplayVolumeIssueJA = (source: WordSource): string => {
|
||||
const day = fieldOf(source, "Day");
|
||||
const month = fieldOf(source, "Month");
|
||||
const date = month
|
||||
? (day ? day + general.Space + month : month) +
|
||||
((fieldOf(source, "Volume") || fieldOf(source, "Issue")) && fieldOf(source, "Pages") ? general.ListSeparator : general.Dot)
|
||||
: "";
|
||||
return date + volumeAndIssueOf(source);
|
||||
};
|
||||
|
||||
/** A periodical's title in italics, its date, then its volume and issue (`BibDisplayVolumeIssue`) */
|
||||
const bibDisplayVolumeIssue = (source: WordSource): FormattedText => {
|
||||
const periodicalTitle = fieldOf(source, "PeriodicalTitle");
|
||||
const day = fieldOf(source, "Day");
|
||||
const month = fieldOf(source, "Month");
|
||||
const afterTitle = ["Month", "Volume", "Issue", "Pages"] as const;
|
||||
const afterMonth = ["Volume", "Issue", "Pages"] as const;
|
||||
const end = (fields: readonly ("Month" | "Volume" | "Issue" | "Pages")[]): string =>
|
||||
(fields.some((field) => fieldOf(source, field)) ? general.ListSeparator : general.Dot) + general.Space;
|
||||
return join(
|
||||
periodicalTitle ? join(italic(periodicalTitle), end(afterTitle)) : "",
|
||||
month ? (day ? day + general.Space : "") + month + end(afterMonth) : "",
|
||||
volumeAndIssueOf(source),
|
||||
);
|
||||
};
|
||||
|
||||
/** The city, with its state or province in brackets, or "s.l.", and a colon (`BibDisplayCity`) */
|
||||
const bibDisplayCity = (source: WordSource): string => {
|
||||
const city = fieldOf(source, "City");
|
||||
const state = fieldOf(source, "StateProvince");
|
||||
const place = city && state ? city + general.OpenBracket + state + general.CloseBracket : city || state || strings.SineLocoShort;
|
||||
// With no place, the colon has no space after it
|
||||
return place + (city || state ? general.EnumSeparator : general.Enum);
|
||||
};
|
||||
|
||||
/** The city, or "s.l.", and ": " (`BibDisplayCityReport`) */
|
||||
const bibDisplayCityReport = (source: WordSource): string => (fieldOf(source, "City") || strings.SineLocoShort) + general.EnumSeparator;
|
||||
|
||||
/** The city, or "s.l.", and a comma (`BibDisplayConfCityConfProc`) */
|
||||
const bibDisplayConfCityConfProc = (source: WordSource): string =>
|
||||
fieldOf(source, "City")
|
||||
? fieldOf(source, "City") + general.ListSeparator + general.Space
|
||||
: strings.SineLocoShort + general.ListSeparator;
|
||||
|
||||
/** The publisher and a dot, or "s.n." (`BibDisplayPublisher`) */
|
||||
const bibDisplayPublisher = (source: WordSource): string =>
|
||||
fieldOf(source, "Publisher") ? fieldOf(source, "Publisher") + general.Dot : strings.SineNomineShort;
|
||||
|
||||
/**
|
||||
* The publisher, or "s.n.", and a comma before pages, or else a dot after a publisher (`BibDisplayConfPublisher`, and
|
||||
* `BibDisplayPublisherBC`, which is the same)
|
||||
*/
|
||||
const bibDisplayConfPublisher = (source: WordSource): string => {
|
||||
const pages = fieldOf(source, "Pages");
|
||||
return fieldOf(source, "Publisher")
|
||||
? fieldOf(source, "Publisher") + (pages ? general.ListSeparator + general.Space : general.Dot)
|
||||
: strings.SineNomineShort + (pages ? general.ListSeparator + general.Space : "");
|
||||
};
|
||||
|
||||
/** Pages, such as "p. 5" or "pp. 5-9", which the style writes in English whatever the language (`DisplayPageOrPages`) */
|
||||
const displayPageOrPages = (pages: string): string => (pages.includes("-") || pages.includes(",") ? "pp. " : "p. ") + pages;
|
||||
|
||||
/** The pages and a dot (`BibDisplayPages`) */
|
||||
const bibDisplayPages = (source: WordSource): string =>
|
||||
fieldOf(source, "Pages") ? displayPageOrPages(fieldOf(source, "Pages")) + general.Dot : "";
|
||||
|
||||
/** The edition and "ed. ", which is the style's word for an editor (`BibDisplayEdition`) */
|
||||
const bibDisplayEdition = (source: WordSource): string =>
|
||||
fieldOf(source, "Edition") ? fieldOf(source, "Edition") + general.Space + strings.EditorShortUnCap + general.Space : "";
|
||||
|
||||
/** "[Online]", and a space before where it is or a dot (`BibDisplayStrOnline`) */
|
||||
const bibDisplayStrOnline = (source: WordSource): string =>
|
||||
apaWording.SecondaryOpen +
|
||||
strings.OnlineCap +
|
||||
apaWording.SecondaryClose +
|
||||
(fieldOf(source, "URL") || fieldOf(source, "YearAccessed") ? general.Space : general.Dot);
|
||||
|
||||
/** "Available at: " and the address, underlined, on a line of its own (`BibDisplayURL`) */
|
||||
const bibDisplayURL = (source: WordSource): FormattedText =>
|
||||
// "Available at:" is the style's own
|
||||
fieldOf(source, "URL") ? join(LINE_BREAK, "Available at:", general.Space, underline(fieldOf(source, "URL"))) : [];
|
||||
|
||||
/** "[Accessed 20 April 2023].", on a line of its own (`BibDisplayAccessedDates`) */
|
||||
const bibDisplayAccessedDates = (source: WordSource): FormattedText => {
|
||||
const year = fieldOf(source, "YearAccessed");
|
||||
const month = fieldOf(source, "MonthAccessed");
|
||||
const day = fieldOf(source, "DayAccessed");
|
||||
if (!year) {
|
||||
return [];
|
||||
}
|
||||
const date = month ? (day ? day + general.Space : "") + month + general.Space + year : year;
|
||||
return join(
|
||||
LINE_BREAK,
|
||||
general.Space +
|
||||
apaWording.SecondaryOpen +
|
||||
findReplaceString(strings.AccessedCap, " %1", general.Space) +
|
||||
date +
|
||||
apaWording.SecondaryClose +
|
||||
general.Dot,
|
||||
);
|
||||
};
|
||||
|
||||
/** The country or region, and a comma before the patent's number or else a dot, or "s.l. " (`BibDisplayCountryRegionPatent`) */
|
||||
const bibDisplayCountryRegionPatent = (source: WordSource): string =>
|
||||
fieldOf(source, "CountryRegion")
|
||||
? fieldOf(source, "CountryRegion") + (fieldOf(source, "PatentNumber") ? general.ListSeparator : general.Dot)
|
||||
: strings.SineLocoShort + general.Space;
|
||||
|
||||
/** "Patent No. 123." (`BibDisplayPatentNumber`) */
|
||||
const bibDisplayPatentNumber = (source: WordSource): string =>
|
||||
fieldOf(source, "PatentNumber")
|
||||
? findReplaceString(strings.PatentNumberShortCap, "%1", fieldOf(source, "PatentNumber")) + general.Dot
|
||||
: "";
|
||||
|
||||
/** The country or region, or "s.l.", and ": " (`BibDisplayCountryRegion`) */
|
||||
const bibDisplayCountryRegion = (source: WordSource): string =>
|
||||
(fieldOf(source, "CountryRegion") || strings.SineLocoShort) + general.EnumSeparator;
|
||||
|
||||
/** The production company and a dot, or "s.n." (`BibDisplayProductionCompany`) */
|
||||
const bibDisplayProductionCompany = (source: WordSource): string =>
|
||||
fieldOf(source, "ProductionCompany") ? fieldOf(source, "ProductionCompany") + general.Dot : strings.SineNomineShort;
|
||||
|
||||
/** The text of a source's entry in the bibliography, by its type (`ProceedBibliography`) */
|
||||
const proceedBibliography = (source: WordSource): FormattedText => {
|
||||
const field = (name: "Institution" | "ProductionCompany" | "Reporter"): string => fieldOf(source, name);
|
||||
switch (source.type) {
|
||||
case "BookSection":
|
||||
return join(
|
||||
bibDisplayAuthor(source, true),
|
||||
bibDisplayYear(source),
|
||||
bibDisplayTitleBC(source),
|
||||
general.Space,
|
||||
findReplaceString(strings.InNameCap, " %1", general.EnumSeparator),
|
||||
peopleOf(source, "Editor").length
|
||||
? bibDisplayEditor(source) + (peopleOf(source, "Author").length ? general.Space : "")
|
||||
: "",
|
||||
italic(bibDisplayBookTitle(source)),
|
||||
bibDisplayEdition(source),
|
||||
bibDisplayCity(source),
|
||||
bibDisplayConfPublisher(source),
|
||||
bibDisplayPages(source),
|
||||
);
|
||||
case "InternetSite":
|
||||
case "DocumentFromInternetSite":
|
||||
return join(
|
||||
bibDisplayAuthor(source),
|
||||
bibDisplayYear(source),
|
||||
italic(bibDisplayTitle(source)),
|
||||
bibDisplayStrOnline(source),
|
||||
bibDisplayURL(source),
|
||||
bibDisplayAccessedDates(source),
|
||||
);
|
||||
case "JournalArticle":
|
||||
return join(
|
||||
bibDisplayAuthor(source, true),
|
||||
bibDisplayYear(source),
|
||||
bibDisplayTitle(source),
|
||||
italic(bibDisplayJournalName(source)),
|
||||
bibDisplayVolumeIssueJA(source),
|
||||
bibDisplayPages(source),
|
||||
);
|
||||
case "ArticleInAPeriodical":
|
||||
return join(
|
||||
bibDisplayAuthor(source, true),
|
||||
bibDisplayYear(source),
|
||||
bibDisplayTitle(source),
|
||||
bibDisplayVolumeIssue(source),
|
||||
bibDisplayPages(source),
|
||||
);
|
||||
case "ConferenceProceedings":
|
||||
return join(
|
||||
bibDisplayAuthor(source, true),
|
||||
bibDisplayYear(source),
|
||||
italic(bibDisplayTitle(source)),
|
||||
bibDisplayConfCityConfProc(source),
|
||||
bibDisplayConfPublisher(source),
|
||||
bibDisplayPages(source),
|
||||
);
|
||||
case "Report":
|
||||
return join(
|
||||
bibDisplayAuthor(source),
|
||||
bibDisplayYear(source),
|
||||
italic(bibDisplayTitleES(source)),
|
||||
bibDisplayCityReport(source),
|
||||
bibDisplayPublisher(source),
|
||||
);
|
||||
case "ElectronicSource":
|
||||
return join(
|
||||
bibDisplayAuthor(source),
|
||||
bibDisplayYear(source),
|
||||
italic(bibDisplayTitleES(source)),
|
||||
bibDisplayCityReport(source),
|
||||
bibDisplayConfPublisher(source),
|
||||
);
|
||||
case "Art":
|
||||
// BibDisplayStrArt, and BibDisplayInstitutionArt
|
||||
return join(
|
||||
bibDisplayArtist(peopleOf(source, "Artist")),
|
||||
bibDisplayYear(source),
|
||||
italic(bibDisplayTitle(source)),
|
||||
apaWording.SecondaryOpen + LOCALS.SourceNames.Art + apaWording.SecondaryClose,
|
||||
field("Institution") ? general.Space + general.OpenBracket + field("Institution") + general.CloseBracket : "",
|
||||
general.Dot,
|
||||
);
|
||||
case "SoundRecording":
|
||||
// BibDisplayStrSoundRecording, and BibDisplayProductionCompanySRec
|
||||
return join(
|
||||
bibDisplayAuthorSoundRec(source),
|
||||
bibDisplayYear(source),
|
||||
italic(bibDisplayTitle(source)),
|
||||
apaWording.SecondaryOpen + LOCALS.SourceNames.SoundRecording + apaWording.SecondaryClose,
|
||||
field("ProductionCompany")
|
||||
? general.Space + general.OpenBracket + field("ProductionCompany") + general.CloseBracket + general.Dot
|
||||
: general.Dot,
|
||||
);
|
||||
case "Performance":
|
||||
// BibDisplayProductionCompanyPerformance: the city as BibDisplayCityReport writes it, and the company
|
||||
return join(
|
||||
bibDisplayArtist(peopleOf(source, "Writer")),
|
||||
bibDisplayYear(source),
|
||||
italic(bibDisplayTitle(source)),
|
||||
bibDisplayCityReport(source),
|
||||
bibDisplayProductionCompany(source),
|
||||
);
|
||||
case "Interview":
|
||||
// BibDisplayStrInterview
|
||||
return join(
|
||||
bibDisplayArtist(peopleOf(source, "Interviewee")),
|
||||
bibDisplayYear(source),
|
||||
italic(bibDisplayTitleInt(source)),
|
||||
apaWording.SecondaryOpen + strings.InterviewCap + apaWording.SecondaryClose + general.Space,
|
||||
bibDisplayDayMonthYear(source),
|
||||
);
|
||||
case "Patent":
|
||||
return join(
|
||||
bibDisplayAuthorPatent(source),
|
||||
bibDisplayYear(source),
|
||||
italic(bibDisplayTitle(source)),
|
||||
bibDisplayCountryRegionPatent(source),
|
||||
bibDisplayPatentNumber(source),
|
||||
);
|
||||
case "Film":
|
||||
// BibDisplayStrFilm
|
||||
return join(
|
||||
italic(bibDisplayTitle(source)),
|
||||
bibDisplayYear(source),
|
||||
apaWording.SecondaryOpen + LOCALS.SourceNames.Film + apaWording.SecondaryClose + general.Space,
|
||||
bibDisplayDirector(source),
|
||||
bibDisplayCountryRegion(source),
|
||||
bibDisplayProductionCompany(source),
|
||||
);
|
||||
case "Case":
|
||||
// BibDisplayReporter
|
||||
return join(
|
||||
italic(bibDisplayTitleInt(source)),
|
||||
bibDisplayYearCase(source),
|
||||
field("Reporter") ? field("Reporter") + general.Dot + general.Space : "",
|
||||
);
|
||||
default:
|
||||
// A book, or a source of another kind
|
||||
return join(
|
||||
bibDisplayAuthor(source, true),
|
||||
bibDisplayYear(source),
|
||||
italic(bibDisplayTitle(source)),
|
||||
bibDisplayEdition(source),
|
||||
bibDisplayCity(source),
|
||||
bibDisplayPublisher(source),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** The initials of a name, with no dots or spaces, such as "MA" of "Mary Ann" (`splitNameSpace`) */
|
||||
const splitNameSpace = (first: string): string => {
|
||||
const space = first.indexOf(" ");
|
||||
return space < 0 ? first.slice(0, 1) : first.slice(0, space).slice(0, 1) + splitNameSpace(first.slice(space + 1));
|
||||
};
|
||||
|
||||
/** The first four people, each as their last name and initials with nothing between, such as "SmithJJonesMA" (`formatPersonsAuthor`) */
|
||||
const formatPersonsAuthor = (people: readonly WordPerson[]): string =>
|
||||
people
|
||||
.slice(0, 4)
|
||||
.map(({ last, first, middle }) => last + splitNameSpace(first) + splitNameSpace(middle))
|
||||
.join("");
|
||||
|
||||
/**
|
||||
* A source's key in the order of the bibliography: who it is named by, or "Anon.", its year, or "n.d.", and its title,
|
||||
* or a case's or film's title and year (`b:SortingString`)
|
||||
*/
|
||||
const sortingStringOf = (source: WordSource): string => {
|
||||
const role = mainContributorsOf(source);
|
||||
const title = fieldOf(source, "Title");
|
||||
// "n.d." and "Anon." are the style's own
|
||||
const year = fieldOf(source, "Year") || "n.d.";
|
||||
if (source.type === "Case" || source.type === "Film") {
|
||||
return title + year;
|
||||
}
|
||||
const author = (role ? organizationOf(source, role) || formatPersonsAuthor(peopleOf(source, role)) : "") || "Anon.";
|
||||
return author + year + title;
|
||||
};
|
||||
|
||||
/**
|
||||
* How a citation names a source by its main people: one person's last name, two joined by "&", or the first of three
|
||||
* or more and "et al.", or else the organization that is the author, or "Anon." (`MainContributors`, as the citation
|
||||
* calls it, with no `returnType`)
|
||||
*/
|
||||
const mainContributorsNameOf = (source: WordSource): string => {
|
||||
const role = mainContributorsOf(source);
|
||||
const people = role ? peopleOf(source, role) : [];
|
||||
if (!people.length) {
|
||||
return organizationOf(source, "Author") || "Anon.";
|
||||
}
|
||||
// Each person's last name, or if nobody has one their first names, or their middle names, as the XSL's `xsl:when`s
|
||||
const part = people.some((person) => person.last) ? "last" : people.some((person) => person.first) ? "first" : "middle";
|
||||
// The first person's who has one, as `value-of select="b:NameList/b:Person/b:Last"`
|
||||
const [name] = people.map((person) => person[part]).filter((value) => value !== "");
|
||||
// " & " and ", et al." are the style's own
|
||||
return people.length === 1 ? name : people.length === 2 ? `${name} & ${people[1][part]}` : `${name}, et al.`;
|
||||
};
|
||||
|
||||
/** The volume or pages cited, such as "2:5", "vol. 2" or "pp. 5-9" (`VolumePages`) */
|
||||
const volumePages = (volume: string, pages: string): string => {
|
||||
if (volume && pages) {
|
||||
return volume + general.Enum + pages;
|
||||
}
|
||||
if (volume) {
|
||||
// A volume with a comma or a hyphen is several
|
||||
const several = volume.includes(",") || translate(volume, general.Hyphens, "") !== volume;
|
||||
return textOf(xsl.stringFormat(several ? strings.VolumesShortUnCap : strings.VolumeShortUnCap, volume));
|
||||
}
|
||||
return pages ? displayPageOrPages(pages) : "";
|
||||
};
|
||||
|
||||
/**
|
||||
* A source of a citation, such as "(Baker, 2010, p. 50" before the next source's "; ": a case or a film by its title, and
|
||||
* any other source by its people (`Citation`)
|
||||
*/
|
||||
const citation = (cited: CitedSource): FormattedText => {
|
||||
const { source } = cited;
|
||||
const year = fieldOf(source, "Year") || strings.NoDateShortUnCap;
|
||||
const volpagesInfo = volumePages(cited.volume, cited.pages);
|
||||
const isCaseOrFilm = source.type === "Case" || source.type === "Film";
|
||||
const name = isCaseOrFilm ? (cited.hideTitle ? "" : fieldOf(source, "Title")) : cited.hideAuthor ? "" : mainContributorsNameOf(source);
|
||||
|
||||
let text = cited.first ? general.OpenBracket : "";
|
||||
text += cited.prefix ?? "";
|
||||
if (name) {
|
||||
text += name + (!cited.hideYear || volpagesInfo ? general.ListSeparator : "");
|
||||
}
|
||||
if (!cited.hideYear) {
|
||||
text += year + (volpagesInfo ? general.ListSeparator : "");
|
||||
}
|
||||
text += volpagesInfo;
|
||||
text += cited.suffix ?? "";
|
||||
text += cited.last ? general.CloseBracket : general.GroupSeparator;
|
||||
return join(text);
|
||||
};
|
||||
|
||||
/** Harvard - Anglia: Word's `HarvardAnglia2008OfficeOnline.xsl` */
|
||||
export const harvardAnglia: StyleDefinition = {
|
||||
name: "Harvard - Anglia",
|
||||
file: "HarvardAnglia2008OfficeOnline.xsl",
|
||||
version: "2008",
|
||||
citation,
|
||||
bibliography: (sources) => ({
|
||||
paragraphs: sortByKey(sources, sortingStringOf).map(proceedBibliography),
|
||||
hangingIndent: false,
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,370 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type CorpusOutput, describeWordOutput, outputOf } from "tests/bibliography";
|
||||
|
||||
import type { CitedSourceOptions } from "../format";
|
||||
import type { Source } from "../source";
|
||||
import expected from "./fixtures/ieee.json";
|
||||
import { ieee } from "./ieee";
|
||||
|
||||
// Sources the fixtures don't have, for the style's other branches. What they're written as is what Word's style,
|
||||
// IEEE2006OfficeOnline.xsl, writes for them when run with libxslt and Word's English wording
|
||||
const CASES: readonly {
|
||||
readonly name: string;
|
||||
readonly sources: readonly Source[];
|
||||
readonly citations?: readonly (readonly CitedSourceOptions[])[];
|
||||
readonly cited?: readonly string[];
|
||||
readonly bibliography: CorpusOutput["bibliography"];
|
||||
}[] = [
|
||||
{
|
||||
name: "a first name with a hyphen and a space",
|
||||
sources: [
|
||||
{ tag: "T1", type: "book", authors: [{ lastName: "Brown", firstName: "Jean-Paul Marc" }], title: "Pancakes", year: "2014" },
|
||||
],
|
||||
bibliography: { rows: [["[1] ", "J.-P. M. Brown, Pancakes, 2014. "]] },
|
||||
},
|
||||
{
|
||||
name: "one director with a hyphenated first name",
|
||||
sources: [{ tag: "T1", type: "film", directors: [{ lastName: "Gray", firstName: "Jean-Luc" }], title: "Breathless", year: "1960" }],
|
||||
bibliography: { rows: [["[1] ", "J.-L. Gray, Director, <i>Breathless. </i>[Film]. 1960. "]] },
|
||||
},
|
||||
{
|
||||
name: "several directors",
|
||||
sources: [
|
||||
{
|
||||
tag: "T1",
|
||||
type: "film",
|
||||
directors: [
|
||||
{ lastName: "Smith", firstName: "Joel" },
|
||||
{ lastName: "Smith", firstName: "Ethan" },
|
||||
],
|
||||
title: "Snow",
|
||||
},
|
||||
],
|
||||
bibliography: { rows: [["[1] ", "J. Smith and E. Smith, Directors, <i>Snow. </i>[Film]. "]] },
|
||||
},
|
||||
{
|
||||
name: "people without a last name in a list",
|
||||
sources: [
|
||||
{
|
||||
tag: "T1",
|
||||
type: "book",
|
||||
authors: [
|
||||
{ lastName: "", firstName: "Ann" },
|
||||
{ lastName: "", firstName: "Bob" },
|
||||
{ lastName: "Lee", firstName: "Cy" },
|
||||
],
|
||||
title: "Lists",
|
||||
},
|
||||
],
|
||||
bibliography: { rows: [["[1] ", "A. B. and C. Lee, Lists. "]] },
|
||||
},
|
||||
{
|
||||
name: "several writers of a performance",
|
||||
sources: [
|
||||
{
|
||||
tag: "T1",
|
||||
type: "performance",
|
||||
writers: [
|
||||
{ lastName: "Nash", firstName: "Leo" },
|
||||
{ lastName: "Holt", firstName: "Eve" },
|
||||
],
|
||||
title: "A Play",
|
||||
productionCompany: "Opera Co",
|
||||
},
|
||||
],
|
||||
bibliography: { rows: [["[1] ", "L. Nash and E. Holt, Writers, <i>A Play. </i>[Performance]. Opera Co. "]] },
|
||||
},
|
||||
{
|
||||
name: "several interviewees and artists",
|
||||
sources: [
|
||||
{
|
||||
tag: "T1",
|
||||
type: "interview",
|
||||
interviewees: [
|
||||
{ lastName: "Russo", firstName: "Gina" },
|
||||
{ lastName: "Mills", firstName: "Joe" },
|
||||
],
|
||||
title: "Talk",
|
||||
},
|
||||
{
|
||||
tag: "T2",
|
||||
type: "art",
|
||||
artists: [
|
||||
{ lastName: "Vega", firstName: "Rosa" },
|
||||
{ lastName: "Mora", firstName: "Luz" },
|
||||
],
|
||||
title: "Bread",
|
||||
institution: "Museum",
|
||||
},
|
||||
],
|
||||
bibliography: {
|
||||
rows: [
|
||||
["[1] ", "G. Russo and J. Mills, Interviewees, <i>Talk. </i>[Interview]. "],
|
||||
["[2] ", "R. Vega and L. Mora, Artists, <i>Bread. </i>[Art]. Museum. "],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "several composers, conductors and performers",
|
||||
sources: [
|
||||
{
|
||||
tag: "T1",
|
||||
type: "soundRecording",
|
||||
composers: [
|
||||
{ lastName: "Lane", firstName: "Mia" },
|
||||
{ lastName: "Fox", firstName: "Nick" },
|
||||
],
|
||||
title: "Song",
|
||||
},
|
||||
{ tag: "T2", type: "soundRecording", conductors: [{ lastName: "Lane", firstName: "Mia" }], title: "Song" },
|
||||
{
|
||||
tag: "T3",
|
||||
type: "soundRecording",
|
||||
conductors: [
|
||||
{ lastName: "Lane", firstName: "Mia" },
|
||||
{ lastName: "Fox", firstName: "Nick" },
|
||||
],
|
||||
title: "Song",
|
||||
},
|
||||
{
|
||||
tag: "T4",
|
||||
type: "soundRecording",
|
||||
performers: [
|
||||
{ lastName: "Day", firstName: "Joy" },
|
||||
{ lastName: "Ray", firstName: "Kai" },
|
||||
],
|
||||
title: "Song",
|
||||
},
|
||||
{ tag: "T5", type: "soundRecording", title: "Song" },
|
||||
],
|
||||
bibliography: {
|
||||
rows: [
|
||||
["[1] ", "M. Lane and N. Fox, Composers, <i>Song. </i>[Sound Recording]. "],
|
||||
["[2] ", "M. Lane, Conductor, <i>Song. </i>[Sound Recording]. "],
|
||||
["[3] ", "M. Lane and N. Fox, Conductors, <i>Song. </i>[Sound Recording]. "],
|
||||
["[4] ", "J. Day and K. Ray, Performers, <i>Song. </i>[Sound Recording]. "],
|
||||
["[5] ", "<i>Song. </i>[Sound Recording]. "],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "editors in place of the authors, with nothing after them",
|
||||
sources: [
|
||||
{ tag: "T1", type: "book", editors: [{ lastName: "Reid", firstName: "Lou" }] },
|
||||
{
|
||||
tag: "T2",
|
||||
type: "bookSection",
|
||||
editors: [
|
||||
{ lastName: "Reid", firstName: "Lou" },
|
||||
{ lastName: "Hart", firstName: "Una" },
|
||||
],
|
||||
},
|
||||
{ tag: "T3", type: "bookSection", editors: [{ lastName: "Reid", firstName: "Lou" }], year: "2001" },
|
||||
{ tag: "T4", type: "journalArticle", editors: [{ lastName: "Reid", firstName: "Lou" }], title: "Salt" },
|
||||
],
|
||||
bibliography: {
|
||||
rows: [
|
||||
["[1] ", "L. Reid, Ed. "],
|
||||
["[2] ", "L. Reid and U. Hart, Eds. "],
|
||||
["[3] ", "L. Reid, Ed., 2001. "],
|
||||
["[4] ", "L. Reid, Ed.“Salt”. "],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "editors after the authors, with nothing after them",
|
||||
sources: [
|
||||
{
|
||||
tag: "T1",
|
||||
type: "book",
|
||||
authors: [{ lastName: "Lee", firstName: "Ann" }],
|
||||
editors: [{ lastName: "Reid", firstName: "Lou" }],
|
||||
},
|
||||
{
|
||||
tag: "T2",
|
||||
type: "book",
|
||||
authors: [{ lastName: "Lee", firstName: "Ann" }],
|
||||
editors: [
|
||||
{ lastName: "Reid", firstName: "Lou" },
|
||||
{ lastName: "Hart", firstName: "Una-May" },
|
||||
],
|
||||
},
|
||||
],
|
||||
bibliography: {
|
||||
rows: [
|
||||
["[1] ", "A. Lee, L. Reid, Ed. "],
|
||||
["[2] ", "A. Lee, L. Reid and U. Hart, Eds. "],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "an organization with nothing after it",
|
||||
sources: [
|
||||
{ tag: "T1", type: "book", corporateAuthor: "Board" },
|
||||
{ tag: "T2", type: "report", corporateAuthor: "Agency" },
|
||||
{ tag: "T3", type: "conferenceProceedings", corporateAuthor: "Society" },
|
||||
{ tag: "T4", type: "journalArticle", corporateAuthor: "Council" },
|
||||
{ tag: "T5", type: "website", corporateAuthor: "WHO" },
|
||||
],
|
||||
bibliography: {
|
||||
rows: [
|
||||
["[1] ", "Board. "],
|
||||
["[2] ", "Agency."],
|
||||
["[3] ", "Society. "],
|
||||
["[4] ", "Council. "],
|
||||
["[5] ", "WHO, [Online]. "],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "titles with nothing after them",
|
||||
sources: [
|
||||
{ tag: "T1", type: "journalArticle", title: "Salt" },
|
||||
{ tag: "T2", type: "articleInAPeriodical", title: "Column" },
|
||||
{ tag: "T3", type: "report", title: "Annual" },
|
||||
{ tag: "T4", type: "conferenceProceedings", title: "Paper" },
|
||||
{ tag: "T5", type: "bookSection", title: "Starters" },
|
||||
{ tag: "T6", type: "book", title: "Pies" },
|
||||
{ tag: "T7", type: "case", title: "A v. B" },
|
||||
],
|
||||
bibliography: {
|
||||
rows: [
|
||||
["[1] ", "“Salt”. "],
|
||||
["[2] ", "“Column”. "],
|
||||
["[3] ", "“Annual”."],
|
||||
["[4] ", "“Paper”. "],
|
||||
["[5] ", "“Starters”. "],
|
||||
["[6] ", "Pies. "],
|
||||
["[7] ", "<i>A v. B.</i>"],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "authors and editors, and one more field",
|
||||
sources: [
|
||||
{
|
||||
tag: "T1",
|
||||
type: "bookSection",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
editors: [{ lastName: "Reid", firstName: "Lou" }],
|
||||
title: "Starters",
|
||||
},
|
||||
{ tag: "T2", type: "bookSection", authors: [{ lastName: "Fox", firstName: "Amy" }], title: "Starters" },
|
||||
{
|
||||
tag: "T3",
|
||||
type: "bookSection",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
editors: [{ lastName: "Reid", firstName: "Lou" }],
|
||||
bookTitle: "Menus",
|
||||
},
|
||||
{ tag: "T4", type: "bookSection", authors: [{ lastName: "Fox", firstName: "Amy" }], bookTitle: "Menus" },
|
||||
{ tag: "T5", type: "bookSection", bookTitle: "Menus" },
|
||||
{
|
||||
tag: "T6",
|
||||
type: "book",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
editors: [{ lastName: "Reid", firstName: "Lou" }],
|
||||
volume: "3",
|
||||
},
|
||||
{ tag: "T7", type: "book", authors: [{ lastName: "Fox", firstName: "Amy" }], volume: "3" },
|
||||
{ tag: "T8", type: "book", volume: "3" },
|
||||
{
|
||||
tag: "T9",
|
||||
type: "book",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
editors: [{ lastName: "Reid", firstName: "Lou" }],
|
||||
edition: "2nd",
|
||||
},
|
||||
{ tag: "T10", type: "book", authors: [{ lastName: "Fox", firstName: "Amy" }], edition: "2nd" },
|
||||
{ tag: "T11", type: "book", edition: "2nd" },
|
||||
{
|
||||
tag: "T12",
|
||||
type: "book",
|
||||
authors: [{ lastName: "Fox", firstName: "Amy" }],
|
||||
editors: [{ lastName: "Reid", firstName: "Lou" }],
|
||||
title: "Pies",
|
||||
},
|
||||
{ tag: "T13", type: "book", authors: [{ lastName: "Fox", firstName: "Amy" }], title: "Pies" },
|
||||
],
|
||||
bibliography: {
|
||||
rows: [
|
||||
["[1] ", "A. Fox, “Starters,” L. Reid, Ed. "],
|
||||
["[2] ", "A. Fox, “Starters”. "],
|
||||
["[3] ", "A. Fox, in <i>Menus</i>, L. Reid, Ed. "],
|
||||
["[4] ", "A. Fox, in <i>Menus</i>. "],
|
||||
["[5] ", "in <i>Menus</i>. "],
|
||||
["[6] ", "A. Fox, vol. 3, L. Reid, Ed. "],
|
||||
["[7] ", "A. Fox, vol. 3. "],
|
||||
["[8] ", "vol. 3. "],
|
||||
["[9] ", "A. Fox, 2nd ed., L. Reid, Ed. "],
|
||||
["[10] ", "A. Fox, 2nd ed. "],
|
||||
["[11] ", "2nd ed. "],
|
||||
["[12] ", "A. Fox, Pies, L. Reid, Ed. "],
|
||||
["[13] ", "A. Fox, Pies. "],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "journal fields with nothing after them",
|
||||
sources: [
|
||||
{ tag: "T1", type: "journalArticle", journalName: "Taste" },
|
||||
{ tag: "T2", type: "articleInAPeriodical", periodicalTitle: "Daily" },
|
||||
{ tag: "T3", type: "journalArticle", volume: "2-3" },
|
||||
{ tag: "T4", type: "journalArticle", year: "2001", volume: "2, 4" },
|
||||
{ tag: "T5", type: "journalArticle", volume: "7" },
|
||||
{ tag: "T6", type: "journalArticle", issue: "4" },
|
||||
],
|
||||
bibliography: {
|
||||
rows: [
|
||||
["[1] ", "<i>Taste.</i> "],
|
||||
["[2] ", "<i>Daily.</i> "],
|
||||
["[3] ", "Vols. 2-3. "],
|
||||
["[4] ", "Vols. 2, 4, 2001. "],
|
||||
["[5] ", "vol. 7. "],
|
||||
["[6] ", "no. 4. "],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "places with nothing after them",
|
||||
sources: [
|
||||
{ tag: "T1", type: "book", city: "Leeds" },
|
||||
{ tag: "T2", type: "book", city: "Leeds", stateOrProvince: "Yorkshire" },
|
||||
{ tag: "T3", type: "bookSection", city: "Leeds" },
|
||||
{ tag: "T4", type: "book", stateOrProvince: "Yorkshire" },
|
||||
{ tag: "T5", type: "book", year: "2001", stateOrProvince: "Yorkshire" },
|
||||
{ tag: "T6", type: "report", publisher: "Press" },
|
||||
{ tag: "T7", type: "website", productionCompany: "Studio" },
|
||||
{ tag: "T8", type: "patent", countryOrRegion: "France" },
|
||||
{ tag: "T9", type: "patent", year: "2001", countryOrRegion: "France" },
|
||||
],
|
||||
bibliography: {
|
||||
rows: [
|
||||
["[1] ", "Leeds. "],
|
||||
["[2] ", "Leeds, Yorkshire. "],
|
||||
["[3] ", "Leeds. "],
|
||||
["[4] ", "Yorkshire. "],
|
||||
["[5] ", "Yorkshire, 2001. "],
|
||||
["[6] ", "Press."],
|
||||
["[7] ", "Studio. [Online]. "],
|
||||
["[8] ", "France."],
|
||||
["[9] ", "France 2001."],
|
||||
],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
describe("ieee", () => {
|
||||
describeWordOutput(ieee, expected);
|
||||
|
||||
describe("as Word's style writes", () => {
|
||||
for (const { name, sources, citations = [], cited = [], bibliography } of CASES) {
|
||||
it(`writes ${name}`, () => {
|
||||
const output = outputOf(ieee, { sources, citations });
|
||||
expect(output.citations).toEqual(cited);
|
||||
expect(output.bibliography).toEqual(bibliography);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,664 @@
|
||||
/**
|
||||
* IEEE: citations such as "[1]" or "[1, p. 50]", and a bibliography that is a table of each source's number and its
|
||||
* entry, such as "[1] A. Baker, The Art of Pizza, Naples: Pizza Press, 2010.", in the order the sources are cited.
|
||||
*
|
||||
* Written from Word's style, IEEE2006OfficeOnline.xsl, whose templates each function names. Unlike Word's other styles,
|
||||
* it writes people's initials and its lists of people with templates of its own, and has some English words written
|
||||
* into it, such as "Available:" and "Artist".
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type FormattedText, type TextLike, italic, join } from "./formatted-text";
|
||||
import { LOCALS } from "./locals";
|
||||
import type { StyleDefinition } from "./style";
|
||||
import {
|
||||
type Field,
|
||||
type Role,
|
||||
type WordPerson,
|
||||
type WordSource,
|
||||
type WordSourceType,
|
||||
fieldOf,
|
||||
organizationOf,
|
||||
peopleOf,
|
||||
} from "../word-source";
|
||||
|
||||
// The names of some of the style's templates, as the style spells them
|
||||
// cspell:words Hypen Artcicle
|
||||
|
||||
const { General, Strings, APA, SourceNames } = LOCALS;
|
||||
const SPACE = General.Space;
|
||||
const DOT = General.Dot;
|
||||
const LIST = General.ListSeparator;
|
||||
const DASH = General.FromToDash;
|
||||
// The style's brackets are APA's secondary ones, which its SecondaryOpen and SecondaryClose read
|
||||
const OPEN = APA.SecondaryOpen;
|
||||
const CLOSE = APA.SecondaryClose;
|
||||
|
||||
/** Whether the source has any of the fields, as the style's `count(b:Field)!=0` */
|
||||
const hasAny = (source: WordSource, ...fields: readonly Field[]): boolean => fields.some((field) => fieldOf(source, field) !== "");
|
||||
|
||||
/** The text without the spaces, tabs and line feeds at its end (`right-trim`) */
|
||||
const rightTrim = (text: string): string => text.replace(/[ \t\r\n]+$/, "");
|
||||
|
||||
/** The text without the spaces at its start (`left-trim`) */
|
||||
const leftTrim = (text: string): string => text.replace(/^ +/, "");
|
||||
|
||||
/** The text with each occurrence of a string replaced (`FindReplaceString`) */
|
||||
const findReplace = (text: string, find: string, replacement: string): string => text.split(find).join(replacement);
|
||||
|
||||
/** The list separator without its spaces, such as "," (`List_Separator_NoSpace`) */
|
||||
const LIST_WITHOUT_SPACE = findReplace(LIST, " ", "");
|
||||
|
||||
/** Pages, such as "p. 50" or "pp. 50-62", in English whatever the language (`DisplayPageOrPages`) */
|
||||
const pageOrPages = (cited: string): string => (cited.includes("-") || cited.includes(",") ? `pp. ${cited}` : `p. ${cited}`);
|
||||
|
||||
/** The initial of each word of a name, such as "M. A." of "Mary Ann" (`splitAuthorSpace`) */
|
||||
const splitAuthorSpace = (name: string): string => {
|
||||
const space = name.indexOf(" ");
|
||||
return space < 0
|
||||
? name.slice(0, 1) + DOT
|
||||
: name.slice(0, space).slice(0, 1) + DOT + SPACE + splitAuthorSpace(leftTrim(name.slice(space + 1)));
|
||||
};
|
||||
|
||||
/** The initials of a hyphenated name, such as "J.-P." of "Jean-Paul" (`HandleHypenInAuthor`) */
|
||||
const handleHyphenInAuthor = (name: string, initials: string = ""): string => {
|
||||
const initial = !name.startsWith(DASH) && initials === "" ? name.slice(0, 1) + DOT : "";
|
||||
const dash = name.indexOf(DASH);
|
||||
if (dash < 0) {
|
||||
return initial + initials;
|
||||
}
|
||||
const after = name.slice(dash + DASH.length);
|
||||
return initial + handleHyphenInAuthor(after, initials + DASH + after.slice(0, 1) + DOT);
|
||||
};
|
||||
|
||||
/** The initials of each word of a name, each word's hyphenated parts too, such as "J.-P. A." (`HandleSPaceHypenInAuthor`) */
|
||||
const handleSpaceHyphenInAuthor = (name: string): string => {
|
||||
const space = name.indexOf(" ");
|
||||
return space < 0
|
||||
? handleHyphenInAuthor(name)
|
||||
: handleHyphenInAuthor(name.slice(0, space)) + SPACE + handleSpaceHyphenInAuthor(leftTrim(name.slice(space + 1)));
|
||||
};
|
||||
|
||||
/** How a list of people writes a first or middle name's initials */
|
||||
type Initials = (name: string) => string;
|
||||
|
||||
/** The initials of a name, which has its trailing spaces trimmed, with hyphenated names' (most lists of people) */
|
||||
const hyphenated: Initials = (name) =>
|
||||
name.includes(DASH) ? handleSpaceHyphenInAuthor(rightTrim(name)) : splitAuthorSpace(rightTrim(name));
|
||||
|
||||
/** The initials of a name, hyphenated without its trailing spaces trimmed (a single director's first name) */
|
||||
const hyphenatedUntrimmed: Initials = (name) => (name.includes(DASH) ? handleSpaceHyphenInAuthor(name) : splitAuthorSpace(rightTrim(name)));
|
||||
|
||||
/** The initials of a name, its trailing spaces trimmed, without hyphenated names' (editors after the authors) */
|
||||
const unhyphenated: Initials = (name) => splitAuthorSpace(rightTrim(name));
|
||||
|
||||
/**
|
||||
* People as the style lists them: each one's initials and last name, a list separator after each but the last two, and
|
||||
* "and" before the last, such as "A. Baker, J. Smith and R. Patel". After the list comes its ending, and after one
|
||||
* person, it comes only when they have a last name.
|
||||
*
|
||||
* @param initials - How the first name's initials are written, then the middle name's
|
||||
* @param initialsOfOne - How they're written when there is one person
|
||||
*/
|
||||
const namesOf = (
|
||||
people: readonly WordPerson[],
|
||||
ending: string,
|
||||
initials: readonly [Initials, Initials] = [hyphenated, hyphenated],
|
||||
initialsOfOne: readonly [Initials, Initials] = initials,
|
||||
): string => {
|
||||
const nameOf = ({ first, middle }: WordPerson, [firstInitials, middleInitials]: readonly [Initials, Initials]): string =>
|
||||
(first ? firstInitials(first) + SPACE : "") + (middle ? middleInitials(middle) + SPACE : "");
|
||||
if (people.length === 1) {
|
||||
const [person] = people;
|
||||
return nameOf(person, initialsOfOne) + (person.last ? person.last + ending : "");
|
||||
}
|
||||
return (
|
||||
people
|
||||
.map(
|
||||
(person, index) =>
|
||||
(index === people.length - 1 ? SPACE + Strings.AndUnCap + SPACE : "") +
|
||||
nameOf(person, initials) +
|
||||
(person.last ? person.last + (index + 2 !== people.length && index + 1 < people.length ? LIST : "") : ""),
|
||||
)
|
||||
.join("") + ending
|
||||
);
|
||||
};
|
||||
|
||||
/** People with a role, their role after them, such as "M. Lane, Composer, " */
|
||||
const peopleWithRole = (people: readonly WordPerson[], one: string, many: string): string =>
|
||||
people.length === 0 ? "" : namesOf(people, LIST) + (people.length === 1 ? one : many);
|
||||
|
||||
/**
|
||||
* The separator after a book's, a book section's or a miscellaneous source's editors, when they're named in place of
|
||||
* its authors (`Seperator`)
|
||||
*/
|
||||
const separator = (source: WordSource): string => {
|
||||
switch (source.type) {
|
||||
case "Book":
|
||||
case "Misc":
|
||||
return hasAny(source, "Title", "Edition", "Volume", "City", "StateProvince", "Publisher", "Year", "Pages") ? LIST : SPACE;
|
||||
case "BookSection":
|
||||
return hasAny(source, "Title", "BookTitle", "Edition", "Volume", "City", "StateProvince", "Publisher", "Year", "Pages")
|
||||
? LIST
|
||||
: SPACE;
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
/** The editors, named in place of the authors, such as "E. Hemingway, Ed., " (`BibDisplayEditorNL`) */
|
||||
const editorNL = (source: WordSource): string => {
|
||||
const editors = peopleOf(source, "Editor");
|
||||
return namesOf(editors, LIST) + (editors.length === 1 ? Strings.EditorShortCap : Strings.EditorsShortCap) + separator(source);
|
||||
};
|
||||
|
||||
/**
|
||||
* The editors after the authors, such as "E. Hemingway, Ed., ", when the source has authors (`BibDisplayEditor` and
|
||||
* `BibDisplayEditorBook`)
|
||||
*/
|
||||
const editor = (source: WordSource): string => {
|
||||
const editors = peopleOf(source, "Editor");
|
||||
if (editors.length === 0 || (peopleOf(source, "Author").length === 0 && !organizationOf(source, "Author"))) {
|
||||
return "";
|
||||
}
|
||||
return (
|
||||
namesOf(editors, LIST, [unhyphenated, unhyphenated]) +
|
||||
(editors.length === 1 ? Strings.EditorShortCap : Strings.EditorsShortCap) +
|
||||
(hasAny(source, "City", "Publisher", "StateProvince", "Year", "Pages") ? LIST : SPACE)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* The authors, or the organization that wrote it, and a list separator after them when the entry goes on, or a dot. With
|
||||
* neither, a book, a book section, a journal article and a miscellaneous source name their editors instead
|
||||
*
|
||||
* @param following - The fields the entry goes on with
|
||||
* @param editorsFollow - Whether the entry goes on with the editors after the authors
|
||||
* @param editorsInstead - Whether the editors are named when the source has no authors
|
||||
*/
|
||||
const authorsOf = (
|
||||
source: WordSource,
|
||||
following: readonly Field[],
|
||||
{
|
||||
editorsFollow = false,
|
||||
editorsInstead = false,
|
||||
organizationEnding,
|
||||
}: { readonly editorsFollow?: boolean; readonly editorsInstead?: boolean; readonly organizationEnding?: string } = {},
|
||||
): string => {
|
||||
const authors = peopleOf(source, "Author");
|
||||
if (authors.length > 0) {
|
||||
const goesOn = hasAny(source, ...following) || (editorsFollow && peopleOf(source, "Editor").length > 0);
|
||||
return namesOf(authors, goesOn ? LIST : DOT);
|
||||
}
|
||||
const organization = organizationOf(source, "Author");
|
||||
if (organization) {
|
||||
return organization + (organizationEnding ?? (hasAny(source, ...following) ? LIST : DOT));
|
||||
}
|
||||
return editorsInstead && peopleOf(source, "Editor").length > 0 ? editorNL(source) : "";
|
||||
};
|
||||
|
||||
/** A book's or a miscellaneous source's authors (`BibDisplayAuthorBook`) */
|
||||
const authorBook = (source: WordSource): string =>
|
||||
authorsOf(source, ["Title", "Edition", "Volume", "City", "StateProvince", "Publisher", "Year", "Pages"], {
|
||||
editorsFollow: true,
|
||||
editorsInstead: true,
|
||||
});
|
||||
|
||||
/** A book section's authors (`BibDisplayAuthorBookSection`) */
|
||||
const authorBookSection = (source: WordSource): string =>
|
||||
authorsOf(source, ["Title", "BookTitle", "Edition", "Volume", "City", "StateProvince", "Publisher", "Year", "Pages"], {
|
||||
editorsFollow: true,
|
||||
editorsInstead: true,
|
||||
});
|
||||
|
||||
/** A website's or a document's authors, whose organization is always followed by a list separator (`BibDisplayAuthorWebsite`) */
|
||||
const authorWebsite = (source: WordSource): string =>
|
||||
authorsOf(source, ["Title", "ProductionCompany", "Year"], { organizationEnding: LIST });
|
||||
|
||||
/**
|
||||
* An article's authors, in a journal or a periodical. Both look for a journal's name, not a periodical's title
|
||||
* (`BibDisplayAuthorJArtcicle`)
|
||||
*/
|
||||
const authorJournalArticle = (source: WordSource): string =>
|
||||
authorsOf(source, ["Title", "JournalName", "Volume", "Issue", "Year", "Pages"], { editorsInstead: true });
|
||||
|
||||
/** A conference paper's authors (`BibDisplayAuthorConPr`) */
|
||||
const authorConferenceProceedings = (source: WordSource): string => authorsOf(source, ["Title", "ConferenceName", "City", "Year"]);
|
||||
|
||||
/** A report's or an electronic source's authors (`BibDisplayAuthorReport`) */
|
||||
const authorReport = (source: WordSource): string => authorsOf(source, ["Title", "City", "Publisher", "Year"]);
|
||||
|
||||
/** A patent's inventors (`BibDisplayAuthorPatent`) */
|
||||
const authorPatent = (source: WordSource): string => {
|
||||
const inventors = peopleOf(source, "Inventor");
|
||||
return inventors.length === 0 ? "" : namesOf(inventors, hasAny(source, "Title") ? LIST : DOT);
|
||||
};
|
||||
|
||||
/** A sound recording's composers, or its conductors, or its performers, with their role (`BibDisplayAuthorSoundRec`) */
|
||||
const authorSoundRecording = (source: WordSource): string => {
|
||||
const roles: readonly (readonly [Role, string, string])[] = [
|
||||
["Composer", Strings.ComposerCap, Strings.ComposersCap],
|
||||
["Conductor", Strings.ConductorCap, Strings.ConductorsCap],
|
||||
["Performer", Strings.PerformerCap, Strings.PerformersCap],
|
||||
];
|
||||
for (const [role, one, many] of roles) {
|
||||
const people = peopleOf(source, role);
|
||||
if (people.length > 0) {
|
||||
return peopleWithRole(people, one + LIST, many + LIST);
|
||||
}
|
||||
}
|
||||
const performer = organizationOf(source, "Performer");
|
||||
return performer ? performer + LIST + Strings.PerformerCap + LIST : "";
|
||||
};
|
||||
|
||||
/** A performance's writers, with their role (`BibDisplayAuthorPerformance`) */
|
||||
const authorPerformance = (source: WordSource): string =>
|
||||
peopleWithRole(peopleOf(source, "Writer"), Strings.WriterCap + LIST, Strings.WritersCap + LIST);
|
||||
|
||||
/** An interview's interviewees, with their role in English (`BibDisplayAuthorInterview`) */
|
||||
const authorInterview = (source: WordSource): string =>
|
||||
peopleWithRole(peopleOf(source, "Interviewee"), `Interviewee${LIST}${SPACE}`, `Interviewees${LIST}${SPACE}`);
|
||||
|
||||
/** A work of art's artists, with their role in English (`BibDisplayArtist`) */
|
||||
const artist = (source: WordSource): string =>
|
||||
peopleWithRole(peopleOf(source, "Artist"), `Artist${LIST}${SPACE}`, `Artists${LIST}${SPACE}`);
|
||||
|
||||
/** A film's directors, with their role. A single director's hyphenated first name isn't trimmed first (`BibDisplayDirector`) */
|
||||
const director = (source: WordSource): string => {
|
||||
const directors = peopleOf(source, "Director");
|
||||
if (directors.length === 0) {
|
||||
return "";
|
||||
}
|
||||
return (
|
||||
namesOf(directors, LIST, [hyphenated, hyphenated], [hyphenatedUntrimmed, hyphenated]) +
|
||||
(directors.length === 1 ? Strings.DirectorCap : Strings.DirectorsCap) +
|
||||
LIST
|
||||
);
|
||||
};
|
||||
|
||||
/** A title in quotes, and a list separator in the quotes when the entry goes on, or a dot after them */
|
||||
const quotedTitle = (source: WordSource, goesOn: boolean): string => {
|
||||
if (!hasAny(source, "Title")) {
|
||||
return "";
|
||||
}
|
||||
const quoted = General.OpenQuote + rightTrim(fieldOf(source, "Title"));
|
||||
return goesOn ? quoted + LIST_WITHOUT_SPACE + General.CloseQuote + SPACE : quoted + General.CloseQuote + DOT;
|
||||
};
|
||||
|
||||
/** A journal article's title (`BibDisplayTitleJournal`) */
|
||||
const titleJournal = (source: WordSource): string => quotedTitle(source, hasAny(source, "JournalName", "Volume", "Issue", "Pages", "Year"));
|
||||
|
||||
/** An article's title in a periodical (`BibDisplayTitleAP`) */
|
||||
const titleArticleInAPeriodical = (source: WordSource): string => quotedTitle(source, hasAny(source, "Volume", "Issue", "Pages", "Year"));
|
||||
|
||||
/** A report's or an electronic source's title (`BibDisplayTitleReport`) */
|
||||
const titleReport = (source: WordSource): string => quotedTitle(source, hasAny(source, "City", "Year", "Publisher"));
|
||||
|
||||
/** A conference paper's title (`BibDisplayTitleConferenceProceedings`) */
|
||||
const titleConferenceProceedings = (source: WordSource): string => quotedTitle(source, hasAny(source, "ConferenceName", "City", "Year"));
|
||||
|
||||
/** A book section's title (`BibDisplayTitleBC`) */
|
||||
const titleBookSection = (source: WordSource): string =>
|
||||
quotedTitle(
|
||||
source,
|
||||
hasAny(source, "BookTitle", "Edition", "Volume", "City", "StateProvince", "Publisher", "Year", "Pages") ||
|
||||
(peopleOf(source, "Author").length > 0 && peopleOf(source, "Editor").length > 0),
|
||||
);
|
||||
|
||||
/** A web page's title, with a list separator in the quotes (`BibDisplayTitleWebSite`) */
|
||||
const titleWebsite = (source: WordSource): string =>
|
||||
hasAny(source, "Title")
|
||||
? General.OpenQuote + rightTrim(fieldOf(source, "Title")) + LIST_WITHOUT_SPACE + General.CloseQuote + SPACE
|
||||
: "";
|
||||
|
||||
/** A patent's title (`BibDisplayTitlePatent`) */
|
||||
const titlePatent = (source: WordSource): string =>
|
||||
hasAny(source, "Title") ? General.OpenQuote + rightTrim(fieldOf(source, "Title")) + General.CloseQuote + DOT + SPACE : "";
|
||||
|
||||
/** A book's or a miscellaneous source's title (`BibDisplayTitleBook`) */
|
||||
const titleBook = (source: WordSource): string => {
|
||||
if (!hasAny(source, "Title")) {
|
||||
return "";
|
||||
}
|
||||
const goesOn =
|
||||
hasAny(source, "Edition", "Volume", "City", "StateProvince", "Publisher", "Year", "Pages") ||
|
||||
(peopleOf(source, "Author").length > 0 && peopleOf(source, "Editor").length > 0);
|
||||
return rightTrim(fieldOf(source, "Title")) + (goesOn ? LIST : DOT);
|
||||
};
|
||||
|
||||
/** A title and a dot (`BibDisplayTitle`, `BibDisplayTitleInt` and `BibDisplayTitlePerformance`) */
|
||||
const title = (source: WordSource): string => (hasAny(source, "Title") ? rightTrim(fieldOf(source, "Title")) + DOT + SPACE : "");
|
||||
|
||||
/** A court case's title (`BibDisplayTitleCase`) */
|
||||
const titleCase = (source: WordSource): string =>
|
||||
hasAny(source, "Title") ? rightTrim(fieldOf(source, "Title")) + (hasAny(source, "Year") ? LIST : DOT) : "";
|
||||
|
||||
/** The title of the book a book section is in, after "in" (`BibDisplayBookTitle`) */
|
||||
const bookTitle = (source: WordSource): FormattedText => {
|
||||
if (!hasAny(source, "BookTitle")) {
|
||||
return [];
|
||||
}
|
||||
const goesOn =
|
||||
hasAny(source, "Edition", "Volume", "City", "StateProvince", "Publisher", "Year", "Pages") ||
|
||||
(peopleOf(source, "Author").length > 0 && peopleOf(source, "Editor").length > 0);
|
||||
return join(findReplace(Strings.InNameUnCap, " %1", SPACE) + SPACE, italic(fieldOf(source, "BookTitle")), goesOn ? LIST : DOT);
|
||||
};
|
||||
|
||||
/** The name of the conference a paper is from, after "in" (`BibDisplayConferenceName`) */
|
||||
const conferenceName = (source: WordSource): FormattedText =>
|
||||
hasAny(source, "ConferenceName")
|
||||
? join(
|
||||
findReplace(Strings.InNameUnCap, " %1", SPACE) + SPACE,
|
||||
italic(fieldOf(source, "ConferenceName")),
|
||||
hasAny(source, "City", "Year") ? LIST : DOT,
|
||||
)
|
||||
: [];
|
||||
|
||||
/** A journal's name (`BibDisplayJournalName`) */
|
||||
const journalName = (source: WordSource): string =>
|
||||
hasAny(source, "JournalName") ? fieldOf(source, "JournalName") + (hasAny(source, "Volume", "Issue", "Pages", "Year") ? LIST : DOT) : "";
|
||||
|
||||
/** A periodical's title (`BibDisplayJournalNameAP`) */
|
||||
const periodicalTitle = (source: WordSource): string =>
|
||||
hasAny(source, "PeriodicalTitle")
|
||||
? fieldOf(source, "PeriodicalTitle") + (hasAny(source, "Volume", "Issue", "Pages", "Year") ? LIST : DOT)
|
||||
: "";
|
||||
|
||||
/** A volume, such as "vol. 3", or volumes, such as "Vols. 2-3" */
|
||||
const volumeOf = (source: WordSource): string => {
|
||||
const volume = fieldOf(source, "Volume");
|
||||
return volume.includes("-") || volume.includes(",")
|
||||
? findReplace(Strings.VolumesOfShortCap, "%1 of %2", SPACE) + volume
|
||||
: SPACE + findReplace(Strings.VolumeShortUnCap, " %1", SPACE) + volume;
|
||||
};
|
||||
|
||||
/** A journal's or a periodical's volume (`BibDisplayVolumeJournal`) */
|
||||
const volumeJournal = (source: WordSource): string =>
|
||||
hasAny(source, "Volume") ? volumeOf(source) + (hasAny(source, "Pages", "Year", "Issue") ? LIST : DOT) : "";
|
||||
|
||||
/** A book's volume (`BibDisplayVolumeBook`) */
|
||||
const volumeBook = (source: WordSource): string => {
|
||||
if (!hasAny(source, "Volume")) {
|
||||
return "";
|
||||
}
|
||||
const goesOn =
|
||||
hasAny(source, "City", "StateProvince", "Publisher", "Year", "Pages") ||
|
||||
(peopleOf(source, "Author").length > 0 && peopleOf(source, "Editor").length > 0);
|
||||
return volumeOf(source) + (goesOn ? LIST : DOT);
|
||||
};
|
||||
|
||||
/** A journal's or a periodical's issue, such as "no. 4" (`BibDisplayIssueJournal`) */
|
||||
const issueJournal = (source: WordSource): string =>
|
||||
hasAny(source, "Issue")
|
||||
? SPACE +
|
||||
findReplace(Strings.NumberShortUnCap, " %1", SPACE) +
|
||||
fieldOf(source, "Issue") +
|
||||
(hasAny(source, "Pages", "Year") ? LIST : DOT)
|
||||
: "";
|
||||
|
||||
/** An article's pages (`BibDisplayPagesJournal`) */
|
||||
const pagesJournal = (source: WordSource): string =>
|
||||
hasAny(source, "Pages") ? pageOrPages(fieldOf(source, "Pages")) + (hasAny(source, "Year") ? LIST : DOT) : "";
|
||||
|
||||
/** A book's pages (`BibDisplayPages`) */
|
||||
const pagesBook = (source: WordSource): string => (hasAny(source, "Pages") ? pageOrPages(fieldOf(source, "Pages")) + DOT : "");
|
||||
|
||||
/** An edition, such as "2nd ed." (`BibDisplayEdition`) */
|
||||
const edition = (source: WordSource): string => {
|
||||
if (!hasAny(source, "Edition")) {
|
||||
return "";
|
||||
}
|
||||
const goesOn =
|
||||
hasAny(source, "Volume", "City", "StateProvince", "Publisher", "Year", "Pages") ||
|
||||
(peopleOf(source, "Author").length > 0 && peopleOf(source, "Editor").length > 0);
|
||||
return fieldOf(source, "Edition") + SPACE + Strings.EditorShortUnCap + (goesOn ? LIST : "");
|
||||
};
|
||||
|
||||
/** A book's or a miscellaneous source's city (`BibDisplayCity`) */
|
||||
const city = (source: WordSource): string => {
|
||||
if (!hasAny(source, "City")) {
|
||||
return "";
|
||||
}
|
||||
const ending =
|
||||
hasAny(source, "Publisher") && !hasAny(source, "StateProvince")
|
||||
? General.EnumSeparator
|
||||
: hasAny(source, "StateProvince", "Year", "Pages")
|
||||
? LIST
|
||||
: DOT;
|
||||
return fieldOf(source, "City") + ending;
|
||||
};
|
||||
|
||||
/** A book section's city (`BibDisplayCityBookSection`) */
|
||||
const cityBookSection = (source: WordSource): string =>
|
||||
hasAny(source, "City") ? fieldOf(source, "City") + (hasAny(source, "Publisher", "StateProvince", "Year", "Pages") ? LIST : DOT) : "";
|
||||
|
||||
/** A city with a list separator after it when the source has a year, or a dot (`BibDisplayCityReport` and `BibDisplayConfCityConfProc`) */
|
||||
const cityBeforeYear = (source: WordSource): string =>
|
||||
hasAny(source, "City") ? fieldOf(source, "City") + (hasAny(source, "Year") ? LIST : DOT) : "";
|
||||
|
||||
/** A state or province (`BibDisplayStateProvinceBook` and `BibDisplayStateProvinceBC`) */
|
||||
const stateProvince = (source: WordSource): string => {
|
||||
if (!hasAny(source, "StateProvince")) {
|
||||
return "";
|
||||
}
|
||||
const ending = hasAny(source, "Publisher") ? General.EnumSeparator + SPACE : hasAny(source, "Year", "Pages") ? LIST : DOT;
|
||||
return fieldOf(source, "StateProvince") + ending;
|
||||
};
|
||||
|
||||
/** A report's or an electronic source's publisher (`BibDisplayPublisher`) */
|
||||
const publisher = (source: WordSource): string =>
|
||||
hasAny(source, "Publisher") ? fieldOf(source, "Publisher") + (hasAny(source, "City", "Year") ? LIST : DOT) : "";
|
||||
|
||||
/** A book's publisher (`BibDisplayPublisherBC`) */
|
||||
const publisherBook = (source: WordSource): string =>
|
||||
hasAny(source, "Publisher") ? fieldOf(source, "Publisher") + (hasAny(source, "Year", "Pages") ? LIST : DOT) : "";
|
||||
|
||||
/** A year and a dot, and a space after it, with or without the year (`BibDisplayYear`) */
|
||||
const year = (source: WordSource): string => (hasAny(source, "Year") ? fieldOf(source, "Year") + DOT : "") + SPACE;
|
||||
|
||||
/** A year and a dot (`BibDisplayYearReport`, `BibDisplayYearCase` and `BibDisplayYearSoundrecording`) */
|
||||
const yearAndDot = (source: WordSource): string => (hasAny(source, "Year") ? fieldOf(source, "Year") + DOT : "");
|
||||
|
||||
/** A book's year, and a space after it, with or without the year (`BibDisplayYearBC`) */
|
||||
const yearBook = (source: WordSource): string =>
|
||||
(hasAny(source, "Year") ? fieldOf(source, "Year") + (hasAny(source, "Pages") ? LIST : DOT) : "") + SPACE;
|
||||
|
||||
/**
|
||||
* A date, such as "14 March 2018.", or the year alone when it has no month. A date with no year is left out
|
||||
* (`BibDisplayDayMonthYearInterview` and `BibDisplayDayMonthYearPatent`)
|
||||
*/
|
||||
const dayMonthYear = (source: WordSource): string => {
|
||||
if (!hasAny(source, "Year")) {
|
||||
return "";
|
||||
}
|
||||
const month = hasAny(source, "Month");
|
||||
const date =
|
||||
month && hasAny(source, "Day")
|
||||
? [fieldOf(source, "Day"), fieldOf(source, "Month"), fieldOf(source, "Year")]
|
||||
: month
|
||||
? [fieldOf(source, "Month"), fieldOf(source, "Year")]
|
||||
: [fieldOf(source, "Year")];
|
||||
return date.join(SPACE) + DOT;
|
||||
};
|
||||
|
||||
/** A website's or an article's date, and a space after it (`BibDisplayDayMonthYearWebSiteJournal`) */
|
||||
const dayMonthYearWebsiteJournal = (source: WordSource): string => dayMonthYear(source) + SPACE;
|
||||
|
||||
/** When a website or a document on one was read, such as " [Accessed 3 February 2022]." (`BibDisplayAccessedDates`) */
|
||||
const accessedDates = (source: WordSource): string => {
|
||||
if (!hasAny(source, "YearAccessed")) {
|
||||
return "";
|
||||
}
|
||||
const month = hasAny(source, "MonthAccessed");
|
||||
const date =
|
||||
month && hasAny(source, "DayAccessed")
|
||||
? [fieldOf(source, "DayAccessed"), fieldOf(source, "MonthAccessed"), fieldOf(source, "YearAccessed")]
|
||||
: month && !hasAny(source, "DayAccessed")
|
||||
? [fieldOf(source, "MonthAccessed"), fieldOf(source, "YearAccessed")]
|
||||
: [fieldOf(source, "YearAccessed")];
|
||||
return SPACE + OPEN + findReplace(Strings.AccessedCap, " %1", SPACE) + date.join(SPACE) + CLOSE + DOT;
|
||||
};
|
||||
|
||||
/** A website's address, after "Available:" in English (`BibDisplayURL`) */
|
||||
const url = (source: WordSource): string => (hasAny(source, "URL") ? `Available:${SPACE}${fieldOf(source, "URL")}${DOT}` : "");
|
||||
|
||||
/** A website's production company (`BibDisplayProductionCompanywebsite`) */
|
||||
const productionCompanyWebsite = (source: WordSource): string =>
|
||||
hasAny(source, "ProductionCompany")
|
||||
? fieldOf(source, "ProductionCompany") + (hasAny(source, "Month", "Day", "Year", "URL") ? LIST : DOT)
|
||||
: "";
|
||||
|
||||
/** A sound recording's production company (`BibDisplayProductionCompanySRec`) */
|
||||
const productionCompanySoundRecording = (source: WordSource): string =>
|
||||
hasAny(source, "ProductionCompany") ? fieldOf(source, "ProductionCompany") + DOT + SPACE : "";
|
||||
|
||||
/** A production company or an institution, and a list separator when the source has a year, or a dot */
|
||||
const beforeYear = (source: WordSource, field: Field): string =>
|
||||
hasAny(source, field) ? fieldOf(source, field) + (hasAny(source, "Year") ? LIST + SPACE : DOT) : "";
|
||||
|
||||
/** A film's country or region (`BibDisplayCountryRegionFilm`) */
|
||||
const countryRegionFilm = (source: WordSource): string =>
|
||||
hasAny(source, "CountryRegion")
|
||||
? fieldOf(source, "CountryRegion") + (hasAny(source, "ProductionCompany") ? General.EnumSeparator : DOT)
|
||||
: "";
|
||||
|
||||
/** A patent's country or region (`BibDisplayCountryRegionPatent`) */
|
||||
const countryRegionPatent = (source: WordSource): string =>
|
||||
hasAny(source, "CountryRegion") ? fieldOf(source, "CountryRegion") + (hasAny(source, "PatentNumber", "Year") ? SPACE : DOT) : "";
|
||||
|
||||
/** A patent's number, such as "Patent 7,123,456" (`BibDisplayPatent`) */
|
||||
const patent = (source: WordSource): string =>
|
||||
hasAny(source, "PatentNumber")
|
||||
? findReplace(Strings.PatentCap, " %1", SPACE) + fieldOf(source, "PatentNumber") + (hasAny(source, "Year") ? LIST + SPACE : DOT)
|
||||
: "";
|
||||
|
||||
/** A kind of source in brackets, such as "[Online]. " */
|
||||
const kindOf = (kind: string): string => OPEN + kind + CLOSE + DOT + SPACE;
|
||||
|
||||
/** A book's entry, with its title in italics for a miscellaneous source */
|
||||
const bookEntry = (source: WordSource, titleOf: (title: string) => TextLike): TextLike =>
|
||||
join(
|
||||
authorBook(source),
|
||||
titleOf(titleBook(source)),
|
||||
edition(source),
|
||||
volumeBook(source),
|
||||
editor(source),
|
||||
city(source),
|
||||
stateProvince(source),
|
||||
publisherBook(source),
|
||||
yearBook(source),
|
||||
pagesBook(source),
|
||||
);
|
||||
|
||||
/** A website's or a document's entry */
|
||||
const websiteEntry = (source: WordSource): TextLike =>
|
||||
join(
|
||||
authorWebsite(source),
|
||||
titleWebsite(source),
|
||||
productionCompanyWebsite(source),
|
||||
dayMonthYearWebsiteJournal(source),
|
||||
kindOf(Strings.OnlineCap),
|
||||
url(source),
|
||||
accessedDates(source),
|
||||
);
|
||||
|
||||
/** A report's or an electronic source's entry */
|
||||
const reportEntry = (source: WordSource): TextLike =>
|
||||
join(authorReport(source), titleReport(source), publisher(source), cityBeforeYear(source), yearAndDot(source));
|
||||
|
||||
/** Each type of source's entry in the bibliography (the template that matches `b:Source`) */
|
||||
const ENTRIES: Readonly<Record<WordSourceType, (source: WordSource) => TextLike>> = {
|
||||
Book: (source) => bookEntry(source, (text) => text),
|
||||
Misc: (source) => bookEntry(source, italic),
|
||||
BookSection: (source) =>
|
||||
join(
|
||||
authorBookSection(source),
|
||||
titleBookSection(source),
|
||||
bookTitle(source),
|
||||
edition(source),
|
||||
volumeBook(source),
|
||||
editor(source),
|
||||
cityBookSection(source),
|
||||
stateProvince(source),
|
||||
publisherBook(source),
|
||||
yearBook(source),
|
||||
pagesBook(source),
|
||||
),
|
||||
InternetSite: websiteEntry,
|
||||
DocumentFromInternetSite: websiteEntry,
|
||||
JournalArticle: (source) =>
|
||||
join(
|
||||
authorJournalArticle(source),
|
||||
titleJournal(source),
|
||||
italic(journalName(source)),
|
||||
volumeJournal(source),
|
||||
issueJournal(source),
|
||||
pagesJournal(source),
|
||||
dayMonthYearWebsiteJournal(source),
|
||||
),
|
||||
ArticleInAPeriodical: (source) =>
|
||||
join(
|
||||
authorJournalArticle(source),
|
||||
titleArticleInAPeriodical(source),
|
||||
italic(periodicalTitle(source)),
|
||||
volumeJournal(source),
|
||||
issueJournal(source),
|
||||
pagesJournal(source),
|
||||
dayMonthYearWebsiteJournal(source),
|
||||
),
|
||||
ConferenceProceedings: (source) =>
|
||||
join(
|
||||
authorConferenceProceedings(source),
|
||||
titleConferenceProceedings(source),
|
||||
conferenceName(source),
|
||||
cityBeforeYear(source),
|
||||
year(source),
|
||||
),
|
||||
Report: reportEntry,
|
||||
ElectronicSource: reportEntry,
|
||||
Art: (source) => join(artist(source), italic(title(source)), kindOf("Art"), beforeYear(source, "Institution"), year(source)),
|
||||
SoundRecording: (source) =>
|
||||
join(
|
||||
authorSoundRecording(source),
|
||||
italic(title(source)),
|
||||
kindOf(SourceNames.SoundRecording),
|
||||
productionCompanySoundRecording(source),
|
||||
yearAndDot(source),
|
||||
),
|
||||
Performance: (source) =>
|
||||
join(
|
||||
authorPerformance(source),
|
||||
italic(title(source)),
|
||||
kindOf("Performance"),
|
||||
beforeYear(source, "ProductionCompany"),
|
||||
year(source),
|
||||
),
|
||||
Interview: (source) => join(authorInterview(source), italic(title(source)), kindOf(Strings.InterviewCap), dayMonthYear(source)),
|
||||
Patent: (source) => join(authorPatent(source), titlePatent(source), countryRegionPatent(source), patent(source), dayMonthYear(source)),
|
||||
Film: (source) =>
|
||||
join(
|
||||
director(source),
|
||||
italic(title(source)),
|
||||
kindOf(SourceNames.Film),
|
||||
countryRegionFilm(source),
|
||||
beforeYear(source, "ProductionCompany"),
|
||||
year(source),
|
||||
),
|
||||
Case: (source) => join(italic(titleCase(source)), yearAndDot(source)),
|
||||
};
|
||||
|
||||
/** IEEE, as Word writes it with IEEE2006OfficeOnline.xsl */
|
||||
export const ieee: StyleDefinition = {
|
||||
name: "IEEE",
|
||||
file: "IEEE2006OfficeOnline.xsl",
|
||||
version: "2006",
|
||||
// The source's number, and the pages, after "p." or "pp." in English (`Citation`)
|
||||
citation: ({ source, first, last, pages: cited }) =>
|
||||
join(first ? OPEN : "", String(source.order), cited ? LIST + pageOrPages(cited) : "", last ? CLOSE : LIST + SPACE),
|
||||
// Each source's number and entry, in the order they're cited (`Bibliography` and `BibRefOrder`)
|
||||
bibliography: (sources) => ({
|
||||
rows: [...sources]
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((source) => [join(OPEN, String(source.order), CLOSE, SPACE), join(ENTRIES[source.type](source))] as const),
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,112 @@
|
||||
// cspell:words MSXML's
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { markupOf, outputOf } from "tests/bibliography";
|
||||
|
||||
import { copy, element, firstElementBibliography, firstElementCitation, readHtml, textOfHtml } from "./iso-690-family";
|
||||
import type { StyleDefinition } from "./style";
|
||||
|
||||
/** The style a variant of the family writes */
|
||||
const styleOf = (variant: "GB7714" | "ISO 690"): StyleDefinition => ({
|
||||
name: variant,
|
||||
file: "",
|
||||
version: "",
|
||||
citation: firstElementCitation(variant),
|
||||
bibliography: firstElementBibliography(variant),
|
||||
});
|
||||
|
||||
// Sources none of the corpora have: listed by a conductor, a producer and a compiler, and a work of art with a publisher
|
||||
// but no place. What the styles write for them is what Word's own styles write when they're run with libxslt
|
||||
const corpus = {
|
||||
sources: [
|
||||
{ tag: "Conductor", type: "soundRecording", conductors: [{ lastName: "Cond", firstName: "Flo" }], title: "Song", year: "2001" },
|
||||
{ tag: "Producer", type: "film", producers: [{ lastName: "Prod", firstName: "Olga" }], title: "Movie", year: "2002" },
|
||||
{ tag: "Compiler", type: "miscellaneous", compilers: [{ lastName: "Comp", firstName: "Di" }], title: "Notes", year: "2003" },
|
||||
{ tag: "Painting", type: "art", title: "Painting", year: "2004", publisher: "Museum Press" },
|
||||
],
|
||||
citations: [
|
||||
[{ source: "Conductor", pages: "5", hideAuthor: true, hideYear: true }],
|
||||
[{ source: "Painting", volume: "2", hideAuthor: true, hideYear: true }],
|
||||
[{ source: "Compiler" }],
|
||||
],
|
||||
} as const;
|
||||
|
||||
// Sources that show where GB7714's templates differ from ISO 690's, as Word's styles write them when run with libxslt
|
||||
const differences = {
|
||||
sources: [
|
||||
{ tag: "Page", type: "website", title: "Page", productionCompany: "Studio", url: "https://example.com/p" },
|
||||
{ tag: "Brief", type: "report", year: "2005", city: "Paris", publisher: "Press", productionCompany: "Studio" },
|
||||
{ tag: "U1", type: "book", title: "Untitled" },
|
||||
{ tag: "Lee", type: "book", authors: [{ lastName: "Lee", firstName: "Ann", middleName: "Kay" }], title: "Ovens", year: "2006" },
|
||||
],
|
||||
citations: [[{ source: "U1" }], [{ source: "Lee" }], [{ source: "Brief" }]],
|
||||
} as const;
|
||||
|
||||
describe("readHtml", () => {
|
||||
it("collapses each run of spaces into one, with none at the start of a paragraph", () => {
|
||||
expect(readHtml([[" Pizza and\n basil "]]).map(markupOf)).toEqual(["Pizza and basil "]);
|
||||
});
|
||||
|
||||
it("writes a space between an element and the element after it, as Word reads MSXML's line break", () => {
|
||||
expect(readHtml([[element("b", "Baker."), element("i", "Pizza.")]]).map(markupOf)).toEqual(["<b>Baker.</b> <i>Pizza.</i>"]);
|
||||
});
|
||||
|
||||
it("writes a space at the end of a copy of a variable between an element and the end of the paragraph", () => {
|
||||
expect(readHtml([["Paris. ", copy(element("i", "Pizza."))]]).map(markupOf)).toEqual(["Paris. <i>Pizza.</i> "]);
|
||||
});
|
||||
|
||||
it("leaves the formatting of a copied element with nothing in it on, for the rest of the bibliography", () => {
|
||||
expect(readHtml([[copy(element("b", copy()), "Pizza.")], ["Basil."]]).map(markupOf)).toEqual(["<b>Pizza.</b>", "<b>Basil.</b>"]);
|
||||
});
|
||||
|
||||
it("ends the formatting of a copied element with an empty xsl:value-of in it", () => {
|
||||
expect(readHtml([[copy(element("i", { value: "" }), "Pizza.")]]).map(markupOf)).toEqual(["Pizza."]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("textOfHtml", () => {
|
||||
it("is the text of what a style writes, as its string value", () => {
|
||||
expect(textOfHtml(["Pizza", { value: " and" }, copy(element("i", " basil"))])).toEqual("Pizza and basil");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the ISO 690 family", () => {
|
||||
describe.each(["GB7714", "ISO 690"] as const)("%s", (variant) => {
|
||||
it("cites pages or a volume alone when the author and year are left out", () => {
|
||||
expect(outputOf(styleOf(variant), corpus).citations).toEqual(["(p. 5)", "(vol. 2)", "(Comp, 2003)"]);
|
||||
});
|
||||
|
||||
it("names a source's conductor, producer or compiler, as what they are, when they're who it is listed by", () => {
|
||||
expect(outputOf(styleOf(variant), corpus).bibliography).toEqual({
|
||||
hangingIndent: false,
|
||||
paragraphs: [
|
||||
"<b>Comp, Di, [comp.]. 2003.</b> Notes. 2003.",
|
||||
"<b>Cond, Flo, [cond.]. 2001.</b> Song. 2001.",
|
||||
"<b>2004.</b> <i>Painting. </i>s.l. : Museum Press, 2004.",
|
||||
"<b>Prod, Olga, [prod.]. 2002.</b> <i>Movie. </i>2002.",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("writes a website with a production company, and a report with one, as the other style does", () => {
|
||||
// GB7714 writes a space after them by different fields than ISO 690, which Word reads as one space
|
||||
expect(outputOf(styleOf(variant), differences).bibliography).toEqual({
|
||||
hangingIndent: false,
|
||||
paragraphs: [
|
||||
"<b>2005.</b> Paris : Press, 2005.",
|
||||
"<b>Lee, Ann Kay. 2006.</b> <i>Ovens. </i>2006.",
|
||||
"Page. [Online] Studio. https://example.com/p.",
|
||||
"<i>Untitled. </i>",
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("cites a source by its tag in GB7714 when it has no author or year, though it has a title", () => {
|
||||
expect(outputOf(styleOf("GB7714"), differences).citations).toEqual(["(U1)", "(Lee, 2006)", "(2005)"]);
|
||||
});
|
||||
|
||||
it("cites a source with a title, but no author or year, by nothing in ISO 690", () => {
|
||||
expect(outputOf(styleOf("ISO 690"), differences).citations).toEqual(["()", "(Lee, 2006)", "(2005)"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,819 @@
|
||||
/**
|
||||
* The templates of Word's ISO 690 styles and of GB7714, written in TypeScript. GB.XSL and ISO690.XSL differ in only a few
|
||||
* of their templates, and ISO690Nmerical.XSL, ISO 690's numerical style, shares most of theirs: how each type of source
|
||||
* is written, its people, its place of publication and its dates.
|
||||
*
|
||||
* These styles write the names that a source starts with in bold, and its titles in italics. Word reads the HTML they
|
||||
* write with quirks, which {@link readHtml} follows: a space between two elements next to each other, and at the end of
|
||||
* a copy of a variable after an element, and formatting left on after an element of ISO 690's numerical style that is
|
||||
* empty.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
// cspell:words Countinous MSXML Nmerical
|
||||
import { type FormattedRun, type FormattedText, textOf } from "./formatted-text";
|
||||
import { LOCALS } from "./locals";
|
||||
import type { CitedSource, FormattedBibliography } from "./style";
|
||||
import { sortByKey, translate, xslTemplates } from "./xsl";
|
||||
import {
|
||||
type Field,
|
||||
type Role,
|
||||
type WordNames,
|
||||
type WordPerson,
|
||||
type WordSource,
|
||||
type WordSourceType,
|
||||
fieldOf,
|
||||
organizationOf,
|
||||
peopleOf,
|
||||
} from "../word-source";
|
||||
|
||||
const { General, Strings, ISO690 } = LOCALS;
|
||||
|
||||
/**
|
||||
* Which of the styles is writing: GB7714 and ISO 690 differ in a few of their templates. ISO 690's numerical style
|
||||
* writes its entries as ISO 690 by first element and date does
|
||||
*/
|
||||
export type Iso690Family = "GB7714" | "ISO 690";
|
||||
const { appendDot, formatDatePrivate, formatName, needDot, printList, stringFormat, stringFormatDot } = xslTemplates(General);
|
||||
|
||||
/**
|
||||
* What these styles write into their HTML: text, the text of an `xsl:value-of`, which MSXML keeps as a text node even
|
||||
* when it is empty, an element, bold (`<b>`) or italics (`<i>`), or a copy of a variable (`xsl:copy-of`), whose ends are
|
||||
* where MSXML writes a line break between elements
|
||||
*/
|
||||
export type HtmlNode =
|
||||
| string
|
||||
| { readonly value: string }
|
||||
| { readonly element: "b" | "i"; readonly content: readonly HtmlNode[] }
|
||||
| { readonly copy: readonly HtmlNode[] };
|
||||
|
||||
/** An element with its content */
|
||||
export const element = (name: "b" | "i", ...content: readonly HtmlNode[]): HtmlNode => ({ element: name, content });
|
||||
|
||||
/** A copy of a variable with its content */
|
||||
export const copy = (...content: readonly HtmlNode[]): HtmlNode => ({ copy: content });
|
||||
|
||||
/** The text of what a style writes, as its string value */
|
||||
export const textOfHtml = (nodes: readonly HtmlNode[]): string =>
|
||||
nodes
|
||||
.map((node) =>
|
||||
typeof node === "string" ? node : "value" in node ? node.value : textOfHtml("element" in node ? node.content : node.copy),
|
||||
)
|
||||
.join("");
|
||||
|
||||
type Token =
|
||||
{ readonly text: string } | { readonly open: "b" | "i"; readonly copied: boolean } | { readonly close: "b" | "i" } | "boundary";
|
||||
|
||||
/** What a style writes, as the tokens of its HTML. An element is copied when it's in a copy of a variable */
|
||||
const tokensOf = (nodes: readonly HtmlNode[], copied = false): readonly Token[] =>
|
||||
nodes.flatMap((node): readonly Token[] => {
|
||||
if (typeof node === "string") {
|
||||
return node ? [{ text: node }] : [];
|
||||
}
|
||||
if ("value" in node) {
|
||||
return [{ text: node.value }];
|
||||
}
|
||||
return "element" in node
|
||||
? [{ open: node.element, copied }, ...tokensOf(node.content, copied), { close: node.element }]
|
||||
: ["boundary", ...tokensOf(node.copy, true), "boundary"];
|
||||
});
|
||||
|
||||
/**
|
||||
* Paragraphs of a style's HTML, read as Word reads them: each run of spaces becomes one, as in HTML, and there's none at
|
||||
* the start of a paragraph. MSXML writes a line break, which Word reads as a space, between an element and an element
|
||||
* after it, and at the end of a copy of a variable between an element and the end of the paragraph.
|
||||
*
|
||||
* An element written into a variable and copied, with nothing in it, such as the bold of an entry of ISO 690's
|
||||
* numerical style with no author, is written as `<b/>`, which Word reads as a start tag that isn't ended: the rest of the
|
||||
* bibliography is bold, or in italics. An element with an `xsl:value-of` in it has a text node, though it is empty, so it
|
||||
* isn't written that way.
|
||||
*/
|
||||
export const readHtml = (paragraphs: readonly (readonly HtmlNode[])[]): readonly FormattedText[] => {
|
||||
const marks = { b: 0, i: 0 };
|
||||
return paragraphs.map((paragraph) => {
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const runs: FormattedRun[] = [];
|
||||
let lastNode: "text" | "start" | "end" | undefined;
|
||||
let boundary = false;
|
||||
// A copied element that has nothing written in it yet
|
||||
let emptyCopy: "b" | "i" | undefined;
|
||||
const lastText = (): string => runs[runs.length - 1]?.text ?? "";
|
||||
const space = (): void => {
|
||||
if (runs.length > 0 && !lastText().endsWith(" ")) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
runs.push({ text: " " });
|
||||
}
|
||||
};
|
||||
for (const token of tokensOf(paragraph)) {
|
||||
if (token === "boundary") {
|
||||
boundary = true;
|
||||
} else if ("text" in token) {
|
||||
let text = token.text.replace(/[ \t\r\n]+/g, " ");
|
||||
if (text.startsWith(" ") && (lastText() === "" || lastText().endsWith(" "))) {
|
||||
text = text.slice(1);
|
||||
}
|
||||
const run: FormattedRun = { text, ...(marks.b > 0 ? { bold: true } : {}), ...(marks.i > 0 ? { italics: true } : {}) };
|
||||
const last = runs[runs.length - 1];
|
||||
if (!text) {
|
||||
// Nothing to add
|
||||
} else if (last && !!last.bold === !!run.bold && !!last.italics === !!run.italics) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
runs[runs.length - 1] = { ...last, text: last.text + text };
|
||||
} else {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
runs.push(run);
|
||||
}
|
||||
lastNode = "text";
|
||||
boundary = false;
|
||||
emptyCopy = undefined;
|
||||
} else if ("open" in token) {
|
||||
if (lastNode === "end") {
|
||||
space();
|
||||
}
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
marks[token.open]++;
|
||||
emptyCopy = token.copied ? token.open : undefined;
|
||||
lastNode = "start";
|
||||
boundary = false;
|
||||
} else {
|
||||
if (emptyCopy !== token.close) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
marks[token.close]--;
|
||||
}
|
||||
emptyCopy = undefined;
|
||||
lastNode = "end";
|
||||
boundary = false;
|
||||
}
|
||||
}
|
||||
if (boundary && lastNode === "end") {
|
||||
space();
|
||||
}
|
||||
return runs;
|
||||
});
|
||||
};
|
||||
|
||||
/** The data in italics, as `ApplyItalicTitleNS` and `ApplyItalicFieldNS` write it: `<i>` around a copy of the data */
|
||||
export const applyItalic = (...data: readonly HtmlNode[]): HtmlNode => element("i", copy(...data));
|
||||
|
||||
/**
|
||||
* A source as the styles read it after `populateMain`: its fields, of which an interview drops some, its people, and its
|
||||
* main contributors, the role whose people it is listed by
|
||||
*/
|
||||
// eslint-disable-next-line functional/no-mixed-types -- its fields and people are read as an interview has them
|
||||
export type PopulatedSource = {
|
||||
readonly source: WordSource;
|
||||
readonly type: WordSourceType;
|
||||
/** A field, or "" when it doesn't have it */
|
||||
readonly field: (field: Field) => string;
|
||||
/** The people with a role, or the organization with it, if the source has it */
|
||||
readonly names: (role: Role) => WordNames | undefined;
|
||||
/** The role of its main contributors (`b:MainAuthorType`), or "" when it has none */
|
||||
readonly mainRole: Role | "";
|
||||
/** Its main contributors (`b:Author/b:Main`): the people with the main role, or the organization */
|
||||
readonly main: WordNames;
|
||||
};
|
||||
|
||||
/** The roles each type of source can be listed by, in the order the styles look for them (`MainContributors`) */
|
||||
const MAIN_ROLES: Readonly<Record<WordSourceType, readonly Role[]>> = {
|
||||
Book: ["Author", "Editor", "Translator"],
|
||||
BookSection: ["Author"],
|
||||
JournalArticle: ["Author", "Editor"],
|
||||
ArticleInAPeriodical: ["Author"],
|
||||
ConferenceProceedings: ["Author", "Editor"],
|
||||
Report: ["Author"],
|
||||
SoundRecording: ["Artist", "Performer", "Composer", "Conductor", "ProducerName"],
|
||||
Performance: ["Writer", "Director", "Performer", "ProducerName"],
|
||||
Art: ["Artist"],
|
||||
DocumentFromInternetSite: ["Author"],
|
||||
InternetSite: ["Author"],
|
||||
Film: ["Director", "Writer", "Performer", "ProducerName"],
|
||||
Interview: ["Interviewee"],
|
||||
Patent: ["Inventor"],
|
||||
ElectronicSource: ["Author", "Editor", "ProducerName", "Translator"],
|
||||
Case: ["Author", "Counsel"],
|
||||
Misc: ["Author", "Editor", "Compiler", "Translator"],
|
||||
};
|
||||
|
||||
/**
|
||||
* The string value of the people with a role, as XSL reads an element: each person's last, first and middle names, one
|
||||
* after another, or the organization
|
||||
*/
|
||||
export const stringOfNames = (names: WordNames | undefined): string =>
|
||||
names === undefined
|
||||
? ""
|
||||
: "corporate" in names
|
||||
? names.corporate
|
||||
: names.people.map(({ last, first, middle }) => last + first + middle).join("");
|
||||
|
||||
/**
|
||||
* A source as the styles read it, with its main contributors (`populateMain`). An interview with a broadcaster or the
|
||||
* title of a broadcast has no editors, translators, compilers or publisher, and one with neither has no station
|
||||
*/
|
||||
export const populate = (source: WordSource): PopulatedSource => {
|
||||
const { type } = source;
|
||||
const broadcast = type === "Interview" && (fieldOf(source, "Broadcaster") !== "" || fieldOf(source, "BroadcastTitle") !== "");
|
||||
const names = (role: Role): WordNames | undefined =>
|
||||
broadcast && (role === "Editor" || role === "Translator" || role === "Compiler") ? undefined : source.names[role];
|
||||
const field = (name: Field): string =>
|
||||
(type === "Interview" && !broadcast && name === "Station") || (broadcast && name === "Publisher") ? "" : fieldOf(source, name);
|
||||
const mainRole = MAIN_ROLES[type].find((role) => stringOfNames(source.names[role]) !== "") ?? "";
|
||||
const corporate = mainRole ? organizationOf(source, mainRole) : "";
|
||||
return {
|
||||
source,
|
||||
type,
|
||||
field,
|
||||
names,
|
||||
mainRole,
|
||||
main: corporate ? { corporate } : { people: mainRole ? peopleOf(source, mainRole) : [] },
|
||||
};
|
||||
};
|
||||
|
||||
/** What follows a person in a list of people: ", et al." after the first of four or more, ", " or " and " (`formatPersonSeparator`) */
|
||||
const formatPersonSeparator = (position: number, count: number): string => {
|
||||
if (count > 3) {
|
||||
// NoCommaBeforeAnd is "no"
|
||||
return General.AuthorsSeparator + Strings.AndOthersUnCap;
|
||||
}
|
||||
if (count - 1 > position) {
|
||||
return General.AuthorsSeparator;
|
||||
}
|
||||
// NoAndBeforeLastAuthor is "no"
|
||||
return position === count - 1 ? General.Space + Strings.AndUnCap + General.Space : "";
|
||||
};
|
||||
|
||||
/**
|
||||
* People, written as the styles list them: the first followed by ", et al." when there are four or more, and the
|
||||
* others' names "First Middle Last", or the main contributors' "Last, First Middle", or the organization (`formatPersons`)
|
||||
*/
|
||||
export const formatPersons = (names: WordNames, isMain: boolean): string => {
|
||||
if ("corporate" in names) {
|
||||
return names.corporate;
|
||||
}
|
||||
const people = names.people.length >= 4 ? names.people.slice(0, 1) : names.people;
|
||||
return people
|
||||
.map(
|
||||
(person: WordPerson, index) =>
|
||||
formatName(person, isMain ? ISO690.MainAuthors : ISO690.SecondaryAuthors) +
|
||||
formatPersonSeparator(index + 1, names.people.length),
|
||||
)
|
||||
.join("");
|
||||
};
|
||||
|
||||
/**
|
||||
* What the main contributors are, after their names, such as "ed.", by their role (`GetMainAuthorTitle`). The template
|
||||
* compares whether they're an organization, a string, with `true()`, which a string always is, so it doesn't depend on how
|
||||
* many of them there are
|
||||
*/
|
||||
const mainAuthorTitle = (source: PopulatedSource): string => {
|
||||
switch (source.mainRole) {
|
||||
case "Editor":
|
||||
return Strings.EditorShortUnCap;
|
||||
case "Translator":
|
||||
return Strings.TranslatorShortUnCap;
|
||||
case "Performer":
|
||||
return Strings.PerformerShortUnCap;
|
||||
case "Composer":
|
||||
return Strings.ComposerShortUnCapIso;
|
||||
case "Conductor":
|
||||
return Strings.ConductorShortUnCap;
|
||||
case "ProducerName":
|
||||
return Strings.ProducerShortUnCap;
|
||||
case "Writer":
|
||||
return source.type === "Film" ? Strings.WriterShortUnCap : "";
|
||||
case "Counsel":
|
||||
return Strings.CounselShortUnCap;
|
||||
case "Compiler":
|
||||
return Strings.CompilerShortUnCap;
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
/** The main contributors, and what they are, such as "Garcia, Lucia, [ed.]" (`formatMain`) */
|
||||
export const formatMain = (source: PopulatedSource): string => {
|
||||
if ("people" in source.main && source.main.people.length === 0) {
|
||||
return "";
|
||||
}
|
||||
const title = mainAuthorTitle(source);
|
||||
return formatPersons(source.main, true) + (title ? General.ListSeparator + ISO690.GeneralOpen + title + ISO690.GeneralClose : "");
|
||||
};
|
||||
|
||||
/**
|
||||
* The people with a role who aren't the main contributors, after what they are, such as "[ed.] Ernest Hemingway. ",
|
||||
* as the variables of the bibliography's templates write them (such as `Editors` with `formatEditor`). They're written
|
||||
* when the source has the role and its people aren't its main contributors
|
||||
*/
|
||||
export const formatRole = (source: PopulatedSource, role: Role, label: string, labelledBy: Role = role): string => {
|
||||
const names = source.names(role);
|
||||
// `b:Author/b:Main != b:Author/b:Editor` compares the string values of the elements, and is false without editors
|
||||
if (names === undefined || stringOfNames(source.main) === stringOfNames(names)) {
|
||||
return "";
|
||||
}
|
||||
// formatInterviewer tests whether there are people interviewed, rather than interviewers
|
||||
if (stringOfNames(source.names(labelledBy)) === "") {
|
||||
return General.Space;
|
||||
}
|
||||
const people = formatPersons(names, false);
|
||||
return ISO690.GeneralOpen + label + ISO690.GeneralClose + General.Space + people + needDot(people) + General.Space;
|
||||
};
|
||||
|
||||
/** Whether a string has text other than spaces, as `string-length(normalize-space($text)) > 0` */
|
||||
export const hasText = (text: string): boolean => /[^ \t\r\n]/.test(text);
|
||||
|
||||
/** The types of source written with their place of publication and publisher */
|
||||
const PUBLISHED: ReadonlySet<WordSourceType> = new Set([
|
||||
"Book",
|
||||
"BookSection",
|
||||
"JournalArticle",
|
||||
"ArticleInAPeriodical",
|
||||
"ConferenceProceedings",
|
||||
"Report",
|
||||
"SoundRecording",
|
||||
"Performance",
|
||||
"Art",
|
||||
"Interview",
|
||||
"ElectronicSource",
|
||||
"Case",
|
||||
"Misc",
|
||||
]);
|
||||
|
||||
/** The types of source whose publisher, or broadcaster, follows their place */
|
||||
const BY_PUBLISHER: ReadonlySet<WordSourceType> = new Set([
|
||||
"Book",
|
||||
"BookSection",
|
||||
"JournalArticle",
|
||||
"ArticleInAPeriodical",
|
||||
"ConferenceProceedings",
|
||||
"Interview",
|
||||
"Report",
|
||||
"Misc",
|
||||
]);
|
||||
|
||||
/** The publisher of a source, or who produced it, after its place: "s.n." when it has none (`after` of `formatLocation`) */
|
||||
const publisherOf = (source: PopulatedSource): string => {
|
||||
const { type, field } = source;
|
||||
if (field("Publisher") && type === "Report") {
|
||||
return field("Publisher");
|
||||
}
|
||||
if (field("ProductionCompany") && (type === "SoundRecording" || type === "Performance")) {
|
||||
return field("ProductionCompany");
|
||||
}
|
||||
if ((field("ProductionCompany") || field("Publisher")) && type === "ElectronicSource") {
|
||||
return (
|
||||
field("Publisher") +
|
||||
(field("Publisher") && field("ProductionCompany") ? General.ListSeparator : "") +
|
||||
field("ProductionCompany")
|
||||
);
|
||||
}
|
||||
if (field("Court") && type === "Case") {
|
||||
return field("Court");
|
||||
}
|
||||
if (type === "Art" && (field("Publisher") || field("Year"))) {
|
||||
return field("Publisher") + (field("Publisher") && field("Year") ? General.ListSeparator : "") + field("Year");
|
||||
}
|
||||
if ((field("Publisher") || (field("Broadcaster") && type === "Interview")) && BY_PUBLISHER.has(type)) {
|
||||
return (type === "Interview" ? field("Broadcaster") : "") + field("Publisher");
|
||||
}
|
||||
return !field("Broadcaster") && type === "Interview" ? "" : Strings.SineNomineShort;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a source with no place has nothing to write in its place either: none of the publisher, the institution, the
|
||||
* production company or the court its type is written with (`nothing` of `formatLocation`)
|
||||
*/
|
||||
const hasNoPublisher = (source: PopulatedSource): boolean => {
|
||||
const { type, field } = source;
|
||||
return !(
|
||||
(field("Publisher") && type === "Report") ||
|
||||
(field("Institution") && type === "Art") ||
|
||||
(field("ProductionCompany") && (type === "SoundRecording" || type === "Performance")) ||
|
||||
((field("ProductionCompany") || field("Publisher")) && type === "ElectronicSource") ||
|
||||
(field("Court") && type === "Case") ||
|
||||
((field("Publisher") || (field("Broadcaster") && type === "Interview")) && (BY_PUBLISHER.has(type) || type === "Art"))
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Where a source was published, and by whom, such as "Chicago : Adventure Works Press", "s.l." and "s.n." when it has
|
||||
* no place or publisher, or for a film, its production company and distributor (`formatLocation`)
|
||||
*/
|
||||
export const formatLocation = (source: PopulatedSource): string => {
|
||||
const { type, field } = source;
|
||||
if (type === "Film") {
|
||||
return (
|
||||
field("ProductionCompany") +
|
||||
(field("ProductionCompany") && field("Distributor") ? General.GroupSeparator : "") +
|
||||
field("Distributor")
|
||||
);
|
||||
}
|
||||
if (type === "Patent") {
|
||||
return field("CountryRegion");
|
||||
}
|
||||
if (!PUBLISHED.has(type)) {
|
||||
return "";
|
||||
}
|
||||
const hasPlace = !!field("City") || (!!field("Theater") && type === "Performance");
|
||||
if (!hasPlace && hasNoPublisher(source)) {
|
||||
return "";
|
||||
}
|
||||
const separated = (first: string): string => first + (first && field("City") ? General.ListSeparator + General.Space : "");
|
||||
const place = hasPlace
|
||||
? (type === "Performance" ? separated(field("Theater")) : "") +
|
||||
(type === "ElectronicSource" ? separated(field("Edition")) : "") +
|
||||
(type === "Interview" ? separated(field("Station")) : "") +
|
||||
(type === "Art" && field("Institution") && field("City") ? General.ListSeparator : "") +
|
||||
field("City")
|
||||
: (type === "Art" && field("Institution") ? General.ListSeparator : "") + Strings.SineLocoShort;
|
||||
const state = field("StateProvince");
|
||||
const country = field("CountryRegion");
|
||||
const region =
|
||||
type === "Performance" || type === "Art" || type === "ElectronicSource" || type === "Case" || type === "Misc"
|
||||
? (state || country ? General.ListSeparator : "") + state + (state && country ? General.ListSeparator : "") + country
|
||||
: "";
|
||||
const publisher = publisherOf(source);
|
||||
return (
|
||||
(type === "Art" ? field("Institution") : "") +
|
||||
place +
|
||||
region +
|
||||
(hasText(publisher) ? General.NonBreakingSpace + General.EnumSeparator + publisher : "")
|
||||
);
|
||||
};
|
||||
|
||||
/** The date a source was published, such as "14 March 2018" (`formatDayMonthYear`) */
|
||||
export const formatDayMonthYear = (source: PopulatedSource): string =>
|
||||
formatDatePrivate(source.field("Day"), source.field("Month"), source.field("Year"), ISO690.Date);
|
||||
|
||||
/**
|
||||
* The date a website was read, such as "[Cited: 3 February 2022.]". The template tests for the day it was read three
|
||||
* times, so it is written only when it has the day (`formatDayMonthYearAccessed`)
|
||||
*/
|
||||
export const formatDayMonthYearAccessed = (source: PopulatedSource): string => {
|
||||
if (!source.field("DayAccessed")) {
|
||||
return "";
|
||||
}
|
||||
const date = formatDatePrivate(
|
||||
source.field("DayAccessed"),
|
||||
source.field("MonthAccessed"),
|
||||
source.field("YearAccessed"),
|
||||
ISO690.DateAccessed,
|
||||
);
|
||||
return ISO690.GeneralOpen + textOf(stringFormatDot(Strings.CitedCap, date)) + ISO690.GeneralClose;
|
||||
};
|
||||
|
||||
/** The first, second and third that it has, with ", " between them, and a dot after them (`templateJ` and `templateC`) */
|
||||
const joinWithDot = (...parts: readonly string[]): string => appendDot(parts.filter((part) => part).join(General.ListSeparator));
|
||||
|
||||
/** "vol." or "vols.", for a volume such as "2" or "2-3", or "Vol." and "Vols." in a bibliography */
|
||||
export const volumeFormatOf = (volume: string, single: string, several: string): string =>
|
||||
volume.includes(",") || translate(volume, General.Hyphens, "") !== volume ? several : single;
|
||||
|
||||
/** Pages such as "p. 50" or "pp. 50-62", the way the styles write them in a bibliography and in a citation */
|
||||
export const pagesOf = (pages: string): string =>
|
||||
pages
|
||||
? (pages.includes(",") || translate(pages, General.Hyphens, "") !== pages ? Strings.PagesCountinousShort : Strings.PageShort) +
|
||||
General.Space +
|
||||
pages
|
||||
: "";
|
||||
|
||||
/** A source's entry in a bibliography after its title, its main contributors and the year: what each type has */
|
||||
type Entry = {
|
||||
/** What starts the entry, before the main contributors: a journal article's or a paper's title, in italics */
|
||||
readonly start: readonly HtmlNode[];
|
||||
/** What follows the main contributors, by the type of source */
|
||||
readonly rest: readonly HtmlNode[];
|
||||
};
|
||||
|
||||
/**
|
||||
* A source's entry in the bibliography, without its main contributors (the `xsl:choose` by `b:SourceType`, and the
|
||||
* bibliography's variables). The title of a journal article or a paper is "—." when it is the same as the one before's.
|
||||
* GB7714 writes a space after a website's version and date, or a report's department and institution, by different
|
||||
* fields than ISO 690
|
||||
*/
|
||||
export const entryOf = (source: PopulatedSource, previous: PopulatedSource | undefined, style: Iso690Family): Entry => {
|
||||
const { type, field } = source;
|
||||
const italicWithDot = (text: string): readonly HtmlNode[] => (text ? [applyItalic(appendDot(text) + General.Space)] : []);
|
||||
const spaced = (text: string): string => (text ? General.Space + text + General.Dot : "");
|
||||
|
||||
const title = italicWithDot(field("Title"));
|
||||
const titleOfMonographParts = field("Title") ? appendDot(field("Title")) + General.Space : "";
|
||||
const volume = field("Volume")
|
||||
? textOf(stringFormat(volumeFormatOf(field("Volume"), Strings.VolumeShortCap, Strings.VolumesShortCap), field("Volume")))
|
||||
: "";
|
||||
const pages = pagesOf(field("Pages"));
|
||||
const dayMonthYear = formatDayMonthYear(source);
|
||||
const location = formatLocation(source);
|
||||
const comments = spaced(field("Comments"));
|
||||
const standardNumber = spaced(field("StandardNumber"));
|
||||
const editors = formatRole(source, "Editor", Strings.EditorShortUnCap);
|
||||
const translators = formatRole(source, "Translator", Strings.TranslatorShortUnCap);
|
||||
const performers = formatRole(source, "Performer", Strings.PerformerShortUnCap);
|
||||
const producers = formatRole(source, "ProducerName", Strings.ProducerShortUnCap);
|
||||
const compilers = formatRole(source, "Compiler", Strings.CompilerShortUnCapIso);
|
||||
const medium = field("Medium") ? ISO690.GeneralOpen + field("Medium") + ISO690.GeneralClose : "";
|
||||
const mediumDot = medium ? medium + General.Dot + General.Space : "";
|
||||
const list = (...items: readonly string[]): string => textOf(printList(items));
|
||||
const spaceAndList = (...items: readonly string[]): readonly HtmlNode[] => {
|
||||
const result = list(...items);
|
||||
return result ? [General.Space, copy(result)] : [];
|
||||
};
|
||||
const websiteTitle = [
|
||||
...italicWithDot(field("InternetSiteTitle")),
|
||||
ISO690.GeneralOpen + Strings.OnlineCap + ISO690.GeneralClose + General.Space,
|
||||
];
|
||||
const website = [
|
||||
joinWithDot(field("Version"), type === "InternetSite" ? field("ProductionCompany") : "", dayMonthYear) +
|
||||
(field("Version") || dayMonthYear || (style === "ISO 690" && field("ProductionCompany")) ? General.Space : ""),
|
||||
formatDayMonthYearAccessed(source),
|
||||
comments,
|
||||
spaced(field("URL")),
|
||||
standardNumber,
|
||||
];
|
||||
|
||||
const start =
|
||||
type === "ConferenceProceedings" || type === "JournalArticle"
|
||||
? [
|
||||
applyItalic(
|
||||
previous &&
|
||||
(previous.type === "JournalArticle" || previous.type === "ConferenceProceedings") &&
|
||||
previous.field("Title") !== "" &&
|
||||
previous.field("Title") === field("Title")
|
||||
? ISO690.SameAuthor + General.Dot
|
||||
: copy(titleOfMonographParts),
|
||||
),
|
||||
]
|
||||
: [];
|
||||
|
||||
const rest = ((): readonly HtmlNode[] => {
|
||||
switch (type) {
|
||||
case "Book":
|
||||
return [
|
||||
copy(...title),
|
||||
editors,
|
||||
translators,
|
||||
field("Edition") ? appendDot(field("Edition")) + General.Space : "",
|
||||
list(location, field("Year")),
|
||||
pages ? General.Space + appendDot(pages) : "",
|
||||
...spaceAndList(volume, comments),
|
||||
standardNumber,
|
||||
];
|
||||
case "BookSection":
|
||||
return [
|
||||
copy(titleOfMonographParts),
|
||||
formatRole(source, "BookAuthor", Strings.BookAuthorShortUnCap),
|
||||
editors,
|
||||
translators,
|
||||
copy(...italicWithDot(field("BookTitle"))),
|
||||
field("Edition") ? appendDot(field("Edition")) + General.Space : "",
|
||||
// The chapter number, between the volume and the pages, is a field Word's sources don't have
|
||||
list(location, field("Year"), volume, pages),
|
||||
comments,
|
||||
];
|
||||
case "JournalArticle":
|
||||
return [
|
||||
editors,
|
||||
field("Issue") ? field("Issue") + General.ListSeparator : "",
|
||||
list(location, dayMonthYear, field("JournalName"), volume, pages),
|
||||
comments,
|
||||
standardNumber,
|
||||
];
|
||||
case "ArticleInAPeriodical":
|
||||
return [
|
||||
copy(titleOfMonographParts),
|
||||
editors,
|
||||
copy(...italicWithDot(field("PeriodicalTitle"))),
|
||||
list(field("Edition"), dayMonthYear, volume, field("Issue"), pages),
|
||||
comments,
|
||||
];
|
||||
case "ConferenceProceedings":
|
||||
return [
|
||||
editors,
|
||||
list(location, field("Year")),
|
||||
copy(field("ConferenceName") ? General.Space + appendDot(field("ConferenceName")) : ""),
|
||||
...spaceAndList(volume, pages),
|
||||
comments,
|
||||
standardNumber,
|
||||
];
|
||||
case "Report":
|
||||
return [
|
||||
copy(...title),
|
||||
joinWithDot(field("Department"), field("Institution")) +
|
||||
(field("Department") || field("Institution") || (style === "GB7714" && field("ProductionCompany"))
|
||||
? General.Space
|
||||
: ""),
|
||||
list(location, field("Year")),
|
||||
...spaceAndList(pages, field("ThesisType")),
|
||||
comments,
|
||||
standardNumber,
|
||||
];
|
||||
case "SoundRecording":
|
||||
return [
|
||||
copy(titleOfMonographParts),
|
||||
performers,
|
||||
formatRole(source, "Composer", Strings.ComposerShortUnCapIso),
|
||||
formatRole(source, "Conductor", Strings.ConductorShortUnCap),
|
||||
producers,
|
||||
copy(...italicWithDot(field("AlbumTitle"))),
|
||||
copy(medium ? medium + General.Space : ""),
|
||||
list(location, field("Year")),
|
||||
comments,
|
||||
standardNumber,
|
||||
];
|
||||
case "Performance":
|
||||
return [
|
||||
copy(...title),
|
||||
formatRole(source, "Director", Strings.DirectorShortUnCap),
|
||||
performers,
|
||||
producers,
|
||||
list(location, dayMonthYear),
|
||||
comments,
|
||||
standardNumber,
|
||||
];
|
||||
case "Art":
|
||||
return [copy(...title), list(location), comments];
|
||||
case "DocumentFromInternetSite":
|
||||
return [copy(titleOfMonographParts), copy(...websiteTitle), ...website];
|
||||
case "InternetSite":
|
||||
return [textOfHtml(title), copy(...websiteTitle), ...website];
|
||||
case "Film":
|
||||
return [
|
||||
copy(...title),
|
||||
mediumDot,
|
||||
formatRole(source, "Writer", Strings.WriterShortUnCap),
|
||||
performers,
|
||||
producers,
|
||||
list(location, field("Year")),
|
||||
comments,
|
||||
standardNumber,
|
||||
];
|
||||
case "Interview": {
|
||||
const broadcastTitle = field("BroadcastTitle") ? appendDot(field("BroadcastTitle")) + General.Space : "";
|
||||
return [
|
||||
!field("Broadcaster") && !field("BroadcastTitle") ? applyItalic({ value: textOfHtml(title) }) : textOfHtml(title),
|
||||
formatRole(source, "Interviewer", Strings.IntervieweeShortUnCap, "Interviewee"),
|
||||
editors,
|
||||
translators,
|
||||
compilers,
|
||||
broadcastTitle ? applyItalic({ value: broadcastTitle }) : "",
|
||||
list(location, dayMonthYear),
|
||||
...spaceAndList(pages),
|
||||
comments,
|
||||
standardNumber,
|
||||
];
|
||||
}
|
||||
case "Patent":
|
||||
return [
|
||||
copy(...title),
|
||||
copy(...(field("PatentNumber") ? [applyItalic(field("PatentNumber") + General.Space)] : [])),
|
||||
editors,
|
||||
translators,
|
||||
list(location, dayMonthYear),
|
||||
field("Type") ? General.Space + appendDot(field("Type")) : "",
|
||||
comments,
|
||||
];
|
||||
case "ElectronicSource":
|
||||
return [
|
||||
copy(...title),
|
||||
copy(medium ? medium + General.Space : ""),
|
||||
editors,
|
||||
producers,
|
||||
translators,
|
||||
list(location, dayMonthYear),
|
||||
...spaceAndList(field("PublicationTitle"), volume ? General.Space + appendDot(volume) : ""),
|
||||
comments,
|
||||
standardNumber,
|
||||
];
|
||||
case "Case":
|
||||
return [
|
||||
copy(...title),
|
||||
copy(field("CaseNumber") ? field("CaseNumber") + General.ListSeparator : ""),
|
||||
copy(field("AbbreviatedCaseNumber") ? field("AbbreviatedCaseNumber") + General.Dot + General.Space : ""),
|
||||
formatRole(source, "Counsel", Strings.CounselShortUnCap),
|
||||
list(location, dayMonthYear),
|
||||
spaced(field("Reporter")),
|
||||
comments,
|
||||
];
|
||||
default:
|
||||
return [
|
||||
copy(titleOfMonographParts),
|
||||
field("Edition"),
|
||||
General.Space,
|
||||
editors,
|
||||
compilers,
|
||||
translators,
|
||||
applyItalic({ value: textOfHtml(italicWithDot(field("PublicationTitle"))) }),
|
||||
mediumDot,
|
||||
list(location, dayMonthYear),
|
||||
...spaceAndList(volume, field("Issue"), pages),
|
||||
comments,
|
||||
standardNumber,
|
||||
];
|
||||
}
|
||||
})();
|
||||
|
||||
return { start, rest };
|
||||
};
|
||||
|
||||
/** Whether a source is a journal article or a paper, which these styles start with its title */
|
||||
export const startsWithTitle = (source: PopulatedSource | undefined): boolean =>
|
||||
source?.type === "JournalArticle" || source?.type === "ConferenceProceedings";
|
||||
|
||||
/** Whether the source before has the same main contributors, as the string values of their elements */
|
||||
export const hasSameMain = (source: PopulatedSource, previous: PopulatedSource | undefined): boolean =>
|
||||
previous !== undefined && stringOfNames(previous.main) === stringOfNames(source.main);
|
||||
|
||||
/**
|
||||
* A citation's volume and pages, such as "vol. 2", "p. 50" or "2:50", after a space when the citation has something
|
||||
* before them
|
||||
*
|
||||
* @param separator - Between a volume and pages: ":" for ISO 690 by first element and date, ": " for its numerical style
|
||||
*/
|
||||
export const citedVolumeAndPages = (volume: string, pages: string, separator: string, spaced: boolean): string => {
|
||||
if (!volume && !pages) {
|
||||
return "";
|
||||
}
|
||||
const cited =
|
||||
volume && pages
|
||||
? volume + separator + pages
|
||||
: volume
|
||||
? textOf(stringFormat(volumeFormatOf(volume, Strings.VolumeShortUnCap, Strings.VolumesShortUnCap), volume))
|
||||
: pagesOf(pages);
|
||||
return (spaced ? General.Space : "") + cited;
|
||||
};
|
||||
|
||||
/** The patterns GB7714 writes the first of a citation's people with: Word's simple patterns, the last name */
|
||||
const GB7714_CITATION = { FML: General.SimpleAuthor.L, FM: General.SimpleAuthor.F, ML: General.SimpleAuthor.L, FL: General.SimpleAuthor.L };
|
||||
|
||||
/**
|
||||
* What a source is sorted by in the bibliography (`b:SortingString` of `populateMain`): a journal article's or a paper's
|
||||
* title, then its main contributors, then any other source's title
|
||||
*/
|
||||
const sortingStringOf = (source: PopulatedSource): string => {
|
||||
const title = source.field("Title");
|
||||
const author = formatPersons(source.main, true);
|
||||
return (
|
||||
(startsWithTitle(source) && title ? General.Space + title : "") +
|
||||
(author ? General.Space + author : "") +
|
||||
(title && !startsWithTitle(source) ? General.Space + title : "")
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* A source of a citation, as ISO 690 by first element and date, and GB7714, write it: the main contributors, or for
|
||||
* a journal article or a paper its title, then the year, such as "(Baker, 2010 p. 50)". A source with no contributors,
|
||||
* title or year is cited by its tag, and in GB7714 one with no contributors or year (the template's `b:Citation`)
|
||||
*/
|
||||
export const firstElementCitation =
|
||||
(style: Iso690Family): ((cited: CitedSource) => FormattedText) =>
|
||||
(cited: CitedSource): FormattedText => {
|
||||
const source = populate(cited.source);
|
||||
const { field, main } = source;
|
||||
const title = field("ShortTitle") || field("Title");
|
||||
const year = field("Year");
|
||||
const people = "people" in main ? main.people : [];
|
||||
const author =
|
||||
startsWithTitle(source) && field("Title")
|
||||
? field("Title")
|
||||
: "corporate" in main
|
||||
? main.corporate
|
||||
: // NoCommaBeforeAnd is "no"
|
||||
(people.length > 0 ? formatName(people[0], style === "GB7714" ? GB7714_CITATION : ISO690.CitationShort) : "") +
|
||||
(people.length > 1 ? General.AuthorsSeparator + Strings.AndOthersUnCap : "");
|
||||
const shownAuthor = cited.hideAuthor ? "" : author;
|
||||
const shownYear = cited.hideYear ? "" : year;
|
||||
return [
|
||||
{
|
||||
text:
|
||||
(cited.first ? General.OpenBracket : "") +
|
||||
(cited.prefix ?? "") +
|
||||
shownAuthor +
|
||||
(shownYear ? (shownAuthor ? General.ListSeparator : "") + shownYear : "") +
|
||||
(!author && (style === "GB7714" || !title) && !year ? cited.source.tag : "") +
|
||||
citedVolumeAndPages(cited.volume, cited.pages, General.Enum, !!shownAuthor || !!shownYear) +
|
||||
(cited.suffix ?? "") +
|
||||
(cited.last ? General.CloseBracket : General.GroupSeparator),
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
/**
|
||||
* The bibliography as ISO 690 by first element and date, and GB7714, write it: sorted by its sources' main
|
||||
* contributors, each with the year after them in bold, such as "**Baker, Anna. 2010.** _The Art of Pizza._", or "—."
|
||||
* for the same contributors as the source before (the template's `b:Bibliography`)
|
||||
*/
|
||||
export const firstElementBibliography =
|
||||
(style: Iso690Family): ((sources: readonly WordSource[]) => FormattedBibliography) =>
|
||||
(sources: readonly WordSource[]): FormattedBibliography => {
|
||||
const sorted = sortByKey(sources.map(populate), sortingStringOf);
|
||||
const paragraphs = sorted.map((source, index): readonly HtmlNode[] => {
|
||||
const previous = sorted[index - 1];
|
||||
const main = formatMain(source);
|
||||
const { start, rest } = entryOf(source, previous, style);
|
||||
const year = source.field("Year");
|
||||
const named =
|
||||
startsWithTitle(previous) || startsWithTitle(source) || !hasSameMain(source, previous)
|
||||
? [copy(main), needDot(main)]
|
||||
: [stringOfNames(source.main) ? ISO690.SameAuthor + General.Dot : ""];
|
||||
return [...start, element("b", ...named, year ? General.Space + year + General.Dot : ""), General.Space, ...rest];
|
||||
});
|
||||
return { paragraphs: readHtml(paragraphs), hangingIndent: false };
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { describeWordOutput } from "tests/bibliography";
|
||||
|
||||
import expected from "./fixtures/iso-690-first-element-and-date.json";
|
||||
import { iso690FirstElementAndDate } from "./iso-690-first-element-and-date";
|
||||
|
||||
describe("iso690FirstElementAndDate", () => {
|
||||
it("is Word's ISO 690 by first element and date", () => {
|
||||
expect(iso690FirstElementAndDate).toMatchObject({ name: "ISO 690 - First Element and Date", file: "ISO690.XSL", version: "1987" });
|
||||
});
|
||||
|
||||
describeWordOutput(iso690FirstElementAndDate, expected);
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* The ISO 690 style of citation by first element and date, written from Word's (ISO690.XSL): citations such as
|
||||
* "(Baker, 2010)", and a bibliography sorted by its sources' authors, with the year after them.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { firstElementBibliography, firstElementCitation } from "./iso-690-family";
|
||||
import type { StyleDefinition } from "./style";
|
||||
|
||||
/** ISO 690 by first element and date, as Word writes it */
|
||||
export const iso690FirstElementAndDate: StyleDefinition = {
|
||||
name: "ISO 690 - First Element and Date",
|
||||
file: "ISO690.XSL",
|
||||
version: "1987",
|
||||
citation: firstElementCitation("ISO 690"),
|
||||
bibliography: firstElementBibliography("ISO 690"),
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
// cspell:words Nmerical
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { describeWordOutput, outputOf } from "tests/bibliography";
|
||||
|
||||
import expected from "./fixtures/iso-690-numerical-reference.json";
|
||||
import { iso690NumericalReference } from "./iso-690-numerical-reference";
|
||||
|
||||
// Sources none of the corpora have: listed by a conductor, a producer and a compiler, and a work of art with a publisher
|
||||
// but no place. What the style writes for them is what Word's own style writes when it's run with libxslt, but for the
|
||||
// compiler's notes, a miscellaneous source with no publication: libxslt reads its empty <i> as one that leaves italics
|
||||
// on for the rest of the bibliography, which Word doesn't, as its own bibliography of corpus b's "A Flyer" shows
|
||||
const corpus = {
|
||||
sources: [
|
||||
{ tag: "Conductor", type: "soundRecording", conductors: [{ lastName: "Cond", firstName: "Flo" }], title: "Song", year: "2001" },
|
||||
{ tag: "Producer", type: "film", producers: [{ lastName: "Prod", firstName: "Olga" }], title: "Movie", year: "2002" },
|
||||
{ tag: "Compiler", type: "miscellaneous", compilers: [{ lastName: "Comp", firstName: "Di" }], title: "Notes", year: "2003" },
|
||||
{ tag: "Painting", type: "art", title: "Painting", year: "2004", publisher: "Museum Press" },
|
||||
],
|
||||
citations: [
|
||||
[{ source: "Conductor", pages: "5", hideAuthor: true, hideYear: true }],
|
||||
[{ source: "Painting", volume: "2", hideAuthor: true, hideYear: true }],
|
||||
[{ source: "Compiler" }],
|
||||
],
|
||||
} as const;
|
||||
|
||||
describe("iso690NumericalReference", () => {
|
||||
it("is Word's ISO 690 by numerical reference", () => {
|
||||
expect(iso690NumericalReference).toMatchObject({
|
||||
name: "ISO 690 - Numerical Reference",
|
||||
file: "ISO690Nmerical.XSL",
|
||||
version: "1987",
|
||||
});
|
||||
});
|
||||
|
||||
describeWordOutput(iso690NumericalReference, expected);
|
||||
|
||||
it("cites a source by its number, with the pages or volume cited after it", () => {
|
||||
expect(outputOf(iso690NumericalReference, corpus).citations).toEqual(["(1 p. 5)", "(2 vol. 2)", "(3)"]);
|
||||
});
|
||||
|
||||
it("leaves the rest of the bibliography bold after an entry whose bold has nothing in it", () => {
|
||||
expect(outputOf(iso690NumericalReference, corpus).bibliography).toEqual({
|
||||
hangingIndent: false,
|
||||
paragraphs: [
|
||||
"1. <b>Cond, Flo, [cond.].</b> Song. 2001.",
|
||||
"2. <b><i>Painting. </i></b><b>s.l. : Museum Press, 2004.</b>",
|
||||
"<b>3. Comp, Di, [comp.]. Notes. 2003.</b>",
|
||||
"<b>4. Prod, Olga, [prod.]. </b><b><i>Movie. </i></b><b>2002.</b>",
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* The ISO 690 style of citation by numerical reference, written from Word's (ISO690Nmerical.XSL): citations by the
|
||||
* number of the source, in the order the document cites them, such as "(1)" or "(1 p. 50)", and a bibliography in that
|
||||
* order, each source after its number.
|
||||
*
|
||||
* Word reads this style's HTML with a quirk that the others don't show: after an entry whose bold holds nothing, such as
|
||||
* one with no author, the rest of the bibliography is bold.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
// cspell:words Nmerical
|
||||
import { type FormattedText } from "./formatted-text";
|
||||
import {
|
||||
type HtmlNode,
|
||||
type PopulatedSource,
|
||||
citedVolumeAndPages,
|
||||
copy,
|
||||
element,
|
||||
entryOf,
|
||||
formatMain,
|
||||
hasSameMain,
|
||||
hasText,
|
||||
populate,
|
||||
readHtml,
|
||||
startsWithTitle,
|
||||
stringOfNames,
|
||||
textOfHtml,
|
||||
} from "./iso-690-family";
|
||||
import { LOCALS } from "./locals";
|
||||
import type { CitedSource, FormattedBibliography, StyleDefinition } from "./style";
|
||||
import { xslTemplates } from "./xsl";
|
||||
import type { WordSource } from "../word-source";
|
||||
|
||||
const { General, ISO690 } = LOCALS;
|
||||
const { appendDot, needDot } = xslTemplates(General);
|
||||
|
||||
/** A source of a citation: its number, then the volume or pages cited, such as "(1 p. 50)" or "(1 2: 50)" (the template's `b:Citation`) */
|
||||
const citation = (cited: CitedSource): FormattedText => [
|
||||
{
|
||||
text:
|
||||
(cited.first ? General.OpenBracket : "") +
|
||||
(cited.prefix ?? "") +
|
||||
String(cited.source.order) +
|
||||
citedVolumeAndPages(cited.volume, cited.pages, General.EnumSeparator, true) +
|
||||
(cited.suffix ?? "") +
|
||||
(cited.last ? General.CloseBracket : General.GroupSeparator),
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* A source's entry, without its number (`BibReference`): the main contributors in bold, such as "**Baker, Anna.**", or
|
||||
* "—." when they're the same as the source before's, then the rest of the entry
|
||||
*/
|
||||
const referenceOf = (source: PopulatedSource, previous: PopulatedSource | undefined): readonly HtmlNode[] => {
|
||||
const main = formatMain(source);
|
||||
const { start, rest } = entryOf(source, previous, "ISO 690");
|
||||
const named =
|
||||
startsWithTitle(previous) || startsWithTitle(source)
|
||||
? [element("b", copy(main), needDot(main)), General.Space]
|
||||
: hasSameMain(source, previous)
|
||||
? [stringOfNames(source.main) ? ISO690.SameAuthor + General.Dot + General.Space : ""]
|
||||
: [element("b", copy(appendDot(main))), General.Space];
|
||||
return [...start, ...named, ...rest];
|
||||
};
|
||||
|
||||
/**
|
||||
* The bibliography, in the order the document cites its sources, each entry after its number, such as "1. ", or empty
|
||||
* when it has nothing (the template's `b:Bibliography`)
|
||||
*/
|
||||
const bibliography = (sources: readonly WordSource[]): FormattedBibliography => {
|
||||
const sorted = [...sources].sort((a, b) => a.order - b.order).map(populate);
|
||||
const paragraphs = sorted.map((source, index): readonly HtmlNode[] => {
|
||||
const reference = referenceOf(source, sorted[index - 1]);
|
||||
return hasText(textOfHtml(reference)) ? [String(source.source.order) + General.Dot + General.Space, copy(...reference)] : [];
|
||||
});
|
||||
return { paragraphs: readHtml(paragraphs), hangingIndent: false };
|
||||
};
|
||||
|
||||
/** ISO 690 by numerical reference, as Word writes it */
|
||||
export const iso690NumericalReference: StyleDefinition = {
|
||||
name: "ISO 690 - Numerical Reference",
|
||||
file: "ISO690Nmerical.XSL",
|
||||
version: "1987",
|
||||
citation,
|
||||
bibliography,
|
||||
};
|
||||
@@ -0,0 +1,436 @@
|
||||
/**
|
||||
* The English wording Word gives its styles of citation: the punctuation, the words such as "Retrieved from", and the
|
||||
* patterns of names and dates, such as "%L, %f %m" for "Dickens, C. J.". Word passes these to each style in its input
|
||||
* (`b:Locals`), for the language of the citation, so they aren't in the styles themselves.
|
||||
*
|
||||
* They were read from what Word for Mac (16.114) writes, by running Word's styles with them and comparing the result with
|
||||
* Word's own, for sources of every type. Where Word's output didn't show one, it is the likeliest wording from its name
|
||||
* and from where the styles use it. Some are empty in Word, such as `EditorsShortUnCap`, so Chicago writes a list of
|
||||
* editors with no "eds." after it, as Word does.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
// cspell:ignore Countinous counsl compl interv perfs conds
|
||||
|
||||
/** A pattern of a person's name for each of the names they have: first, middle and last, first and middle, and so on */
|
||||
export type NamePatterns = { readonly FML: string; readonly FM: string; readonly ML: string; readonly FL: string };
|
||||
|
||||
/** A pattern of a date for each of the parts it has: day, month and year, day and month, and so on */
|
||||
export type DatePatterns = { readonly DMY: string; readonly DM: string; readonly MY: string; readonly DY: string };
|
||||
|
||||
/** The wording, by its path in Word's input to a style, such as `LOCALS.Strings.EditorShortCap` for `b:Strings/b:EditorShortCap` */
|
||||
export const LOCALS = {
|
||||
Properties: {
|
||||
Direction: "ltr",
|
||||
},
|
||||
General: {
|
||||
AuthorsSeparator: ", ",
|
||||
CloseBracket: ")",
|
||||
CloseLink: ">",
|
||||
CloseQuote: "\u201d",
|
||||
Dot: ".",
|
||||
DotInitial: ".",
|
||||
EndChars: ".!?",
|
||||
Enum: ":",
|
||||
EnumSeparator: ": ",
|
||||
Equal: "=",
|
||||
FromToDash: "-",
|
||||
GroupSeparator: "; ",
|
||||
Hyphens: "-\u2013\u2014",
|
||||
ListSeparator: ", ",
|
||||
NoAndBeforeLastAuthor: "no",
|
||||
NoCommaBeforeAnd: "no",
|
||||
NoItalics: "no",
|
||||
NonBreakingSpace: "\u00a0",
|
||||
OpenBracket: "(",
|
||||
OpenLink: "<",
|
||||
OpenQuote: "\u201c",
|
||||
SimpleAuthor: {
|
||||
F: "%F",
|
||||
L: "%L",
|
||||
M: "%M",
|
||||
},
|
||||
SimpleDate: {
|
||||
D: "%D",
|
||||
M: "%M",
|
||||
Y: "%Y",
|
||||
},
|
||||
Space: " ",
|
||||
TitleClose: "",
|
||||
TitleOpen: "",
|
||||
},
|
||||
APA: {
|
||||
BeforeLastAuthor: "&",
|
||||
CitationLong: {
|
||||
FML: "%L %f %m",
|
||||
FM: "%f %m",
|
||||
ML: "%L %m",
|
||||
FL: "%L %f ",
|
||||
},
|
||||
CitationShort: {
|
||||
FML: "%L",
|
||||
FM: "%F",
|
||||
ML: "%L",
|
||||
FL: "%L",
|
||||
},
|
||||
Date: {
|
||||
DMY: "%Y, %M %D",
|
||||
DM: "%M %D",
|
||||
MY: "%Y, %M",
|
||||
DY: "%Y",
|
||||
},
|
||||
DateAccessed: {
|
||||
DMY: "%M %D, %Y",
|
||||
DM: "%M %D",
|
||||
MY: "%M %Y",
|
||||
DY: "%Y",
|
||||
},
|
||||
DateCourt: {
|
||||
DMY: "%M %D, %Y",
|
||||
DM: "%M %D",
|
||||
MY: "%M %Y",
|
||||
DY: "%Y",
|
||||
},
|
||||
GeneralClose: ")",
|
||||
GeneralOpen: "(",
|
||||
MainAuthors: {
|
||||
FML: "%L, %f %m",
|
||||
FM: "%f %m",
|
||||
ML: "%L, %m",
|
||||
FL: "%L, %f",
|
||||
},
|
||||
SecondaryAuthors: {
|
||||
FML: "%f %m %L",
|
||||
FM: "%f %m",
|
||||
ML: "%m %L",
|
||||
FL: "%f %L",
|
||||
},
|
||||
SecondaryClose: "]",
|
||||
SecondaryOpen: "[",
|
||||
},
|
||||
Chicago: {
|
||||
CitationLong: {
|
||||
FML: "%f %m %L",
|
||||
FM: "%f %m",
|
||||
ML: "%m %L",
|
||||
FL: "%f %L",
|
||||
},
|
||||
CitationShort: {
|
||||
FML: "%L",
|
||||
FM: "%F",
|
||||
ML: "%L",
|
||||
FL: "%L",
|
||||
},
|
||||
Date: {
|
||||
DMY: "%D %M %Y",
|
||||
DM: "%D %M",
|
||||
MY: "%M %Y",
|
||||
DY: "%Y",
|
||||
},
|
||||
MainAuthor: {
|
||||
FML: "%L, %F %M",
|
||||
FM: "%F %M",
|
||||
ML: "%L, %M",
|
||||
FL: "%L, %F",
|
||||
},
|
||||
OtherAuthors: {
|
||||
FML: "%F %M %L",
|
||||
FM: "%F %M",
|
||||
ML: "%M %L",
|
||||
FL: "%F %L",
|
||||
},
|
||||
SameAuthor: "\u2014",
|
||||
SecondaryAuthors: {
|
||||
FML: "%F %M %L",
|
||||
FM: "%F %M",
|
||||
ML: "%M %L",
|
||||
FL: "%F %L",
|
||||
},
|
||||
},
|
||||
MLA: {
|
||||
CitationLong: {
|
||||
FML: "%f %m %L",
|
||||
FM: "%f %m",
|
||||
ML: "%m %L",
|
||||
FL: "%f %L",
|
||||
},
|
||||
CitationShort: {
|
||||
FML: "%L",
|
||||
FM: "%F",
|
||||
ML: "%L",
|
||||
FL: "%L",
|
||||
},
|
||||
Date: {
|
||||
DMY: "%D %M %Y",
|
||||
DM: "%D %M",
|
||||
MY: "%M %Y",
|
||||
DY: "%Y",
|
||||
},
|
||||
MainAuthor: {
|
||||
FML: "%L, %F %M",
|
||||
FM: "%F %M",
|
||||
ML: "%L, %M",
|
||||
FL: "%L, %F",
|
||||
},
|
||||
OtherAuthors: {
|
||||
FML: "%F %M %L",
|
||||
FM: "%F %M",
|
||||
ML: "%M %L",
|
||||
FL: "%F %L",
|
||||
},
|
||||
SameAuthor: "\u2014",
|
||||
SecondaryAuthors: {
|
||||
FML: "%F %M %L",
|
||||
FM: "%F %M",
|
||||
ML: "%M %L",
|
||||
FL: "%F %L",
|
||||
},
|
||||
},
|
||||
Gost: {
|
||||
Authors: {
|
||||
FML: "%L %F %M",
|
||||
FM: "%F %M",
|
||||
ML: "%L %M",
|
||||
FL: "%L %F",
|
||||
},
|
||||
CitationLong: {
|
||||
FML: "%L %f. %m.",
|
||||
FM: "%f. %m.",
|
||||
ML: "%L %m.",
|
||||
FL: "%L %f.",
|
||||
},
|
||||
CitationShort: {
|
||||
FML: "%L",
|
||||
FM: "%F",
|
||||
ML: "%L",
|
||||
FL: "%L",
|
||||
},
|
||||
Date: {
|
||||
DMY: "%D %M %Y",
|
||||
DM: "%D %M",
|
||||
MY: "%M %Y",
|
||||
DY: "%Y",
|
||||
},
|
||||
GeneralClose: "]",
|
||||
GeneralOpen: "[",
|
||||
OneSlash: "/",
|
||||
TwoSlash: "//",
|
||||
},
|
||||
ISO690: {
|
||||
CitationLong: {
|
||||
FML: "%L, %f. %m.",
|
||||
FM: "%f. %m.",
|
||||
ML: "%L, %m.",
|
||||
FL: "%L, %f.",
|
||||
},
|
||||
CitationShort: {
|
||||
FML: "%L",
|
||||
FM: "%F",
|
||||
ML: "%L",
|
||||
FL: "%L",
|
||||
},
|
||||
Date: {
|
||||
DMY: "%D %M %Y",
|
||||
DM: "%D %M",
|
||||
MY: "%M %Y",
|
||||
DY: "%Y",
|
||||
},
|
||||
DateAccessed: {
|
||||
DMY: "%D %M %Y",
|
||||
DM: "%D %M",
|
||||
MY: "%M %Y",
|
||||
DY: "%Y",
|
||||
},
|
||||
GeneralClose: "]",
|
||||
GeneralOpen: "[",
|
||||
MainAuthors: {
|
||||
FML: "%L, %F %M",
|
||||
FM: "%F %M",
|
||||
ML: "%L, %M",
|
||||
FL: "%L, %F",
|
||||
},
|
||||
SameAuthor: "\u2014",
|
||||
SecondaryAuthors: {
|
||||
FML: "%F %M %L",
|
||||
FM: "%F %M",
|
||||
ML: "%M %L",
|
||||
FL: "%F %L",
|
||||
},
|
||||
},
|
||||
SIST: {
|
||||
Date: {
|
||||
DMY: "%D %M %Y",
|
||||
DM: "%D %M",
|
||||
MY: "%M %Y",
|
||||
DY: "%Y",
|
||||
},
|
||||
DateAccessed: {
|
||||
DMY: "%D %M %Y",
|
||||
DM: "%D %M",
|
||||
MY: "%M %Y",
|
||||
DY: "%Y",
|
||||
},
|
||||
GeneralClose: "]",
|
||||
GeneralOpen: "[",
|
||||
MainAuthors: {
|
||||
FML: "%L%F%M",
|
||||
FM: "%F%M",
|
||||
ML: "%L%M",
|
||||
FL: "%L%F",
|
||||
},
|
||||
SameAuthor: "\u2014",
|
||||
SecondaryAuthors: {
|
||||
FML: "%L%F%M",
|
||||
FM: "%F%M",
|
||||
ML: "%L%M",
|
||||
FL: "%L%F",
|
||||
},
|
||||
},
|
||||
SourceNames: {
|
||||
Book: "Book",
|
||||
BookSection: "Book Section",
|
||||
JournalArticle: "Journal",
|
||||
ArticleInAPeriodical: "Article",
|
||||
ConferenceProceedings: "Conference",
|
||||
Report: "Report",
|
||||
InternetSite: "Online",
|
||||
DocumentFromInternetSite: "Online",
|
||||
ElectronicSource: "Electronic Source",
|
||||
Art: "Art",
|
||||
SoundRecording: "Sound Recording",
|
||||
Performance: "Performance",
|
||||
Film: "Film",
|
||||
Interview: "Interview",
|
||||
Patent: "Patent",
|
||||
Case: "Case",
|
||||
Misc: "Misc",
|
||||
},
|
||||
Strings: {
|
||||
AccessedCap: "Accessed %1",
|
||||
AccessedUnCap: "accessed %1",
|
||||
AndOthersUnCap: "et al.",
|
||||
AndUnCap: "and",
|
||||
ArtistShortUnCap: "art.",
|
||||
AuthorShortUnCap: "auth.",
|
||||
BookAuthorShortUnCap: "book auth.",
|
||||
ByCap: "By %1",
|
||||
ByUnCap: "by %1",
|
||||
ChapterCap: "Chapter %1",
|
||||
ChapterInCap: "In %1",
|
||||
ChapterInUnCap: "in %1",
|
||||
ChapterUnCap: "chapter %1",
|
||||
CitedCap: "Cited: %1",
|
||||
CompiledByCap: "Compiled by %1",
|
||||
CompiledByUnCap: "compiled by %1",
|
||||
CompilerCap: "Compiler",
|
||||
CompilersCap: "Compilers",
|
||||
CompilerShortCap: "Comp.",
|
||||
CompilerShortUnCap: "comp.",
|
||||
CompilerShortUnCapIso: "compl.",
|
||||
CompilersShortCap: "Comps.",
|
||||
CompilersShortUnCap: "comps.",
|
||||
ComposerCap: "Composer",
|
||||
ComposersCap: "Composers",
|
||||
ComposerShortCap: "Comp.",
|
||||
ComposerShortUnCapIso: "comps.",
|
||||
ComposersShortCap: "Comps.",
|
||||
ConductedByCap: "Conducted by %1",
|
||||
ConductedByUnCap: "conducted by %1",
|
||||
ConductorCap: "Conductor",
|
||||
ConductorsCap: "Conductors",
|
||||
ConductorShortCap: "Cond.",
|
||||
ConductorShortUnCap: "cond.",
|
||||
ConductorsShortCap: "Conds.",
|
||||
ConductorsShortUnCap: "conds.",
|
||||
CounselShortUnCap: "counsl.",
|
||||
CounselShortUnCapIso: "counsl.",
|
||||
DirectedByCap: "Directed by %1",
|
||||
DirectedByUnCap: "directed by %1",
|
||||
DirectorCap: "Director",
|
||||
DirectorsCap: "Directors",
|
||||
DirectorShortCap: "Dir.",
|
||||
DirectorShortUnCap: "dir.",
|
||||
DirectorsShortCap: "Dirs.",
|
||||
DirectorsShortUnCap: "dirs.",
|
||||
EditedByCap: "Edited by %1",
|
||||
EditedByUnCap: "edited by %1",
|
||||
EditionShortUnCap: "%1 ed.",
|
||||
EditionUnCap: "%1 edition",
|
||||
EditorCap: "Editor",
|
||||
EditorsCap: "Editors",
|
||||
EditorShortCap: "Ed.",
|
||||
EditorShortUnCap: "ed.",
|
||||
EditorsShortCap: "Eds.",
|
||||
EditorsShortUnCap: "",
|
||||
FiledCap: "Filed %1",
|
||||
FromCap: "Retrieved from %1",
|
||||
FromUnCap: "from %1",
|
||||
InCap: "In",
|
||||
InNameCap: "In %1",
|
||||
InNameUnCap: "in %1",
|
||||
InterviewByCap: "Interview by %1",
|
||||
InterviewByUnCap: "interview by %1",
|
||||
InterviewCap: "Interview",
|
||||
IntervieweeShortUnCap: "interv.",
|
||||
InterviewerCap: "Interviewer",
|
||||
InterviewersCap: "Interviewers",
|
||||
InterviewWithCap: "Interview with %1",
|
||||
InventorShortUnCap: "invent.",
|
||||
MotionPictureCap: "Motion Picture",
|
||||
NoDateShortUnCap: "n.d.",
|
||||
NumberShortCap: "No. %1",
|
||||
NumberShortUnCap: "no. %1",
|
||||
OnAlbumTitleCap: "On %1",
|
||||
OnlineCap: "Online",
|
||||
OnlineUnCap: "online",
|
||||
PagesCountinousShort: "pp.",
|
||||
PageShort: "p.",
|
||||
PatentCap: "Patent %1",
|
||||
PatentFiledCap: "Patent filed %1",
|
||||
PatentNumberShortCap: "Patent No. %1",
|
||||
PerformedByCap: "Performed by %1",
|
||||
PerformedByUnCap: "performed by %1",
|
||||
PerformerCap: "Performer",
|
||||
PerformersCap: "Performers",
|
||||
PerformerShortCap: "Perf.",
|
||||
PerformerShortUnCap: "perf.",
|
||||
PerformersShortCap: "Perfs.",
|
||||
PerformersShortUnCap: "perfs.",
|
||||
ProducedByCap: "Produced by %1",
|
||||
ProducedByUnCap: "produced by %1",
|
||||
ProducerCap: "Producer",
|
||||
ProducersCap: "Producers",
|
||||
ProducerShortCap: "Prod.",
|
||||
ProducerShortUnCap: "prod.",
|
||||
ProducersShortCap: "Prods.",
|
||||
ProductionCompanyShortCap: "Prod.",
|
||||
RecordedByCap: "Recorded by %1",
|
||||
RetrievedCap: "Retrieved %1",
|
||||
RetrievedFromCap: "Retrieved %1, from %2",
|
||||
SineLocoShort: "s.l.",
|
||||
SineLocoSineNomineShort: "s.l. : s.n.",
|
||||
SineNomineShort: "s.n.",
|
||||
TranslatedByCap: "Translated by %1",
|
||||
TranslatedByUnCap: "translated by %1",
|
||||
TranslatorCap: "Translator",
|
||||
TranslatorsCap: "Translators",
|
||||
TranslatorShortCap: "Trans.",
|
||||
TranslatorShortUnCap: "trans.",
|
||||
TranslatorsShortCap: "Trans.",
|
||||
TranslatorsShortUnCap: "trans.",
|
||||
UnCapEditorsShort: "eds.",
|
||||
VersionShortCap: "Vers.",
|
||||
VolumeCap: "Volume %1",
|
||||
VolumeOfShortCap: "Vol. %1 of %2",
|
||||
VolumesAfterShortUnCap: "%1 vols.",
|
||||
VolumeShortCap: "Vol. %1",
|
||||
VolumeShortUnCap: "vol. %1",
|
||||
VolumesOfShortCap: "Vols. %1 of %2",
|
||||
VolumesShortCap: "Vols. %1",
|
||||
VolumesShortUnCap: "vols. %1",
|
||||
WithUnCap: "%1 with %2",
|
||||
WriterCap: "Writer",
|
||||
WritersCap: "Writers",
|
||||
WriterShortUnCap: "writ.",
|
||||
},
|
||||
} as const;
|
||||
@@ -0,0 +1,281 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type CorpusOutput, describeWordOutput, outputOf } from "tests/bibliography";
|
||||
|
||||
import type { CitedSourceOptions } from "../format";
|
||||
import type { Source } from "../source";
|
||||
import expected from "./fixtures/mla.json";
|
||||
import { mla } from "./mla";
|
||||
|
||||
// Sources the fixtures don't have, for the style's other branches. What they're written as is what Word's style,
|
||||
// MLASeventhEditionOfficeOnline.xsl, writes for them when run with libxslt and Word's English wording
|
||||
const CASES: readonly {
|
||||
readonly name: string;
|
||||
readonly sources: readonly Source[];
|
||||
readonly citations?: readonly (readonly CitedSourceOptions[])[];
|
||||
readonly cited?: readonly string[];
|
||||
readonly bibliography: CorpusOutput["bibliography"];
|
||||
}[] = [
|
||||
{
|
||||
name: "a work of art with nothing to write, as an empty paragraph",
|
||||
sources: [{ tag: "T1", type: "art" }],
|
||||
bibliography: { hangingIndent: true, paragraphs: [""] },
|
||||
},
|
||||
{
|
||||
name: "an entry that ends with italics, with a space after it unless its medium follows",
|
||||
sources: [
|
||||
{ tag: "T1", type: "art", artists: [{ lastName: "Baker", firstName: "Anna" }], title: "Bread" },
|
||||
{ tag: "T2", type: "documentFromWebsite", title: "Crusts", websiteName: "Pizza Daily", year: "2019" },
|
||||
{ tag: "T3", type: "documentFromWebsite", title: "Dough", websiteName: "Pizza Daily", medium: "Web" },
|
||||
],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: ["Baker, Anna. <i>Bread</i>.", "“Crusts.” 2019. <i>Pizza Daily.</i> ", "“Dough.” n.d. <i>Pizza Daily.</i> Web."],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a medium, with and without an address",
|
||||
sources: [
|
||||
{ tag: "T1", type: "website", title: "Ovens", medium: "Web" },
|
||||
{ tag: "T2", type: "website", title: "Salt", medium: "Web", url: "https://example.com/salt" },
|
||||
{
|
||||
tag: "T3",
|
||||
type: "website",
|
||||
title: "Tables",
|
||||
yearAccessed: "2020",
|
||||
monthAccessed: "May",
|
||||
dayAccessed: "3",
|
||||
url: "https://example.com/tables",
|
||||
},
|
||||
],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: [
|
||||
"<i>Ovens</i>. n.d. Web.",
|
||||
"<i>Salt</i>. n.d. Web. <https://example.com/salt>.",
|
||||
"<i>Tables</i>. n.d. 3 May 2020. <https://example.com/tables>.",
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a dash for the same people as the entry before, even editors named in place of authors, but not in a book section",
|
||||
sources: [
|
||||
{ tag: "T1", type: "book", editors: [{ lastName: "Smith", firstName: "John" }], title: "Apples" },
|
||||
{ tag: "T2", type: "book", editors: [{ lastName: "Smith", firstName: "John" }], title: "Bread" },
|
||||
{ tag: "T3", type: "book", authors: [{ lastName: "Lee", firstName: "Ann" }], title: "Cakes" },
|
||||
{ tag: "T4", type: "bookSection", authors: [{ lastName: "Lee", firstName: "Ann" }], title: "Dough", bookTitle: "Kitchens" },
|
||||
],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: [
|
||||
"Lee, Ann. <i>Cakes</i>. n.d.",
|
||||
"Lee, Ann. “Dough.” <i>Kitchens</i>. n.d.",
|
||||
"Smith, John, ed. <i>Apples</i>. n.d.",
|
||||
"—. <i>Bread</i>. Ed. John Smith. n.d.",
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "performers that are an organization, without the word for their role",
|
||||
sources: [
|
||||
{
|
||||
tag: "T1",
|
||||
type: "performance",
|
||||
corporatePerformer: "The Players",
|
||||
title: "Hamlet",
|
||||
year: "1999",
|
||||
city: "London",
|
||||
theater: "Globe",
|
||||
},
|
||||
{
|
||||
tag: "T2",
|
||||
type: "film",
|
||||
directors: [{ lastName: "Gray", firstName: "Tom" }],
|
||||
corporatePerformer: "The Players",
|
||||
title: "Storm",
|
||||
distributor: "Studio",
|
||||
},
|
||||
],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: ["<i>Hamlet</i>. The Players. Globe, London. 1999.", "<i>Storm</i>. Dir. Tom Gray. The Players. Studio, n.d."],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sound recordings named by their composers, with no space before the producer after the album alone",
|
||||
sources: [
|
||||
{
|
||||
tag: "T1",
|
||||
type: "soundRecording",
|
||||
composers: [{ lastName: "Moss", firstName: "Eve" }],
|
||||
producers: [{ lastName: "Lee", firstName: "Ann" }],
|
||||
albumTitle: "Songs",
|
||||
},
|
||||
{
|
||||
tag: "T2",
|
||||
type: "soundRecording",
|
||||
producers: [{ lastName: "Lee", firstName: "Ann" }],
|
||||
albumTitle: "Tunes",
|
||||
year: "2001",
|
||||
city: "Leeds",
|
||||
},
|
||||
],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: ["<i>Tunes</i>.Prod. Ann Lee. Leeds, 2001.", "Moss, Eve. <i>Songs</i>. Prod. Ann Lee. n.d."],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a conference paper named by its editors, and one with its editors after its authors",
|
||||
sources: [
|
||||
{
|
||||
tag: "T1",
|
||||
type: "conferenceProceedings",
|
||||
editors: [
|
||||
{ lastName: "Patel", firstName: "Ravi" },
|
||||
{ lastName: "Jones", firstName: "Mary" },
|
||||
],
|
||||
title: "Heat",
|
||||
conferenceName: "Pizza Summit",
|
||||
year: "2010",
|
||||
city: "Naples",
|
||||
publisher: "Press",
|
||||
pages: "4-9",
|
||||
},
|
||||
{
|
||||
tag: "T2",
|
||||
type: "conferenceProceedings",
|
||||
authors: [{ lastName: "Moss", firstName: "Eve" }],
|
||||
editors: [{ lastName: "Patel", firstName: "Ravi" }],
|
||||
title: "Salt",
|
||||
conferenceName: "Pizza Summit",
|
||||
},
|
||||
],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: [
|
||||
"Moss, Eve. “Salt.” <i>Pizza Summit</i>. Ed. Ravi Patel. n.d.",
|
||||
"Patel, Ravi and Mary Jones, “Heat.” <i>Pizza Summit</i>. Naples: Press, 2010. 4-9.",
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "broadcast interviews, with and without a title, a broadcast's title and interviewers",
|
||||
sources: [
|
||||
{
|
||||
tag: "T1",
|
||||
type: "interview",
|
||||
interviewees: [{ lastName: "Hall", firstName: "Ann" }],
|
||||
year: "2001",
|
||||
broadcaster: "Radio One",
|
||||
},
|
||||
{
|
||||
tag: "T2",
|
||||
type: "interview",
|
||||
interviewees: [{ lastName: "Hall", firstName: "Ben" }],
|
||||
interviewers: [{ lastName: "Ward", firstName: "Cy" }],
|
||||
broadcastTitle: "Mornings",
|
||||
broadcaster: "Radio One",
|
||||
},
|
||||
{
|
||||
tag: "T3",
|
||||
type: "interview",
|
||||
interviewees: [{ lastName: "Hall", firstName: "Cara" }],
|
||||
title: "On Bread",
|
||||
city: "Leeds",
|
||||
broadcaster: "Radio One",
|
||||
station: "FM",
|
||||
},
|
||||
{
|
||||
tag: "T4",
|
||||
type: "interview",
|
||||
interviewees: [{ lastName: "Hall", firstName: "Dee" }],
|
||||
interviewers: [{ lastName: "Ward", firstName: "Cy" }],
|
||||
title: "On Salt",
|
||||
broadcaster: "Radio One",
|
||||
},
|
||||
{ tag: "T5", type: "interview", title: "On Ovens", broadcastTitle: "Mornings", broadcaster: "Radio One" },
|
||||
{
|
||||
tag: "T6",
|
||||
type: "interview",
|
||||
interviewers: [{ lastName: "Ward", firstName: "Cy" }],
|
||||
title: "On Heat",
|
||||
broadcastTitle: "Mornings",
|
||||
broadcaster: "Radio One",
|
||||
},
|
||||
],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: [
|
||||
"Hall, Ann. Interview. Radio One. 2001.",
|
||||
"Hall, Ben. Interview with Cy Ward. <i>Mornings.</i> Radio One. n.d.",
|
||||
"Hall, Cara. <i>On Bread</i>. Radio One. FM, Leeds. n.d.",
|
||||
"Hall, Dee. On Salt. with Cy Ward. Radio One. n.d.",
|
||||
"“On Heat” with Cy Ward. <i>Mornings.</i> Radio One. n.d.",
|
||||
"“On Ovens” <i>Mornings.</i> Radio One. n.d.",
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "citations with volumes and pages, without the author or the title, and of a source with neither",
|
||||
sources: [
|
||||
{ tag: "T1", type: "book", authors: [{ lastName: "Baker", firstName: "Anna" }], title: "Pizza" },
|
||||
{ tag: "T2", type: "book", title: "Bread" },
|
||||
{ tag: "T3", type: "book", year: "2001" },
|
||||
],
|
||||
citations: [
|
||||
[{ source: "T1", volume: "2" }],
|
||||
[{ source: "T1", pages: "5", volume: "2-3" }],
|
||||
[{ source: "T1", volume: "2, 4" }],
|
||||
[{ source: "T2", pages: "5" }],
|
||||
[{ source: "T3", pages: "5" }],
|
||||
[{ source: "T1", pages: "5", hideAuthor: true }],
|
||||
[{ source: "T1", pages: "5", hideAuthor: true, hideTitle: true }],
|
||||
[{ source: "T1", prefix: "see ", suffix: ", note" }, { source: "T2" }],
|
||||
],
|
||||
cited: [
|
||||
"(Baker vol. 2)",
|
||||
"(Baker 2-3:5)",
|
||||
"(Baker vols. 2, 4)",
|
||||
"(Bread 5)",
|
||||
"(T35)",
|
||||
"(Pizza 5)",
|
||||
"(5)",
|
||||
"(see Baker, note; Bread)",
|
||||
],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["2001.", "Baker, Anna. <i>Pizza</i>. n.d.", "<i>Bread</i>. n.d."] },
|
||||
},
|
||||
{
|
||||
name: "citations of more than three authors",
|
||||
sources: [
|
||||
{
|
||||
tag: "T1",
|
||||
type: "book",
|
||||
authors: [
|
||||
{ lastName: "Baker", firstName: "Anna" },
|
||||
{ lastName: "Smith", firstName: "John" },
|
||||
{ lastName: "Patel", firstName: "Ravi" },
|
||||
{ lastName: "Jones", firstName: "Mary" },
|
||||
],
|
||||
title: "Pizza",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "T1" }]],
|
||||
cited: ["(Baker, Smith and Patel)"],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["Baker, Anna, et al. <i>Pizza</i>. n.d."] },
|
||||
},
|
||||
];
|
||||
|
||||
describe("mla", () => {
|
||||
describeWordOutput(mla, expected);
|
||||
|
||||
describe("as Word's style writes", () => {
|
||||
for (const { name, sources, citations = [], cited = [], bibliography } of CASES) {
|
||||
it(`writes ${name}`, () => {
|
||||
const output = outputOf(mla, { sources, citations });
|
||||
expect(output.citations).toEqual(cited);
|
||||
expect(output.bibliography).toEqual(bibliography);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,753 @@
|
||||
/**
|
||||
* MLA, seventh edition: citations such as "(Baker 50)", and a bibliography of the sources sorted by their authors, such
|
||||
* as "Baker, Anna. The Art of Pizza. Naples: Pizza Press, 2010.", each indented after its first line, with "—" in place
|
||||
* of the authors of the entry before when they are the same.
|
||||
*
|
||||
* Written from Word's style, MLASeventhEditionOfficeOnline.xsl, whose templates and variables each function names.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type FormattedText, type TextLike, italic, join, textOf } from "./formatted-text";
|
||||
import { LOCALS } from "./locals";
|
||||
import type { CitedSource, FormattedBibliography, StyleDefinition } from "./style";
|
||||
import { sortByKey, translate, xslTemplates } from "./xsl";
|
||||
import { type Field, type Role, type WordNames, type WordSource, type WordSourceType, fieldOf } from "../word-source";
|
||||
|
||||
// Some of the style's names for its templates and variables, as it spells them
|
||||
// cspell:words Seperator VIYP dups
|
||||
|
||||
const { General, Strings, MLA } = LOCALS;
|
||||
const { appendDot, formatDatePrivate, formatName, needDot, stringFormat, stringFormatDot } = xslTemplates(General);
|
||||
const SPACE = General.Space;
|
||||
const LIST = General.ListSeparator;
|
||||
|
||||
/**
|
||||
* The roles whose people each type of source is named by, in the order the style looks for them. A film's last is its
|
||||
* producers, which the style looks for as `b:Producer`, which no source has
|
||||
*/
|
||||
const MAIN_ROLES: Readonly<Record<WordSourceType, readonly Role[]>> = {
|
||||
Book: ["Author", "Editor", "Translator"],
|
||||
BookSection: ["Author"],
|
||||
JournalArticle: ["Author"],
|
||||
ArticleInAPeriodical: ["Author"],
|
||||
ConferenceProceedings: ["Author", "Editor"],
|
||||
Report: ["Author"],
|
||||
SoundRecording: ["Performer", "Conductor", "Composer"],
|
||||
Performance: ["Writer", "Director", "Performer"],
|
||||
Art: ["Artist"],
|
||||
DocumentFromInternetSite: ["Author"],
|
||||
InternetSite: ["Author"],
|
||||
Film: ["Writer", "Director", "Performer"],
|
||||
Interview: ["Interviewee"],
|
||||
Patent: ["Inventor"],
|
||||
ElectronicSource: ["Author", "Editor", "Compiler", "Translator"],
|
||||
Case: [],
|
||||
Misc: ["Author"],
|
||||
};
|
||||
|
||||
/** The text of the people with a role, or of the organization, as the style reads a role's string value */
|
||||
const stringValueOf = (names: WordNames | undefined): string =>
|
||||
!names ? "" : "corporate" in names ? names.corporate : names.people.map(({ last, first, middle }) => last + first + middle).join("");
|
||||
|
||||
/** The people a source is named by: those with the first of its main roles that has any (`MainContributors`) */
|
||||
const mainContributorsOf = (source: WordSource): WordNames | undefined => {
|
||||
const role = MAIN_ROLES[source.type].find((candidate) => stringValueOf(source.names[candidate]) !== "");
|
||||
return role === undefined ? undefined : source.names[role];
|
||||
};
|
||||
|
||||
/**
|
||||
* What comes after a person in a list of people: "et al." after the first of more than three, who is the only one
|
||||
* written, "and" before the last of two or three, and a list separator after the others (`formatPersonSeperator`)
|
||||
*/
|
||||
const personSeparator = (position: number, count: number): string =>
|
||||
count > 3
|
||||
? position === 1
|
||||
? LIST + Strings.AndOthersUnCap
|
||||
: ""
|
||||
: position === count - 1
|
||||
? SPACE + Strings.AndUnCap + SPACE
|
||||
: position === count
|
||||
? ""
|
||||
: LIST;
|
||||
|
||||
/**
|
||||
* The people who made a source, as an entry starts with them, such as "Baker, Anna, Ravi Patel and Mary Ann Jones", or
|
||||
* "Baker, Anna, et al." for more than three, or the organization (`formatPersonsAuthor`)
|
||||
*/
|
||||
const personsAuthor = (names: WordNames | undefined): string => {
|
||||
if (!names) {
|
||||
return "";
|
||||
}
|
||||
if ("corporate" in names) {
|
||||
return names.corporate;
|
||||
}
|
||||
const count = names.people.length;
|
||||
return names.people
|
||||
.map(
|
||||
(person, index) =>
|
||||
(index === 0 ? formatName(person, MLA.MainAuthor) : count <= 3 ? formatName(person, MLA.OtherAuthors) : "") +
|
||||
personSeparator(index + 1, count),
|
||||
)
|
||||
.join("");
|
||||
};
|
||||
|
||||
/** People later in an entry, such as "Ravi Patel and Mary Ann Jones" as its editors, or the organization (`formatPersons`) */
|
||||
const persons = (names: WordNames | undefined): string => {
|
||||
if (!names) {
|
||||
return "";
|
||||
}
|
||||
if ("corporate" in names) {
|
||||
return names.corporate;
|
||||
}
|
||||
const count = names.people.length;
|
||||
return names.people
|
||||
.map(
|
||||
(person, index) =>
|
||||
(count <= 3 || index === 0 ? formatName(person, MLA.SecondaryAuthors) : "") + personSeparator(index + 1, count),
|
||||
)
|
||||
.join("");
|
||||
};
|
||||
|
||||
/** How many people have a role, which is none when an organization has it */
|
||||
const countOf = (source: WordSource, role: Role): number => {
|
||||
const names = source.names[role];
|
||||
return names && "people" in names ? names.people.length : 0;
|
||||
};
|
||||
|
||||
/** The word for several people, or for one, or nothing for an organization, as the style counts the people */
|
||||
const wordFor = (count: number, one: string, many: string): string => (count > 1 ? many : count === 1 ? one : "");
|
||||
|
||||
/** The year, or "n.d." without one (`getYear`) */
|
||||
const yearOf = (source: WordSource): string => fieldOf(source, "Year") || Strings.NoDateShortUnCap;
|
||||
|
||||
/** The date, such as "14 March 2018", or "n.d." without a year (`formatDate`) */
|
||||
const dateOf = (source: WordSource): string => {
|
||||
const year = fieldOf(source, "Year");
|
||||
return year ? formatDatePrivate(fieldOf(source, "Day"), fieldOf(source, "Month"), year, MLA.Date) : Strings.NoDateShortUnCap;
|
||||
};
|
||||
|
||||
/** The date the source was read, or nothing without a year (`formatDateAccessed`) */
|
||||
const dateAccessedOf = (source: WordSource): string => {
|
||||
const year = fieldOf(source, "YearAccessed");
|
||||
return year ? formatDatePrivate(fieldOf(source, "DayAccessed"), fieldOf(source, "MonthAccessed"), year, MLA.Date) : "";
|
||||
};
|
||||
|
||||
/** The text without the spaces, tabs and line feeds at its ends, and with each run of them in it as one space (`normalize-space`) */
|
||||
const normalizeSpace = (text: string): string => text.replace(/[ \t\r\n]+/g, " ").replace(/^ | $/g, "");
|
||||
|
||||
/** Three fields, with a separator between the first two and another before the third, and a dot after them */
|
||||
const fieldsDot = (first: string, second: string, third: string, firstSeparator: string, secondSeparator: string): string => {
|
||||
const firstTwo = first + (first && second ? firstSeparator : "") + second;
|
||||
return appendDot(firstTwo + (firstTwo && third ? secondSeparator : "") + third);
|
||||
};
|
||||
|
||||
/** The first field, ": ", the second, ", " and the third, such as "Naples: Pizza Press, 2010." (`templateA`) */
|
||||
const templateA = (first: string, second: string, third: string): string => fieldsDot(first, second, third, General.EnumSeparator, LIST);
|
||||
|
||||
/** The first field, ": " and the second, such as "Italy: Patent 123." (`templateB`) */
|
||||
const templateB = (first: string, second: string): string => fieldsDot(first, second, "", General.EnumSeparator, "");
|
||||
|
||||
/** The first field, ", " and the second, such as "National Gallery, London." (`templateC`) */
|
||||
const templateC = (first: string, second: string): string => fieldsDot(first, second, "", LIST, "");
|
||||
|
||||
/** The first field, ", ", the second, ": " and the third, such as "14 March 2018, late ed.: 12-14." (`templateE`) */
|
||||
const templateE = (first: string, second: string, third: string): string => fieldsDot(first, second, third, LIST, General.EnumSeparator);
|
||||
|
||||
/** A journal's volume and issue, its year in brackets and the pages, such as "12.4 (2018): 233-250." (`templateVIYP`) */
|
||||
const templateVIYP = (source: WordSource): string => {
|
||||
const volume = fieldOf(source, "Volume");
|
||||
const issue = fieldOf(source, "Issue");
|
||||
const pages = fieldOf(source, "Pages");
|
||||
// The year is "n.d." without one, so it is always written
|
||||
return appendDot(
|
||||
volume +
|
||||
(volume && issue ? General.Dot : "") +
|
||||
issue +
|
||||
SPACE +
|
||||
General.OpenBracket +
|
||||
yearOf(source) +
|
||||
General.CloseBracket +
|
||||
(pages ? General.EnumSeparator : "") +
|
||||
pages,
|
||||
);
|
||||
};
|
||||
|
||||
/** The medium, the date the source was read and its address, such as "Web. 3 May 2019. <https://pizza.example>." (`templateMDaU`) */
|
||||
const templateMDaU = (source: WordSource): string => {
|
||||
const medium = appendDot(fieldOf(source, "Medium"));
|
||||
const accessed = appendDot(dateAccessedOf(source));
|
||||
const url = fieldOf(source, "URL");
|
||||
const accessedUrl = appendDot(accessed + (accessed && url ? SPACE : "") + (url ? General.OpenLink + url + General.CloseLink : ""));
|
||||
return medium + (medium && accessedUrl ? SPACE : "") + accessedUrl;
|
||||
};
|
||||
|
||||
/** The format of a volume, or of volumes when it has a comma or a hyphen in it, such as "2-3" */
|
||||
const volumeFormatOf = (volume: string, one: string, many: string): string =>
|
||||
volume.includes(",") || translate(volume, General.Hyphens, "").length !== volume.length ? many : one;
|
||||
|
||||
/** A part of an entry: its name, its text, and the parts before it whose text puts a space before it, or all of them */
|
||||
type Part = readonly [name: string, text: TextLike, after?: readonly string[]];
|
||||
|
||||
/** The parts of an entry that have text, each with a space before it when a part before it has text, as the style writes them */
|
||||
const spaced = (...parts: readonly Part[]): FormattedText =>
|
||||
parts.reduce<{ readonly text: FormattedText; readonly written: readonly string[]; readonly names: readonly string[] }>(
|
||||
(entry, [name, text, after = entry.names]) => {
|
||||
const names = [...entry.names, name];
|
||||
if (textOf(text).length === 0) {
|
||||
return { ...entry, names };
|
||||
}
|
||||
const space = after.some((other) => entry.written.includes(other)) ? SPACE : "";
|
||||
return { text: join(entry.text, space, text), written: [...entry.written, name], names };
|
||||
},
|
||||
{ text: [], written: [], names: [] },
|
||||
).text;
|
||||
|
||||
/** A title in italics, and a dot after it unless it ends a sentence */
|
||||
const italicDot = (title: string): FormattedText => join(italic(title), needDot(title));
|
||||
|
||||
/** A title and a dot after it, in quotes */
|
||||
const quotedDot = (title: string): string => (title ? General.OpenQuote + appendDot(title) + General.CloseQuote : "");
|
||||
|
||||
/** People with a role and the word for it before them, such as "Ed. Ravi Patel.", or an organization with a space before it */
|
||||
const prefixDot = (people: string, count: number, one: string, many: string): string =>
|
||||
people ? wordFor(count, one, many) + SPACE + appendDot(people) : "";
|
||||
|
||||
/** People named first and the word for their role, such as "Patel, Ravi, ed." */
|
||||
const suffixLF = (people: string, count: number, one: string, many: string): string =>
|
||||
people ? people + LIST + wordFor(count, one, many) : "";
|
||||
|
||||
/** The variables the style writes each type of source from, by their names in the style */
|
||||
type Variables = {
|
||||
readonly author: string;
|
||||
readonly authorDot: string;
|
||||
readonly sectionAuthorDot: string;
|
||||
readonly bookAuthorDot: string;
|
||||
readonly performerLF: string;
|
||||
readonly performerLFDot: string;
|
||||
readonly conductorLFDot: string;
|
||||
readonly composerLFDot: string;
|
||||
readonly artistDot: string;
|
||||
readonly intervieweeLFDot: string;
|
||||
readonly inventorLFDot: string;
|
||||
readonly interviewer: string;
|
||||
readonly interviewerDot: string;
|
||||
readonly writer: string;
|
||||
readonly composer: string;
|
||||
readonly editor: string;
|
||||
readonly translator: string;
|
||||
readonly suffixEditorLFDot: string;
|
||||
readonly suffixTranslatorLFDot: string;
|
||||
readonly suffixCompilerLFDot: string;
|
||||
readonly prefixEditorDot: string;
|
||||
readonly prefixTranslatorDot: string;
|
||||
readonly prefixDirectorDot: string;
|
||||
readonly prefixPerformerDot: string;
|
||||
readonly prefixConductorDot: string;
|
||||
readonly prefixCompilerDot: string;
|
||||
readonly prefixVersionDot: string;
|
||||
readonly prefixVolumeDot: string;
|
||||
readonly noVolumesSufDot: string;
|
||||
readonly prefixCaseNoDot: string;
|
||||
readonly prodDot: string;
|
||||
readonly prefixProdDot: string;
|
||||
readonly tempProdPr: string;
|
||||
readonly title: string;
|
||||
readonly titleDot: string;
|
||||
readonly dateDot: string;
|
||||
readonly editionDot: string;
|
||||
readonly pagesDot: string;
|
||||
readonly institutionDot: string;
|
||||
readonly tempCPY: string;
|
||||
readonly tempCPD: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The variables of a source's entry, from its fields and people, and its author, which is "—" for the same people as
|
||||
* the entry before
|
||||
*/
|
||||
const variablesOf = (source: WordSource, author: string): Variables => {
|
||||
const field = (name: Field): string => fieldOf(source, name);
|
||||
const count = (role: Role): number => countOf(source, role);
|
||||
const editor = persons(source.names.Editor);
|
||||
const translator = persons(source.names.Translator);
|
||||
const producerName = persons(source.names.ProducerName);
|
||||
const productionCompany = field("ProductionCompany");
|
||||
const volume = field("Volume");
|
||||
const prodDot = producerName ? appendDot(producerName) : appendDot(productionCompany);
|
||||
return {
|
||||
author,
|
||||
authorDot: appendDot(author),
|
||||
sectionAuthorDot: appendDot(personsAuthor(source.names.Author)),
|
||||
bookAuthorDot: appendDot(personsAuthor(source.names.BookAuthor)),
|
||||
performerLF: personsAuthor(source.names.Performer),
|
||||
performerLFDot: appendDot(personsAuthor(source.names.Performer)),
|
||||
conductorLFDot: appendDot(personsAuthor(source.names.Conductor)),
|
||||
composerLFDot: appendDot(personsAuthor(source.names.Composer)),
|
||||
artistDot: appendDot(personsAuthor(source.names.Artist)),
|
||||
intervieweeLFDot: appendDot(personsAuthor(source.names.Interviewee)),
|
||||
inventorLFDot: appendDot(personsAuthor(source.names.Inventor)),
|
||||
interviewer: persons(source.names.Interviewer),
|
||||
interviewerDot: appendDot(persons(source.names.Interviewer)),
|
||||
writer: persons(source.names.Writer),
|
||||
composer: persons(source.names.Composer),
|
||||
editor,
|
||||
translator,
|
||||
suffixEditorLFDot: suffixLF(
|
||||
personsAuthor(source.names.Editor),
|
||||
count("Editor"),
|
||||
Strings.EditorShortUnCap,
|
||||
Strings.EditorsShortUnCap,
|
||||
),
|
||||
suffixTranslatorLFDot: suffixLF(
|
||||
personsAuthor(source.names.Translator),
|
||||
count("Translator"),
|
||||
Strings.TranslatorShortUnCap,
|
||||
Strings.TranslatorsShortUnCap,
|
||||
),
|
||||
suffixCompilerLFDot: suffixLF(
|
||||
personsAuthor(source.names.Compiler),
|
||||
count("Compiler"),
|
||||
Strings.CompilerShortUnCap,
|
||||
Strings.CompilersShortUnCap,
|
||||
),
|
||||
// The style writes "Ed." and "Perf." before several editors or performers too
|
||||
prefixEditorDot: prefixDot(editor, count("Editor"), Strings.EditorShortCap, Strings.EditorShortCap),
|
||||
prefixTranslatorDot: prefixDot(translator, count("Translator"), Strings.TranslatorShortCap, Strings.TranslatorsShortCap),
|
||||
prefixDirectorDot: prefixDot(
|
||||
persons(source.names.Director),
|
||||
count("Director"),
|
||||
Strings.DirectorShortCap,
|
||||
Strings.DirectorsShortCap,
|
||||
),
|
||||
prefixPerformerDot: prefixDot(
|
||||
persons(source.names.Performer),
|
||||
count("Performer"),
|
||||
Strings.PerformerShortCap,
|
||||
Strings.PerformerShortCap,
|
||||
),
|
||||
prefixConductorDot: prefixDot(
|
||||
persons(source.names.Conductor),
|
||||
count("Conductor"),
|
||||
Strings.ConductorShortUnCap,
|
||||
Strings.ConductorsShortUnCap,
|
||||
),
|
||||
prefixCompilerDot: prefixDot(
|
||||
persons(source.names.Compiler),
|
||||
count("Compiler"),
|
||||
Strings.CompilerShortCap,
|
||||
Strings.CompilersShortCap,
|
||||
),
|
||||
prefixVersionDot: field("Version") ? Strings.VersionShortCap + SPACE + appendDot(field("Version")) : "",
|
||||
prefixVolumeDot: volume
|
||||
? appendDot(textOf(stringFormat(volumeFormatOf(volume, Strings.VolumeShortCap, Strings.VolumesShortCap), volume)))
|
||||
: "",
|
||||
noVolumesSufDot: field("NumberVolumes")
|
||||
? appendDot(textOf(stringFormat(Strings.VolumesAfterShortUnCap, field("NumberVolumes"))))
|
||||
: "",
|
||||
prefixCaseNoDot: field("CaseNumber") ? textOf(stringFormatDot(Strings.NumberShortCap, field("CaseNumber"))) : "",
|
||||
prodDot,
|
||||
prefixProdDot:
|
||||
producerName || productionCompany
|
||||
? wordFor(count("ProducerName"), Strings.ProducerShortCap + SPACE, Strings.ProducersShortCap + SPACE) + prodDot
|
||||
: "",
|
||||
tempProdPr: producerName ? Strings.ProducerShortCap + SPACE + appendDot(producerName) : "",
|
||||
title: field("Title"),
|
||||
titleDot: appendDot(field("Title")),
|
||||
dateDot: appendDot(dateOf(source)),
|
||||
editionDot: appendDot(field("Edition")),
|
||||
pagesDot: appendDot(field("Pages")),
|
||||
institutionDot: appendDot(field("Institution")),
|
||||
tempCPY: templateA(field("City"), field("Publisher"), yearOf(source)),
|
||||
tempCPD: templateA(field("City"), field("Publisher"), dateOf(source)),
|
||||
};
|
||||
};
|
||||
|
||||
/** A book's volume, or how many volumes it has, and how many after its publisher when it has both */
|
||||
const volumesOf = (v: Variables): readonly [Part, Part] => [
|
||||
["volume", v.prefixVolumeDot || v.noVolumesSufDot],
|
||||
["volumes", v.prefixVolumeDot ? v.noVolumesSufDot : ""],
|
||||
];
|
||||
|
||||
/** A book's entry, named by its editors, or else its translators, when it has no author */
|
||||
const book = (v: Variables): FormattedText => {
|
||||
const [volume, volumes] = volumesOf(v);
|
||||
const place: Part = ["place", v.tempCPY];
|
||||
if (v.editor && !v.author) {
|
||||
return spaced(
|
||||
["editor", v.suffixEditorLFDot],
|
||||
["title", italicDot(v.title)],
|
||||
["translator", v.prefixTranslatorDot],
|
||||
["edition", v.editionDot],
|
||||
volume,
|
||||
place,
|
||||
volumes,
|
||||
);
|
||||
}
|
||||
return v.translator && !v.author
|
||||
? spaced(["translator", v.suffixTranslatorLFDot], ["title", italicDot(v.title)], ["edition", v.editionDot], volume, place, volumes)
|
||||
: spaced(
|
||||
["author", v.authorDot],
|
||||
["title", italicDot(v.title)],
|
||||
["editor", v.prefixEditorDot],
|
||||
["translator", v.prefixTranslatorDot],
|
||||
["edition", v.editionDot],
|
||||
volume,
|
||||
place,
|
||||
volumes,
|
||||
);
|
||||
};
|
||||
|
||||
/** A book section's entry, named by its own authors even when the entry before has them */
|
||||
const bookSection = (v: Variables, source: WordSource): FormattedText => {
|
||||
const [volume, volumes] = volumesOf(v);
|
||||
return spaced(
|
||||
["author", v.sectionAuthorDot],
|
||||
["title", quotedDot(v.title)],
|
||||
["bookAuthor", v.bookAuthorDot],
|
||||
["bookTitle", italicDot(fieldOf(source, "BookTitle"))],
|
||||
["editor", v.prefixEditorDot],
|
||||
["translator", v.prefixTranslatorDot],
|
||||
["edition", v.editionDot],
|
||||
volume,
|
||||
["place", v.tempCPY],
|
||||
volumes,
|
||||
["pages", v.pagesDot],
|
||||
);
|
||||
};
|
||||
|
||||
/** A conference paper's entry, named by its editors when it has no author */
|
||||
const conferenceProceedings = (v: Variables, source: WordSource): FormattedText => {
|
||||
const title: Part = ["title", quotedDot(v.title)];
|
||||
const conference: Part = ["conference", italicDot(fieldOf(source, "ConferenceName"))];
|
||||
return v.editor && !v.author
|
||||
? spaced(["editor", v.suffixEditorLFDot], title, conference, ["place", v.tempCPY], ["pages", v.pagesDot])
|
||||
: spaced(["author", v.authorDot], title, conference, ["editor", v.prefixEditorDot], ["place", v.tempCPY], ["pages", v.pagesDot]);
|
||||
};
|
||||
|
||||
/** A report's entry: one with a city has its title in italics, and its publisher */
|
||||
const report = (v: Variables, source: WordSource): FormattedText => {
|
||||
const type: Part = ["type", appendDot(fieldOf(source, "ThesisType"))];
|
||||
return fieldOf(source, "City")
|
||||
? spaced(["author", v.authorDot], ["title", italicDot(v.title)], type, ["institution", v.institutionDot], ["place", v.tempCPY])
|
||||
: spaced(["author", v.authorDot], ["title", quotedDot(v.title)], type, [
|
||||
"institution",
|
||||
templateC(fieldOf(source, "Institution"), yearOf(source)),
|
||||
]);
|
||||
};
|
||||
|
||||
/** A sound recording's entry, named by its performers, or else its conductors, or else its composers */
|
||||
const soundRecording = (v: Variables, source: WordSource): FormattedText => {
|
||||
const title: Part = ["title", quotedDot(v.title)];
|
||||
const album: Part = ["album", italicDot(fieldOf(source, "AlbumTitle"))];
|
||||
const composer: Part = ["composer", v.composer ? stringFormatDot(Strings.ByCap, v.composer) : ""];
|
||||
const place: Part = ["place", templateA(fieldOf(source, "City"), fieldOf(source, "ProductionCompany"), yearOf(source))];
|
||||
if (v.performerLF) {
|
||||
return spaced(
|
||||
["performer", v.performerLFDot],
|
||||
title,
|
||||
album,
|
||||
["conductor", v.prefixConductorDot],
|
||||
composer,
|
||||
["producer", v.tempProdPr],
|
||||
place,
|
||||
);
|
||||
}
|
||||
// Named by its composers, it has no space between its album and its producer when it has neither composers nor a
|
||||
// title: the style doesn't look for the album there
|
||||
return v.conductorLFDot
|
||||
? spaced(["conductor", v.conductorLFDot], title, album, composer, ["producer", v.tempProdPr], place)
|
||||
: spaced(["composer", v.composerLFDot], title, album, ["producer", v.tempProdPr, ["composer", "title"]], place);
|
||||
};
|
||||
|
||||
/** A performance's or a film's title, writers, directors and performers */
|
||||
const titleAndPeople = (v: Variables): readonly Part[] => [
|
||||
["title", italicDot(v.title)],
|
||||
["writer", v.writer ? stringFormatDot(Strings.ByCap, v.writer) : ""],
|
||||
["director", v.prefixDirectorDot],
|
||||
["performer", v.prefixPerformerDot],
|
||||
];
|
||||
|
||||
/** A work of art's entry, with the publication it is in when it has one */
|
||||
const art = (v: Variables, source: WordSource): FormattedText => {
|
||||
const artist: Part = ["artist", normalizeSpace(v.artistDot)];
|
||||
const title: Part = ["title", italicDot(v.title)];
|
||||
const publication = fieldOf(source, "PublicationTitle");
|
||||
return publication
|
||||
? spaced(
|
||||
artist,
|
||||
title,
|
||||
["institution", v.institutionDot],
|
||||
["publication", italicDot(publication)],
|
||||
["place", v.tempCPY],
|
||||
["pages", v.pagesDot],
|
||||
)
|
||||
: spaced(artist, title, ["institution", templateC(fieldOf(source, "Institution"), fieldOf(source, "City"))], ["pages", v.pagesDot]);
|
||||
};
|
||||
|
||||
/** An electronic source's entry, named by its authors, or else its editors, its compilers or its translators */
|
||||
const electronicSource = (v: Variables, source: WordSource): FormattedText => {
|
||||
const publication = fieldOf(source, "PublicationTitle");
|
||||
// The style looks for the parts up to the volume before the people and the producers after them
|
||||
const before = ["author", "title", "publication", "edition", "volume"];
|
||||
return spaced(
|
||||
["author", v.authorDot || v.suffixEditorLFDot || v.suffixCompilerLFDot || v.suffixTranslatorLFDot],
|
||||
["title", publication ? quotedDot(v.title) : italicDot(v.title)],
|
||||
["publication", italicDot(publication)],
|
||||
["edition", v.editionDot],
|
||||
["volume", v.prefixVolumeDot],
|
||||
["editor", v.authorDot ? v.prefixEditorDot : "", before],
|
||||
["compiler", v.authorDot || v.suffixEditorLFDot ? v.prefixCompilerDot : "", before],
|
||||
["translator", v.authorDot || v.suffixEditorLFDot || v.suffixCompilerLFDot ? v.prefixTranslatorDot : "", before],
|
||||
["producer", v.prefixProdDot, before],
|
||||
["place", v.tempCPD, [...before, "producer"]],
|
||||
);
|
||||
};
|
||||
|
||||
/** An interview's title, or "Interview" without one, and its interviewers with it when it is broadcast */
|
||||
const interviewTitle = (v: Variables, source: WordSource): TextLike => {
|
||||
const broadcast = fieldOf(source, "BroadcastTitle");
|
||||
if (!fieldOf(source, "Broadcaster")) {
|
||||
return !v.title ? Strings.InterviewCap + General.Dot : broadcast ? quotedDot(v.title) : italic(v.title);
|
||||
}
|
||||
if (!v.title) {
|
||||
return v.interviewer ? stringFormatDot(Strings.InterviewWithCap, v.interviewer) : Strings.InterviewCap + General.Dot;
|
||||
}
|
||||
if (!v.interviewer) {
|
||||
return broadcast ? General.OpenQuote + v.title + General.CloseQuote : italicDot(v.title);
|
||||
}
|
||||
// The style's formats write the text of what they are given, so the title in italics is written without them
|
||||
return stringFormatDot(
|
||||
Strings.WithUnCap,
|
||||
broadcast ? General.OpenQuote + v.title + General.CloseQuote : appendDot(v.title),
|
||||
v.interviewerDot,
|
||||
);
|
||||
};
|
||||
|
||||
/** An interview's entry, with a space before each part after its title, whatever is before it */
|
||||
const interview = (v: Variables, source: WordSource): FormattedText => {
|
||||
const after = (text: TextLike): TextLike => (textOf(text) ? join(SPACE, text) : "");
|
||||
return join(
|
||||
v.intervieweeLFDot,
|
||||
v.intervieweeLFDot ? SPACE : "",
|
||||
interviewTitle(v, source),
|
||||
after(italic(appendDot(fieldOf(source, "BroadcastTitle")))),
|
||||
...(fieldOf(source, "Broadcaster")
|
||||
? [
|
||||
after(appendDot(fieldOf(source, "Broadcaster"))),
|
||||
after(templateC(fieldOf(source, "Station"), fieldOf(source, "City"))),
|
||||
after(v.dateDot),
|
||||
]
|
||||
: [after(v.interviewerDot), after(v.prefixEditorDot), after(v.prefixTranslatorDot), after(v.tempCPD), after(v.pagesDot)]),
|
||||
);
|
||||
};
|
||||
|
||||
/** Each type of source's entry, before its medium, the date it was read and its address (the `source` variable) */
|
||||
const ENTRIES: Readonly<Record<WordSourceType, (v: Variables, source: WordSource) => FormattedText>> = {
|
||||
Book: book,
|
||||
BookSection: bookSection,
|
||||
JournalArticle: (v, source) =>
|
||||
spaced(
|
||||
["author", v.authorDot],
|
||||
["title", quotedDot(v.title)],
|
||||
["journal", italic(fieldOf(source, "JournalName"))],
|
||||
["volume", templateVIYP(source)],
|
||||
),
|
||||
ConferenceProceedings: conferenceProceedings,
|
||||
Report: report,
|
||||
SoundRecording: soundRecording,
|
||||
Performance: (v, source) =>
|
||||
spaced(...titleAndPeople(v), ["place", templateC(fieldOf(source, "Theater"), fieldOf(source, "City"))], ["date", v.dateDot]),
|
||||
Art: art,
|
||||
DocumentFromInternetSite: (v, source) =>
|
||||
spaced(
|
||||
["author", v.authorDot],
|
||||
["title", quotedDot(v.title)],
|
||||
["version", v.prefixVersionDot],
|
||||
["date", v.dateDot],
|
||||
["site", italic(appendDot(fieldOf(source, "InternetSiteTitle")))],
|
||||
["editor", v.prefixEditorDot],
|
||||
["producer", v.prodDot],
|
||||
),
|
||||
InternetSite: (v) =>
|
||||
spaced(
|
||||
["author", v.authorDot],
|
||||
["title", italicDot(v.title)],
|
||||
["editor", v.prefixEditorDot],
|
||||
["version", v.prefixVersionDot],
|
||||
["date", v.dateDot],
|
||||
["producer", v.prodDot],
|
||||
),
|
||||
Patent: (v, source) => {
|
||||
const patentNumber = fieldOf(source, "PatentNumber");
|
||||
return spaced(
|
||||
["inventor", v.inventorLFDot],
|
||||
["title", v.titleDot],
|
||||
["editor", v.prefixEditorDot],
|
||||
["translator", v.prefixTranslatorDot],
|
||||
[
|
||||
"country",
|
||||
templateB(fieldOf(source, "CountryRegion"), patentNumber ? textOf(stringFormat(Strings.PatentCap, patentNumber)) : ""),
|
||||
],
|
||||
["date", v.dateDot],
|
||||
);
|
||||
},
|
||||
Case: (v, source) =>
|
||||
spaced(
|
||||
["title", v.titleDot],
|
||||
["number", v.prefixCaseNoDot],
|
||||
["court", appendDot(fieldOf(source, "Court"))],
|
||||
["place", templateB(fieldOf(source, "City"), dateOf(source))],
|
||||
),
|
||||
Misc: (v, source) =>
|
||||
spaced(
|
||||
["author", v.authorDot],
|
||||
["title", quotedDot(v.title)],
|
||||
["publication", italicDot(fieldOf(source, "PublicationTitle"))],
|
||||
["volume", v.prefixVolumeDot],
|
||||
["issue", appendDot(fieldOf(source, "Issue"))],
|
||||
["editor", v.prefixEditorDot],
|
||||
["translator", v.prefixTranslatorDot],
|
||||
["compiler", v.prefixCompilerDot],
|
||||
["place", v.tempCPD],
|
||||
["pages", v.pagesDot],
|
||||
),
|
||||
ElectronicSource: electronicSource,
|
||||
ArticleInAPeriodical: (v, source) => {
|
||||
const edition = fieldOf(source, "Edition");
|
||||
return spaced(
|
||||
["author", v.authorDot],
|
||||
["title", quotedDot(v.title)],
|
||||
["periodical", italic(fieldOf(source, "PeriodicalTitle"))],
|
||||
// templateDEP
|
||||
[
|
||||
"date",
|
||||
templateE(
|
||||
dateOf(source),
|
||||
edition ? textOf(stringFormat(Strings.EditionShortUnCap, edition)) : "",
|
||||
fieldOf(source, "Pages"),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
Film: (v, source) =>
|
||||
spaced(
|
||||
...titleAndPeople(v),
|
||||
["producer", v.prefixProdDot],
|
||||
["distributor", templateC(fieldOf(source, "Distributor"), yearOf(source))],
|
||||
),
|
||||
Interview: interview,
|
||||
};
|
||||
|
||||
/** The title a type of source has in a citation when it has neither a short title nor a title */
|
||||
const CITATION_TITLES: Readonly<Partial<Record<WordSourceType, Field>>> = {
|
||||
BookSection: "BookTitle",
|
||||
ArticleInAPeriodical: "PeriodicalTitle",
|
||||
InternetSite: "InternetSiteTitle",
|
||||
DocumentFromInternetSite: "InternetSiteTitle",
|
||||
ElectronicSource: "PublicationTitle",
|
||||
Art: "PublicationTitle",
|
||||
Misc: "PublicationTitle",
|
||||
SoundRecording: "AlbumTitle",
|
||||
Interview: "BroadcastTitle",
|
||||
};
|
||||
|
||||
/** A source's title in a citation: its short title, or its title, or for most types another title it has (`populateMain`) */
|
||||
const citationTitleOf = (source: WordSource): string => {
|
||||
const other = CITATION_TITLES[source.type];
|
||||
return fieldOf(source, "ShortTitle") || fieldOf(source, "Title") || (other ? fieldOf(source, other) : "");
|
||||
};
|
||||
|
||||
/**
|
||||
* The people a source is named by in a citation: the last names of the first three, with their initials when another
|
||||
* source's first author has the same last name, or the organization
|
||||
*/
|
||||
const citationAuthorsOf = (names: WordNames | undefined, nonUniqueLastName: boolean): string => {
|
||||
if (!names) {
|
||||
return "";
|
||||
}
|
||||
if ("corporate" in names) {
|
||||
return names.corporate;
|
||||
}
|
||||
const count = names.people.length;
|
||||
return names.people
|
||||
.map((person, index) => {
|
||||
const position = index + 1;
|
||||
const name = position > 3 ? "" : formatName(person, nonUniqueLastName ? MLA.CitationLong : MLA.CitationShort);
|
||||
const separator =
|
||||
(count - 1 === position && (count === 2 || count === 3)) || (count > 3 && position === 2)
|
||||
? SPACE + Strings.AndUnCap + SPACE
|
||||
: count > position && position < 3
|
||||
? General.AuthorsSeparator
|
||||
: "";
|
||||
return name + separator;
|
||||
})
|
||||
.join("");
|
||||
};
|
||||
|
||||
/**
|
||||
* A source of a citation, such as "(Baker 50)": its authors, its title when they don't tell it apart from another
|
||||
* source or it has none, and the volume and pages cited
|
||||
*/
|
||||
const citation = (cited: CitedSource): FormattedText => {
|
||||
const { source, volume, pages } = cited;
|
||||
const title0 = citationTitleOf(source);
|
||||
const author0 = citationAuthorsOf(mainContributorsOf(source), cited.nonUniqueLastName);
|
||||
const author = cited.hideAuthor ? "" : author0;
|
||||
const title = cited.hideTitle ? "" : title0;
|
||||
const displayTitle = !author || cited.repeatedAuthor ? title : "";
|
||||
const volVolume = volume
|
||||
? textOf(stringFormat(volumeFormatOf(volume, Strings.VolumeShortUnCap, Strings.VolumesShortUnCap), volume))
|
||||
: "";
|
||||
return join(
|
||||
cited.first ? General.OpenBracket : "",
|
||||
cited.prefix ?? "",
|
||||
author,
|
||||
displayTitle ? (author ? LIST : "") + displayTitle : "",
|
||||
!author0 && !title0 ? source.tag : "",
|
||||
volume || pages
|
||||
? (author || displayTitle ? SPACE : "") + (volume && pages ? volume + General.Enum + pages : volVolume || pages)
|
||||
: "",
|
||||
cited.suffix ?? "",
|
||||
cited.last ? General.CloseBracket : General.GroupSeparator,
|
||||
);
|
||||
};
|
||||
|
||||
/** What the bibliography is sorted by: the source's authors and its title, or its title first for some types (`b:SortingString`) */
|
||||
const sortingStringOf = (source: WordSource): string => {
|
||||
const author = personsAuthor(mainContributorsOf(source));
|
||||
const title = fieldOf(source, "Title");
|
||||
const titleFirst = source.type === "Performance" || source.type === "Case" || source.type === "Film";
|
||||
return (titleFirst && title ? SPACE + title : "") + (author ? SPACE + author : "") + (!titleFirst && title ? SPACE + title : "");
|
||||
};
|
||||
|
||||
/**
|
||||
* A bibliography of the sources, sorted, each entry with its medium, the date it was read and its address after it, and
|
||||
* "—" for its author when the entry before is named by the same people
|
||||
*/
|
||||
const bibliography = (sources: readonly WordSource[]): FormattedBibliography => {
|
||||
const sorted = sortByKey(sources, sortingStringOf);
|
||||
// The people each source is named by, which the style keeps in its `dups` variable
|
||||
const mains = sorted.map((source) => personsAuthor(mainContributorsOf(source)));
|
||||
return {
|
||||
hangingIndent: true,
|
||||
paragraphs: sorted.map((source, index) => {
|
||||
const author =
|
||||
index > 0 && mains[index] !== "" && mains[index] === mains[index - 1] ? MLA.SameAuthor : personsAuthor(source.names.Author);
|
||||
const entry = ENTRIES[source.type](variablesOf(source, author), source);
|
||||
const after = templateMDaU(source);
|
||||
// Word's XSLT writes a line break after the copy of an entry, which Word reads as a space after one that ends
|
||||
// with italics, at the end of its paragraph
|
||||
const space = !after && entry[entry.length - 1]?.italics ? SPACE : "";
|
||||
return join(entry, textOf(entry) && after ? SPACE : "", after, space);
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
/** MLA, as Word writes it with MLASeventhEditionOfficeOnline.xsl */
|
||||
export const mla: StyleDefinition = {
|
||||
name: "MLA",
|
||||
file: "MLASeventhEditionOfficeOnline.xsl",
|
||||
version: "7",
|
||||
citation,
|
||||
bibliography,
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { describeWordOutput, markupOf } from "tests/bibliography";
|
||||
|
||||
import expected from "./fixtures/sist02.json";
|
||||
import { sist02 } from "./sist02";
|
||||
import { formatBibliography } from "../format";
|
||||
import type { Source } from "../source";
|
||||
import { wordSourceOf } from "../word-source";
|
||||
|
||||
const paragraphsOf = (sources: readonly Source[]): readonly string[] => {
|
||||
const bibliography = formatBibliography(
|
||||
sist02,
|
||||
sources.map((source, index) => wordSourceOf(source, index + 1)),
|
||||
);
|
||||
return "paragraphs" in bibliography ? bibliography.paragraphs.map(markupOf) : [];
|
||||
};
|
||||
|
||||
describe("sist02", () => {
|
||||
describeWordOutput(sist02, expected);
|
||||
|
||||
// Expected values from Word's style, run with libxslt and Word's English wording, read as Word reads its HTML
|
||||
describe("where Word reads its HTML", () => {
|
||||
it("writes a space between two elements that follow each other, even when the first is empty", () => {
|
||||
expect(paragraphsOf([{ tag: "Cp", type: "conferenceProceedings", title: "Short Paper", conferenceName: "Bake Con" }])).toEqual([
|
||||
"<i>Short Paper.</i> Bake Con.",
|
||||
]);
|
||||
});
|
||||
|
||||
// As Word for Mac shows "<b>MoraLuz</b> <i>Bread.</i>" in corpus b, where libxslt's output has a space after it
|
||||
it("writes no space at the end of an entry", () => {
|
||||
expect(
|
||||
paragraphsOf([
|
||||
{ tag: "M1", type: "miscellaneous", authors: [{ lastName: "Lee", firstName: "Ann" }] },
|
||||
{ tag: "M2", type: "miscellaneous", authors: [{ lastName: "Lee", firstName: "Ann" }] },
|
||||
]),
|
||||
).toEqual(["<b>LeeAnn</b>", "<b>—.</b>"]);
|
||||
});
|
||||
});
|
||||
|
||||
// Expected values from Word's style, run with libxslt and Word's English wording
|
||||
describe("where its template doesn't do what it means to", () => {
|
||||
it("writes the date a website was accessed only when it has the day, and then even with no year", () => {
|
||||
expect(
|
||||
paragraphsOf([
|
||||
{ tag: "W1", type: "website", title: "Page One", yearAccessed: 2020, monthAccessed: "May" },
|
||||
{ tag: "W2", type: "website", title: "Page Two", dayAccessed: 3 },
|
||||
]),
|
||||
).toEqual(["Page One.[Online]", "Page Two.[Online][Cited: ]"]);
|
||||
});
|
||||
|
||||
it("writes a dash for an article's title when the article before has the same title, though its authors differ", () => {
|
||||
expect(
|
||||
paragraphsOf([
|
||||
{ tag: "J1", type: "journalArticle", title: "Same", authors: [{ lastName: "Lee", firstName: "Ann" }], year: 2001 },
|
||||
{ tag: "J2", type: "journalArticle", title: "Same", authors: [{ lastName: "Ray", firstName: "Bob" }], year: 2002 },
|
||||
]),
|
||||
).toEqual(["<i>Same.</i> <b>LeeAnn</b>2001.", "<i>—.</i> <b>RayBob</b>2002."]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,566 @@
|
||||
/**
|
||||
* Word's SIST02 style (SIST02.XSL), which writes citations and bibliographies as the Japanese standard SIST 02 has them,
|
||||
* with full-width punctuation: citations such as "(Baker,2010p.50)", and a bibliography of entries such as
|
||||
* "**SmithJohn, JonesMaryAnn** *Dough and Fire.*London,Crust Books,2011.", sorted by their authors.
|
||||
*
|
||||
* The style writes its own punctuation in place of Word's: full-width commas, dots and brackets, and nothing for a space,
|
||||
* so names and the parts of an entry are written one after another. Word reads a space between two of its bold or italic
|
||||
* elements that follow each other, as it does in each of the styles that write them.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type FormattedText, bold, formatted, italic, join, textOf } from "./formatted-text";
|
||||
import { LOCALS, type NamePatterns } from "./locals";
|
||||
import type { CitedSource, FormattedBibliography, StyleDefinition } from "./style";
|
||||
import { type Punctuation, sortByKey, translate, xslTemplates } from "./xsl";
|
||||
import { type Field, type Role, type WordNames, type WordPerson, type WordSource, type WordSourceType, fieldOf } from "../word-source";
|
||||
|
||||
const { General, ISO690, SIST, Strings } = LOCALS;
|
||||
|
||||
// The style's punctuation, which it writes itself rather than reading Word's. Its spaces, the separator of a group and
|
||||
// the dot after an initial are empty
|
||||
const DOT = ".";
|
||||
const LIST_SEPARATOR = ",";
|
||||
const ENUM = ",";
|
||||
const OPEN_BRACKET = "(";
|
||||
const CLOSE_BRACKET = ")";
|
||||
|
||||
const PUNCTUATION: Punctuation = {
|
||||
Dot: DOT,
|
||||
DotInitial: "",
|
||||
EndChars: General.EndChars,
|
||||
Hyphens: General.Hyphens,
|
||||
ListSeparator: LIST_SEPARATOR,
|
||||
GroupSeparator: "",
|
||||
SimpleAuthor: General.SimpleAuthor,
|
||||
SimpleDate: General.SimpleDate,
|
||||
};
|
||||
const xsl = xslTemplates(PUNCTUATION);
|
||||
|
||||
/** The names of the people a source is named by, last name first: the style's own, which are Word's (`SIST_MainAuthors`) */
|
||||
const MAIN_AUTHORS: NamePatterns = { FML: "%L%F%M", FM: "%F%M", ML: "%L%M", FL: "%L%F" };
|
||||
|
||||
/** The names of the other people: the style's own (`SIST_SecondaryAuthors`), with a middle name before a first name */
|
||||
const SECONDARY_AUTHORS: NamePatterns = { FML: "%L%M%F", FM: "%M%F", ML: "%L%M", FL: "%L%F" };
|
||||
|
||||
/** The name of the first person in a citation: the last name, or the first name of someone who has no last name */
|
||||
const CITATION_AUTHOR: NamePatterns = {
|
||||
FML: General.SimpleAuthor.L,
|
||||
FM: General.SimpleAuthor.F,
|
||||
ML: General.SimpleAuthor.L,
|
||||
FL: General.SimpleAuthor.L,
|
||||
};
|
||||
|
||||
/** The roles a type of source is named by, in the order they're looked for (`MainContributors`) */
|
||||
const MAIN_ROLES: Readonly<Record<WordSourceType, readonly Role[]>> = {
|
||||
Book: ["Author", "Editor", "Translator"],
|
||||
BookSection: ["Author"],
|
||||
JournalArticle: ["Author", "Editor"],
|
||||
ArticleInAPeriodical: ["Author"],
|
||||
ConferenceProceedings: ["Author", "Editor"],
|
||||
Report: ["Author"],
|
||||
SoundRecording: ["Artist", "Performer", "Composer", "Conductor", "ProducerName"],
|
||||
Performance: ["Writer", "Director", "Performer", "ProducerName"],
|
||||
Art: ["Artist"],
|
||||
DocumentFromInternetSite: ["Author"],
|
||||
InternetSite: ["Author"],
|
||||
Film: ["Director", "Writer", "Performer", "ProducerName"],
|
||||
Interview: ["Interviewee"],
|
||||
Patent: ["Inventor"],
|
||||
ElectronicSource: ["Author", "Editor", "ProducerName", "Translator"],
|
||||
Case: ["Author", "Counsel"],
|
||||
Misc: ["Author", "Editor", "Compiler", "Translator"],
|
||||
};
|
||||
|
||||
/**
|
||||
* What the people a source is named by are, after their names, such as "[ed.]", by their role (`GetMainAuthorTitle`).
|
||||
* The template means to write the plural for more than one person, but its test of whether they are an organization
|
||||
* is always true, so it writes the singular
|
||||
*/
|
||||
const MAIN_AUTHOR_TITLES: Readonly<Partial<Record<Role, string>>> = {
|
||||
Editor: Strings.EditorShortUnCap,
|
||||
Translator: Strings.TranslatorShortUnCap,
|
||||
Performer: Strings.PerformerShortUnCap,
|
||||
Composer: Strings.ComposerShortUnCapIso,
|
||||
Conductor: Strings.ConductorShortUnCap,
|
||||
ProducerName: Strings.ProducerShortUnCap,
|
||||
Writer: Strings.WriterShortUnCap,
|
||||
Counsel: Strings.CounselShortUnCap,
|
||||
Compiler: Strings.CompilerShortUnCap,
|
||||
};
|
||||
|
||||
/** The types whose entries start with their titles in italics, and whose citations name them by their titles */
|
||||
const isTitledFirst = (type: WordSourceType): boolean => type === "JournalArticle" || type === "ConferenceProceedings";
|
||||
|
||||
/** The string value of the people with a role, or the organization: their names one after another, as XPath reads it */
|
||||
const stringOf = (names: WordNames): string =>
|
||||
"corporate" in names ? names.corporate : names.people.map(({ last, first, middle }) => last + first + middle).join("");
|
||||
|
||||
/** The people or organization a source is named by, and their role (`b:Author/b:Main` and `b:MainAuthorType`) */
|
||||
type Main = { readonly role: Role; readonly names: WordNames };
|
||||
|
||||
/**
|
||||
* The people or organization a source is named by: those of the first of its type's roles it has a name in
|
||||
* (`MainContributors` and `populateMain`), if it has any
|
||||
*/
|
||||
const mainOf = (source: WordSource): Main | undefined =>
|
||||
MAIN_ROLES[source.type].flatMap((role) => {
|
||||
const names = source.names[role];
|
||||
return names !== undefined && stringOf(names).length > 0 ? [{ role, names }] : [];
|
||||
})[0];
|
||||
|
||||
/** The string value of the people or organization a source is named by, or "" (`b:Author/b:Main`) */
|
||||
const mainStringOf = (source: WordSource): string => {
|
||||
const main = mainOf(source);
|
||||
return main === undefined ? "" : stringOf(main.names);
|
||||
};
|
||||
|
||||
/**
|
||||
* The separator after a person of a list of people (`formatPersonSeparator`): "et al." after the first of four or more,
|
||||
* and a comma between the others
|
||||
*/
|
||||
const formatPersonSeparator = (position: number, count: number): string =>
|
||||
count > 3 ? Strings.AndOthersUnCap : count > position ? General.AuthorsSeparator : "";
|
||||
|
||||
/** People with a role, or the organization that has it (`formatPersons`). Of four or more people, only the first is written */
|
||||
const formatPersons = (names: WordNames, patterns: NamePatterns): string => {
|
||||
if ("corporate" in names) {
|
||||
return names.corporate;
|
||||
}
|
||||
const count = names.people.length;
|
||||
const shown: readonly WordPerson[] = count >= 4 ? names.people.slice(0, 1) : names.people;
|
||||
return shown.map((person, index) => xsl.formatName(person, patterns) + formatPersonSeparator(index + 1, count)).join("");
|
||||
};
|
||||
|
||||
/**
|
||||
* The people a source is named by, last name first, and what they are, such as "GarciaLucia, NguyenBao,[ed.]"
|
||||
* (`formatMain`)
|
||||
*/
|
||||
const formatMain = (source: WordSource): string => {
|
||||
const main = mainOf(source);
|
||||
if (main === undefined) {
|
||||
return "";
|
||||
}
|
||||
const title = main.role === "Writer" && source.type !== "Film" ? "" : (MAIN_AUTHOR_TITLES[main.role] ?? "");
|
||||
return formatPersons(main.names, MAIN_AUTHORS) + (title ? LIST_SEPARATOR + SIST.GeneralOpen + title + SIST.GeneralClose : "");
|
||||
};
|
||||
|
||||
/** The volume, such as "Vol. 3", or "Vols. 2-3" for more than one */
|
||||
const formatVolume = (volume: string, single: string, plural: string): string => {
|
||||
if (volume.length === 0) {
|
||||
return "";
|
||||
}
|
||||
const format = volume.includes(",") ? plural : translate(volume, General.Hyphens, "") === volume ? single : plural;
|
||||
return textOf(xsl.stringFormat(format, volume));
|
||||
};
|
||||
|
||||
/** The pages, such as "p.5", or "pp.10-20" for more than one */
|
||||
const formatPages = (pages: string): string => {
|
||||
if (pages.length === 0) {
|
||||
return "";
|
||||
}
|
||||
const prefix = pages.includes(",")
|
||||
? Strings.PagesCountinousShort
|
||||
: translate(pages, General.Hyphens, "") === pages
|
||||
? Strings.PageShort
|
||||
: Strings.PagesCountinousShort;
|
||||
return prefix + pages;
|
||||
};
|
||||
|
||||
/** Parts with a comma between them, each written only when it isn't empty, and a dot after them (`templateC` and `templateJ`) */
|
||||
const formatParts = (...parts: readonly string[]): string => xsl.appendDot(parts.filter((part) => part.length > 0).join(LIST_SEPARATOR));
|
||||
|
||||
/** Text in a bold or italic element of the style's HTML */
|
||||
type Element = { readonly tag: "b" | "i"; readonly text: string };
|
||||
|
||||
/** What the style writes into an entry: text, or text in an element, which Word reads a space before when it follows another */
|
||||
type Node = string | Element;
|
||||
|
||||
const boldElement = (text: string): Element => ({ tag: "b", text });
|
||||
|
||||
/** Text in italics (`ApplyItalicTitleNS` and `ApplyItalicFieldNS`), which the style writes as an element even when empty */
|
||||
const italicElement = (text: string): Element => ({ tag: "i", text });
|
||||
|
||||
/** Text in italics, or nothing when it is empty, as the style's variables of titles write it */
|
||||
const italicUnlessEmpty = (text: string): readonly Node[] => (text ? [italicElement(text)] : []);
|
||||
|
||||
const SPACE_BETWEEN_ELEMENTS: FormattedText = [{ text: " " }];
|
||||
|
||||
/**
|
||||
* An entry, as Word reads the style's HTML of it: with a space between two elements that follow each other, even when
|
||||
* the first is empty, as Word's XSLT processor writes a line break between them. Word doesn't read one at the end of the
|
||||
* paragraph
|
||||
*/
|
||||
const paragraphOf = (nodes: readonly Node[]): FormattedText => {
|
||||
const parts = nodes
|
||||
.filter((node) => node !== "")
|
||||
.flatMap((node, index, written) =>
|
||||
typeof node === "string"
|
||||
? [formatted(node)]
|
||||
: [
|
||||
...(typeof written[index - 1] === "object" ? [SPACE_BETWEEN_ELEMENTS] : []),
|
||||
node.tag === "b" ? bold(node.text) : italic(node.text),
|
||||
],
|
||||
)
|
||||
.filter((part) => part.length > 0);
|
||||
return join(...(parts[parts.length - 1] === SPACE_BETWEEN_ELEMENTS ? parts.slice(0, -1) : parts));
|
||||
};
|
||||
|
||||
/**
|
||||
* Where a source was published and by whom, such as "London,Crust Books", with "s.l." or "s.n." for one that's missing
|
||||
* (`formatLocation`). A source of most types with neither has nothing
|
||||
*/
|
||||
const formatLocation = (type: WordSourceType, field: (name: Field) => string): string => {
|
||||
if (type === "Film") {
|
||||
// The style's separator of a group, between them, is empty
|
||||
return field("ProductionCompany") + field("Distributor");
|
||||
}
|
||||
if (type === "Patent") {
|
||||
return field("CountryRegion");
|
||||
}
|
||||
if (type === "DocumentFromInternetSite" || type === "InternetSite") {
|
||||
return "";
|
||||
}
|
||||
const published = [
|
||||
"Book",
|
||||
"BookSection",
|
||||
"JournalArticle",
|
||||
"ArticleInAPeriodical",
|
||||
"ConferenceProceedings",
|
||||
"Interview",
|
||||
"Report",
|
||||
"Misc",
|
||||
].includes(type);
|
||||
const hasPlace = field("City") !== "" || (type === "Performance" && field("Theater") !== "");
|
||||
const hasPublisher =
|
||||
(type === "Report" && field("Publisher") !== "") ||
|
||||
(type === "Art" && field("Institution") !== "") ||
|
||||
((type === "SoundRecording" || type === "Performance") && field("ProductionCompany") !== "") ||
|
||||
(type === "ElectronicSource" && (field("ProductionCompany") !== "" || field("Publisher") !== "")) ||
|
||||
(type === "Case" && field("Court") !== "") ||
|
||||
((field("Publisher") !== "" || (type === "Interview" && field("Broadcaster") !== "")) && (published || type === "Art"));
|
||||
if (!hasPlace && !hasPublisher) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const before = (prefixType: WordSourceType, prefix: Field): string =>
|
||||
type === prefixType ? field(prefix) + (field(prefix) !== "" && field("City") !== "" ? LIST_SEPARATOR : "") : "";
|
||||
const place = hasPlace
|
||||
? before("Performance", "Theater") +
|
||||
before("ElectronicSource", "Edition") +
|
||||
before("Interview", "Station") +
|
||||
(type === "Art" && field("Institution") !== "" && field("City") !== "" ? LIST_SEPARATOR : "") +
|
||||
field("City")
|
||||
: (type === "Art" && field("Institution") !== "" ? LIST_SEPARATOR : "") + Strings.SineLocoShort;
|
||||
const region = ["Performance", "Art", "ElectronicSource", "Case", "Misc"].includes(type)
|
||||
? (field("StateProvince") !== "" || field("CountryRegion") !== "" ? LIST_SEPARATOR : "") +
|
||||
[field("StateProvince"), field("CountryRegion")].filter((part) => part !== "").join(LIST_SEPARATOR)
|
||||
: "";
|
||||
|
||||
const both = (first: Field, second: Field): string => [field(first), field(second)].filter((part) => part !== "").join(LIST_SEPARATOR);
|
||||
const after =
|
||||
type === "Report" && field("Publisher") !== ""
|
||||
? field("Publisher")
|
||||
: (type === "SoundRecording" || type === "Performance") && field("ProductionCompany") !== ""
|
||||
? field("ProductionCompany")
|
||||
: type === "ElectronicSource" && (field("ProductionCompany") !== "" || field("Publisher") !== "")
|
||||
? both("Publisher", "ProductionCompany")
|
||||
: type === "Case" && field("Court") !== ""
|
||||
? field("Court")
|
||||
: type === "Art" && (field("Publisher") !== "" || field("Year") !== "")
|
||||
? both("Publisher", "Year")
|
||||
: published && (field("Publisher") !== "" || (type === "Interview" && field("Broadcaster") !== ""))
|
||||
? (type === "Interview" ? field("Broadcaster") : "") + field("Publisher")
|
||||
: type === "Interview" && field("Broadcaster") === ""
|
||||
? ""
|
||||
: Strings.SineNomineShort;
|
||||
|
||||
// The style writes a non-breaking space before the separator, which is empty
|
||||
return (type === "Art" ? field("Institution") : "") + place + region + (/[^ \t\r\n]/.test(after) ? LIST_SEPARATOR + after : "");
|
||||
};
|
||||
|
||||
/**
|
||||
* A source's entry in the bibliography (the `b:Bibliography` part of the template that matches `/`): its title in
|
||||
* italics, for an article, then the people it's named by in bold, or "—." when they're the ones of the entry before,
|
||||
* then the rest of it, by its type, each part ending with a dot.
|
||||
*
|
||||
* @param previous - The entry before it in the bibliography, if it has one
|
||||
*/
|
||||
const formatEntry = (source: WordSource, previous: WordSource | undefined): FormattedText => {
|
||||
const { type } = source;
|
||||
// populateMain leaves out an interview's editors, translators, compilers and publisher when it was broadcast, and
|
||||
// its station when it wasn't
|
||||
const broadcast = type === "Interview" && (fieldOf(source, "Broadcaster") !== "" || fieldOf(source, "BroadcastTitle") !== "");
|
||||
const field = (name: Field): string =>
|
||||
type === "Interview" && name === (broadcast ? "Publisher" : "Station") ? "" : fieldOf(source, name);
|
||||
const namesOf = (role: Role): WordNames | undefined =>
|
||||
broadcast && (role === "Editor" || role === "Translator" || role === "Compiler") ? undefined : source.names[role];
|
||||
|
||||
const mainString = mainStringOf(source);
|
||||
/**
|
||||
* The people with a role, and the role, such as "HemingwayErnested.." (`formatEditor`, `formatTranslator` and the
|
||||
* like), unless they're the people the source is named by
|
||||
*/
|
||||
const formatRole = (role: Role, label: string): string => {
|
||||
const names = namesOf(role);
|
||||
return names !== undefined && stringOf(names) !== mainString && stringOf(names).length > 0
|
||||
? formatPersons(names, SECONDARY_AUTHORS) + label + DOT
|
||||
: "";
|
||||
};
|
||||
const editors = formatRole("Editor", Strings.EditorShortUnCap);
|
||||
const translators = formatRole("Translator", Strings.TranslatorShortUnCap);
|
||||
const bookAuthors = formatRole("BookAuthor", Strings.BookAuthorShortUnCap);
|
||||
const compilers = formatRole("Compiler", Strings.CompilerShortUnCapIso);
|
||||
const composers = formatRole("Composer", Strings.ComposerShortUnCapIso);
|
||||
const conductors = formatRole("Conductor", Strings.ConductorShortUnCap);
|
||||
const counsel = formatRole("Counsel", Strings.CounselShortUnCap);
|
||||
const directors = formatRole("Director", Strings.DirectorShortUnCap);
|
||||
const performers = formatRole("Performer", Strings.PerformerShortUnCap);
|
||||
const producers = formatRole("ProducerName", Strings.ProducerShortUnCap);
|
||||
const writers = formatRole("Writer", Strings.WriterShortUnCap);
|
||||
// The interviewers, and the abbreviation for an interviewee, which `formatInterviewer` writes when there are interviewees
|
||||
const interviewerNames = namesOf("Interviewer");
|
||||
const interviewers =
|
||||
interviewerNames !== undefined &&
|
||||
stringOf(interviewerNames) !== mainString &&
|
||||
stringOf(namesOf("Interviewee") ?? { people: [] }) !== ""
|
||||
? formatPersons(interviewerNames, SECONDARY_AUTHORS) + Strings.IntervieweeShortUnCap + DOT
|
||||
: "";
|
||||
|
||||
const location = formatLocation(type, field);
|
||||
const date = xsl.formatDatePrivate(field("Day"), field("Month"), field("Year"), SIST.Date);
|
||||
// `formatDayMonthYearAccessed` looks for the day it was accessed, three times, rather than for each part of the date
|
||||
const accessed = field("DayAccessed")
|
||||
? SIST.GeneralOpen +
|
||||
textOf(
|
||||
xsl.stringFormatDot(
|
||||
Strings.CitedCap,
|
||||
xsl.formatDatePrivate(field("DayAccessed"), field("MonthAccessed"), field("YearAccessed"), SIST.DateAccessed),
|
||||
),
|
||||
) +
|
||||
SIST.GeneralClose
|
||||
: "";
|
||||
const volume = formatVolume(field("Volume"), Strings.VolumeShortCap, Strings.VolumesShortCap);
|
||||
const pages = formatPages(field("Pages"));
|
||||
const ended = (name: Field): string => (field(name) ? field(name) + DOT : "");
|
||||
const comments = ended("Comments");
|
||||
const standardNumber = field("StandardNumber") ? OPEN_BRACKET + field("StandardNumber") + CLOSE_BRACKET + DOT : "";
|
||||
const url = ended("URL");
|
||||
const medium = field("Medium") ? SIST.GeneralOpen + field("Medium") + SIST.GeneralClose : "";
|
||||
const mediumDot = medium && medium + DOT;
|
||||
const title = xsl.appendDot(field("Title"));
|
||||
const italicTitle = italicUnlessEmpty(title);
|
||||
const italicField = (name: Field): readonly Node[] => italicUnlessEmpty(xsl.appendDot(field(name)));
|
||||
const internetSiteTitle: readonly Node[] = [
|
||||
...italicField("InternetSiteTitle"),
|
||||
SIST.GeneralOpen + Strings.OnlineCap + SIST.GeneralClose,
|
||||
];
|
||||
const versionAndDate = formatParts(field("Version"), type === "InternetSite" ? field("ProductionCompany") : "", date);
|
||||
const printList = (...items: readonly string[]): string => textOf(xsl.printList(items));
|
||||
|
||||
// Each type's own parts, after the people it's named by
|
||||
const sectionsOf: Readonly<Record<WordSourceType, () => readonly Node[]>> = {
|
||||
Book: () => [
|
||||
...italicTitle,
|
||||
editors,
|
||||
translators,
|
||||
printList(location, field("Edition"), field("Year"), volume, pages),
|
||||
comments,
|
||||
standardNumber,
|
||||
],
|
||||
BookSection: () => [
|
||||
title,
|
||||
bookAuthors,
|
||||
editors,
|
||||
translators,
|
||||
...italicField("BookTitle"),
|
||||
printList(location, field("Year"), field("Edition"), volume, pages),
|
||||
comments,
|
||||
],
|
||||
JournalArticle: () => [
|
||||
editors,
|
||||
field("Issue") && field("Issue") + LIST_SEPARATOR,
|
||||
printList(location, date, field("JournalName"), volume, pages),
|
||||
comments,
|
||||
standardNumber,
|
||||
],
|
||||
ArticleInAPeriodical: () => [
|
||||
title,
|
||||
editors,
|
||||
...italicField("PeriodicalTitle"),
|
||||
printList(field("Edition"), date, volume, field("Issue"), pages),
|
||||
comments,
|
||||
],
|
||||
ConferenceProceedings: () => [
|
||||
editors,
|
||||
printList(location, field("Year")),
|
||||
xsl.appendDot(field("ConferenceName")),
|
||||
printList(volume, pages),
|
||||
comments,
|
||||
standardNumber,
|
||||
],
|
||||
Report: () => [
|
||||
...italicTitle,
|
||||
formatParts(field("Department"), field("Institution")),
|
||||
printList(location, field("Year")),
|
||||
printList(pages, field("ThesisType")),
|
||||
comments,
|
||||
standardNumber,
|
||||
],
|
||||
SoundRecording: () => [
|
||||
title,
|
||||
performers,
|
||||
composers,
|
||||
conductors,
|
||||
producers,
|
||||
...italicField("AlbumTitle"),
|
||||
medium,
|
||||
printList(location, field("Year")),
|
||||
comments,
|
||||
standardNumber,
|
||||
],
|
||||
Performance: () => [...italicTitle, directors, performers, producers, printList(location, date), comments, standardNumber],
|
||||
Art: () => [...italicTitle, printList(location), comments],
|
||||
DocumentFromInternetSite: () => [title, ...internetSiteTitle, versionAndDate, accessed, comments, url, standardNumber],
|
||||
// The template writes the text of its title, without its italics
|
||||
InternetSite: () => [title, ...internetSiteTitle, versionAndDate, accessed, comments, url, standardNumber],
|
||||
Film: () => [
|
||||
...italicTitle,
|
||||
mediumDot,
|
||||
writers,
|
||||
performers,
|
||||
producers,
|
||||
printList(location, field("Year")),
|
||||
comments,
|
||||
standardNumber,
|
||||
],
|
||||
Interview: () => [
|
||||
// The text of its title, in italics again when it wasn't broadcast
|
||||
broadcast ? title : italicElement(title),
|
||||
interviewers,
|
||||
editors,
|
||||
translators,
|
||||
compilers,
|
||||
...italicUnlessEmpty(xsl.appendDot(field("BroadcastTitle"))),
|
||||
printList(location, date),
|
||||
printList(pages),
|
||||
comments,
|
||||
standardNumber,
|
||||
],
|
||||
Patent: () => [
|
||||
...italicTitle,
|
||||
...italicUnlessEmpty(field("PatentNumber")),
|
||||
editors,
|
||||
translators,
|
||||
printList(location, date),
|
||||
xsl.appendDot(field("Type")),
|
||||
comments,
|
||||
],
|
||||
ElectronicSource: () => [
|
||||
...italicTitle,
|
||||
medium,
|
||||
editors,
|
||||
producers,
|
||||
translators,
|
||||
printList(location, date),
|
||||
printList(field("PublicationTitle"), xsl.appendDot(volume)),
|
||||
comments,
|
||||
standardNumber,
|
||||
],
|
||||
Case: () => [
|
||||
...italicTitle,
|
||||
field("CaseNumber") && field("CaseNumber") + LIST_SEPARATOR,
|
||||
ended("AbbreviatedCaseNumber"),
|
||||
counsel,
|
||||
printList(location, date),
|
||||
ended("Reporter"),
|
||||
comments,
|
||||
],
|
||||
Misc: () => [
|
||||
title,
|
||||
field("Edition"),
|
||||
editors,
|
||||
compilers,
|
||||
translators,
|
||||
// The text of its publication's title, in an element in italics even when it has none
|
||||
italicElement(xsl.appendDot(field("PublicationTitle"))),
|
||||
mediumDot,
|
||||
printList(location, date),
|
||||
printList(volume, field("Issue"), pages),
|
||||
comments,
|
||||
standardNumber,
|
||||
],
|
||||
};
|
||||
|
||||
// XPath compares the entry before's title and people with this one's only when it has an entry before it
|
||||
const previousTitled = previous !== undefined && isTitledFirst(previous.type);
|
||||
const sameTitle = previousTitled && fieldOf(previous, "Title") !== "" && fieldOf(previous, "Title") === field("Title");
|
||||
const sameMain = previous !== undefined && mainStringOf(previous) === mainString;
|
||||
const head: readonly Node[] = [
|
||||
...(isTitledFirst(type) ? [italicElement(sameTitle ? ISO690.SameAuthor + DOT : title)] : []),
|
||||
boldElement(previousTitled || isTitledFirst(type) || !sameMain ? formatMain(source) : mainString && SIST.SameAuthor + DOT),
|
||||
];
|
||||
return paragraphOf([...head, ...sectionsOf[type]()]);
|
||||
};
|
||||
|
||||
/** What the bibliography is sorted by (`b:SortingString`, as `populateMain` writes it): the authors, with the title */
|
||||
const sortingStringOf = (source: WordSource): string => {
|
||||
const main = mainOf(source);
|
||||
const author = main === undefined ? "" : formatPersons(main.names, MAIN_AUTHORS);
|
||||
const title = fieldOf(source, "Title");
|
||||
const titledFirst = isTitledFirst(source.type);
|
||||
return (titledFirst && title ? ` ${title}` : "") + (author ? ` ${author}` : "") + (!titledFirst && title ? ` ${title}` : "");
|
||||
};
|
||||
|
||||
/**
|
||||
* A source of a citation (the `b:Citation` part of the template that matches `/`), such as "(Baker,2010p.50)": the last
|
||||
* name of the first of the people it's named by, with "et al." when there are more, or an article's title, its year,
|
||||
* and the volume or pages cited. It is its tag when it has neither a name nor a year
|
||||
*/
|
||||
const formatCitation = ({ source, first, last, hideAuthor, hideYear, pages, volume, prefix, suffix }: CitedSource): FormattedText => {
|
||||
const main = mainOf(source);
|
||||
const title = fieldOf(source, "Title");
|
||||
const author0 =
|
||||
isTitledFirst(source.type) && title
|
||||
? title
|
||||
: main === undefined
|
||||
? ""
|
||||
: "corporate" in main.names
|
||||
? main.names.corporate
|
||||
: xsl.formatName(main.names.people[0], CITATION_AUTHOR) + (main.names.people.length > 1 ? Strings.AndOthersUnCap : "");
|
||||
const year0 = fieldOf(source, "Year");
|
||||
const author = hideAuthor ? "" : author0;
|
||||
const year = hideYear ? "" : year0;
|
||||
return join(
|
||||
first ? OPEN_BRACKET : "",
|
||||
prefix ?? "",
|
||||
author,
|
||||
year ? (author ? LIST_SEPARATOR : "") + year : "",
|
||||
author0 === "" && year0 === "" ? source.tag : "",
|
||||
// The style's space before them is empty
|
||||
volume && pages
|
||||
? volume + ENUM + pages
|
||||
: formatVolume(volume, Strings.VolumeShortUnCap, Strings.VolumesShortUnCap) || formatPages(pages),
|
||||
suffix ?? "",
|
||||
last ? CLOSE_BRACKET : "",
|
||||
);
|
||||
};
|
||||
|
||||
/** The bibliography: each source's entry, sorted by the people it's named by, after the entry before it */
|
||||
const formatBibliography = (sources: readonly WordSource[]): FormattedBibliography => {
|
||||
const sorted = sortByKey(sources, sortingStringOf);
|
||||
return { hangingIndent: false, paragraphs: sorted.map((source, index) => formatEntry(source, sorted[index - 1])) };
|
||||
};
|
||||
|
||||
/**
|
||||
* Word's SIST02 style.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export const sist02: StyleDefinition = {
|
||||
name: "SIST02",
|
||||
file: "SIST02.XSL",
|
||||
version: "2003",
|
||||
citation: formatCitation,
|
||||
bibliography: formatBibliography,
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* What a style of citation is: how it writes a citation of a source, and a bibliography of sources. Each is written from
|
||||
* one of Word's styles, which are XSL, so that a citation or a bibliography `docx` writes is the one Word writes when it
|
||||
* updates the document's fields.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { FormattedText } from "./formatted-text";
|
||||
import type { WordSource } from "../word-source";
|
||||
|
||||
/**
|
||||
* A source a citation cites, as Word gives it to a style (`b:Citation`): the source, where it is in the citation, how
|
||||
* the citation shows it, and what Word works out from the document's other sources.
|
||||
*
|
||||
* A citation of several sources, such as "(Baker, 2010; Evans, 2019)", is written one source at a time, and each style
|
||||
* writes the bracket before the first and after the last, and the separator after the others.
|
||||
*/
|
||||
export type CitedSource = {
|
||||
readonly source: WordSource;
|
||||
/** Whether it is the first source of the citation (`b:FirstAuthor`) */
|
||||
readonly first: boolean;
|
||||
/** Whether it is the last source of the citation (`b:LastAuthor`) */
|
||||
readonly last: boolean;
|
||||
/**
|
||||
* Whether another source has the same first author, or the same first three when it has more than three, so a
|
||||
* citation can't tell them apart by their authors and some styles add the title (`b:RepeatedAuthor`)
|
||||
*/
|
||||
readonly repeatedAuthor: boolean;
|
||||
/**
|
||||
* Whether another source's first author has the same last name, but isn't the same person, so some styles add their
|
||||
* initials (`b:NonUniqueLastName`)
|
||||
*/
|
||||
readonly nonUniqueLastName: boolean;
|
||||
/** How many of its authors tell it apart from the other sources, which Chicago and Turabian show (`b:MinAuthors`) */
|
||||
readonly minAuthors: number;
|
||||
/** Whether the citation leaves out the author (`b:NoAuthor`, the field's `\n`) */
|
||||
readonly hideAuthor: boolean;
|
||||
/** Whether the citation leaves out the year (`b:NoYear`, `\y`) */
|
||||
readonly hideYear: boolean;
|
||||
/** Whether the citation leaves out the title (`b:NoTitle`, `\t`) */
|
||||
readonly hideTitle: boolean;
|
||||
/** The pages cited (`b:Pages`, `\p`), or "" */
|
||||
readonly pages: string;
|
||||
/** The volume cited (`b:Volume`, `\v`), or "" */
|
||||
readonly volume: string;
|
||||
/** Text before the citation of the source (`b:PagePrefix`, `\f`), if it has any */
|
||||
readonly prefix?: string;
|
||||
/** Text after the citation of the source (`b:PageSuffix`, `\s`), if it has any */
|
||||
readonly suffix?: string;
|
||||
};
|
||||
|
||||
/** A bibliography, as a style writes it: a paragraph for each source, or a table of each source's number and entry */
|
||||
export type FormattedBibliography =
|
||||
| {
|
||||
readonly paragraphs: readonly FormattedText[];
|
||||
/** Whether each paragraph's lines after the first are indented half an inch, as APA's are */
|
||||
readonly hangingIndent: boolean;
|
||||
}
|
||||
| {
|
||||
/** Each source's number, such as "[1] ", and its entry */
|
||||
readonly rows: readonly (readonly [FormattedText, FormattedText])[];
|
||||
};
|
||||
|
||||
/** A style of citation, written from one of Word's */
|
||||
// eslint-disable-next-line functional/no-mixed-types -- its names, which the document records, and how it writes
|
||||
export type StyleDefinition = {
|
||||
/** The style's name, as Word lists it and records it in the document (`StyleName`), such as "APA" */
|
||||
readonly name: string;
|
||||
/** The file of Word's style, which Word records in the document (`SelectedStyle`), such as "APASixthEditionOfficeOnline.xsl" */
|
||||
readonly file: string;
|
||||
/** The version of the style Word records in the document (`Version`), such as "6" */
|
||||
readonly version: string;
|
||||
/**
|
||||
* A source of a citation, as the style writes it. The text is read as Word reads a style's HTML, with
|
||||
* {@link readAsWord}, after the citation's sources are joined
|
||||
*/
|
||||
readonly citation: (cited: CitedSource) => FormattedText;
|
||||
/**
|
||||
* A bibliography of the sources, in the order of the document's list of sources, each numbered with the order the
|
||||
* document cites it in. The style sorts them. Each paragraph or cell is read as Word reads a style's HTML
|
||||
*/
|
||||
readonly bibliography: (sources: readonly WordSource[]) => FormattedBibliography;
|
||||
};
|
||||
@@ -0,0 +1,151 @@
|
||||
// cspell:words Turabian
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { describeWordOutput, outputOf } from "tests/bibliography";
|
||||
|
||||
import type { Person } from "../source";
|
||||
import expected from "./fixtures/turabian.json";
|
||||
import { turabian } from "./turabian";
|
||||
|
||||
const people = (prefix: string, count: number): readonly Person[] =>
|
||||
Array.from({ length: count }, (_, index) => ({ lastName: `${prefix}${index + 1}`, firstName: "Al" }));
|
||||
|
||||
describe("turabian", () => {
|
||||
describeWordOutput(turabian, expected);
|
||||
|
||||
// The expected text of these is what Word's own style, TURABIAN.XSL, writes for them
|
||||
describe("as Word's own style writes them", () => {
|
||||
it("lists six authors or editors, but only the first of seven or more, then et al.", () => {
|
||||
expect(
|
||||
outputOf(turabian, {
|
||||
sources: [
|
||||
{
|
||||
tag: "Six",
|
||||
type: "book",
|
||||
authors: people("Author", 6),
|
||||
editors: people("Editor", 6),
|
||||
title: "Few",
|
||||
year: "2001",
|
||||
city: "Rome",
|
||||
publisher: "Press",
|
||||
},
|
||||
{
|
||||
tag: "Seven",
|
||||
type: "book",
|
||||
authors: people("Writer", 7),
|
||||
editors: people("Editor", 7),
|
||||
title: "Crowds",
|
||||
year: "2001",
|
||||
city: "Rome",
|
||||
publisher: "Press",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "Six" }], [{ source: "Seven" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(Author1, et al. 2001)", "(Writer1, et al. 2001)"],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: [
|
||||
"Author1, Al, Al Author2, Al Author3, Al Author4, Al Author5, and Al Author6. <i>Few.</i> Edited by Al Editor1, Al Editor2, Al Editor3, Al Editor4, Al Editor5, & Al Editor6. Rome: Press, 2001.",
|
||||
"Writer1, Al, et al. <i>Crowds.</i> Edited by Al Editor1, et al. Rome: Press, 2001.",
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("writes the producers of an electronic source", () => {
|
||||
expect(
|
||||
outputOf(turabian, {
|
||||
sources: [
|
||||
{
|
||||
tag: "App",
|
||||
type: "electronicSource",
|
||||
authors: people("Maker", 1),
|
||||
title: "App",
|
||||
producers: people("Producer", 2),
|
||||
productionCompany: "Studio",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "App" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(Maker1 n.d.)"],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: ["Maker1, Al. <i>App.</i> Prods. Al Producer1, & Al Producer2. n.d."],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("names a miscellaneous source by its compilers when it has no authors or editors", () => {
|
||||
expect(
|
||||
outputOf(turabian, {
|
||||
sources: [{ tag: "Notes", type: "miscellaneous", compilers: people("Compiler", 2), title: "Notes", year: "2002" }],
|
||||
citations: [[{ source: "Notes" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(Compiler1 and Compiler2 2002)"],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["Compiler1, Al, and Al Compiler2, comps. “Notes.” 2002."] },
|
||||
});
|
||||
});
|
||||
|
||||
it("names an electronic source by its translators, and writes its compilers", () => {
|
||||
expect(
|
||||
outputOf(turabian, {
|
||||
sources: [
|
||||
{
|
||||
tag: "Disc",
|
||||
type: "electronicSource",
|
||||
translators: people("Translator", 1),
|
||||
compilers: people("Compiler", 1),
|
||||
title: "Disc",
|
||||
year: "2003",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "Disc" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(Disc 2003)"],
|
||||
bibliography: { hangingIndent: true, paragraphs: ["Translator1, Al, trans. <i>Disc.</i> Comp. Al Compiler1. 2003."] },
|
||||
});
|
||||
});
|
||||
|
||||
it("writes the editors of an interview after its broadcast, or after its title with its translators", () => {
|
||||
expect(
|
||||
outputOf(turabian, {
|
||||
sources: [
|
||||
{
|
||||
tag: "Talk",
|
||||
type: "interview",
|
||||
interviewees: people("Guest", 1),
|
||||
title: "Talk",
|
||||
broadcastTitle: "Show",
|
||||
editors: people("Editor", 1),
|
||||
year: "2004",
|
||||
},
|
||||
{
|
||||
tag: "Chat",
|
||||
type: "interview",
|
||||
interviewees: people("Guest", 1),
|
||||
title: "Chat",
|
||||
editors: people("Editor", 1),
|
||||
translators: people("Translator", 1),
|
||||
year: "2005",
|
||||
},
|
||||
],
|
||||
citations: [[{ source: "Talk" }], [{ source: "Chat" }]],
|
||||
}),
|
||||
).toEqual({
|
||||
citations: ["(Guest1, Talk 2004)", "(Guest1, Chat 2005)"],
|
||||
bibliography: {
|
||||
hangingIndent: true,
|
||||
paragraphs: [
|
||||
"Guest1, Al. <i>Chat</i>Edited by Al Editor1, translated by Al Translator1. (2005).",
|
||||
"Guest1, Al. “Talk.” <i>Show</i>, edited by Al Editor1. (2004).",
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,784 @@
|
||||
/**
|
||||
* Turabian, the style of Kate Turabian's manual for writers of papers (6th edition), written from Word's own
|
||||
* (TURABIAN.XSL).
|
||||
*
|
||||
* Its citations are Chicago's, and its bibliography is sorted as Chicago's is, but its entries end with where and when
|
||||
* the source was published, rather than having the year after the authors.
|
||||
*
|
||||
* Each function follows the XSL template its description names, including where that doesn't do what it looks like it
|
||||
* should, so citations and bibliographies are written as Word writes them when it updates a document's fields.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
// The names of the XSL's templates and variables, which the functions and variables here keep, such as templateCPY for
|
||||
// the city, the publisher and the year, and its spellings of "sufix" and "Seperator"
|
||||
// cspell:words Turabian TURABIAN CPDMY DACURL RICPY VIYP sufix Sufix Seperator Forno
|
||||
import {
|
||||
bibliographyOf,
|
||||
citation,
|
||||
countOf,
|
||||
formatIf,
|
||||
getYear,
|
||||
normalizeSpace,
|
||||
prefixed,
|
||||
printSpaceAndList,
|
||||
quoted,
|
||||
spaceIf,
|
||||
suffixed,
|
||||
templateA,
|
||||
templateANoDot,
|
||||
templateC,
|
||||
templateCP,
|
||||
templateCityStateProvince,
|
||||
templateE,
|
||||
volumeFormatOf,
|
||||
when,
|
||||
} from "./chicago-family";
|
||||
import { type FormattedRun, type FormattedText, join, textOf } from "./formatted-text";
|
||||
import { LOCALS } from "./locals";
|
||||
import type { FormattedBibliography, StyleDefinition } from "./style";
|
||||
import { applyItalic, xslTemplates } from "./xsl";
|
||||
import { type Field, type Role, type WordNames, type WordSource, type WordSourceType, fieldOf } from "../word-source";
|
||||
|
||||
const { General, Strings, Chicago, APA } = LOCALS;
|
||||
const xsl = xslTemplates(General);
|
||||
|
||||
/**
|
||||
* What comes after a person in a list of a source's authors: a comma, ", and", or "et al." after the first of seven or
|
||||
* more (`formatPersonSeperator`, where English has a comma before "and")
|
||||
*/
|
||||
const formatPersonSeperator = (position: number, count: number): string => {
|
||||
if (count > 6) {
|
||||
return position === 1 ? General.ListSeparator + Strings.AndOthersUnCap : "";
|
||||
}
|
||||
return position === count
|
||||
? ""
|
||||
: position === count - 1
|
||||
? General.ListSeparator + Strings.AndUnCap + General.Space
|
||||
: General.ListSeparator;
|
||||
};
|
||||
|
||||
/**
|
||||
* What comes after a person in a list of other contributors, such as editors: a comma, ", &" with APA's word before the
|
||||
* last author, or "et al." after the first of seven or more (`formatPersonSeperator2`)
|
||||
*/
|
||||
const formatPersonSeperator2 = (position: number, count: number): string => {
|
||||
if (count > 6) {
|
||||
return position === 1 ? General.ListSeparator + Strings.AndOthersUnCap : "";
|
||||
}
|
||||
return position === count
|
||||
? ""
|
||||
: position === count - 1
|
||||
? General.AuthorsSeparator + APA.BeforeLastAuthor + General.Space
|
||||
: General.ListSeparator;
|
||||
};
|
||||
|
||||
/**
|
||||
* People as a source's authors are listed: the first last name first, the others first name first, and only the first
|
||||
* of seven or more; or the organization (`formatPersonsAuthor`)
|
||||
*/
|
||||
const formatPersonsAuthor = (names: WordNames | undefined): string => {
|
||||
if (names === undefined) {
|
||||
return "";
|
||||
}
|
||||
if ("corporate" in names) {
|
||||
return names.corporate;
|
||||
}
|
||||
const count = names.people.length;
|
||||
return names.people
|
||||
.map((person, index) => {
|
||||
const position = index + 1;
|
||||
const name =
|
||||
position === 1
|
||||
? xsl.formatName(person, Chicago.MainAuthor)
|
||||
: count <= 6
|
||||
? xsl.formatName(person, Chicago.OtherAuthors)
|
||||
: "";
|
||||
return name + formatPersonSeperator(position, count);
|
||||
})
|
||||
.join("");
|
||||
};
|
||||
|
||||
/**
|
||||
* People as a source's other contributors are listed, such as its editors, first name first, and only the first of seven
|
||||
* or more (`formatPersons`)
|
||||
*/
|
||||
const formatPersons = (names: WordNames | undefined): string => {
|
||||
if (names === undefined) {
|
||||
return "";
|
||||
}
|
||||
if ("corporate" in names) {
|
||||
return names.corporate;
|
||||
}
|
||||
const count = names.people.length;
|
||||
return names.people
|
||||
.map((person, index) => {
|
||||
const position = index + 1;
|
||||
return (
|
||||
(count <= 6 || position === 1 ? xsl.formatName(person, Chicago.SecondaryAuthors) : "") +
|
||||
formatPersonSeperator2(position, count)
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
};
|
||||
|
||||
/** The date, such as "4 May 2001", or "n.d." when the source has no year (`formatDate`, with `formatDateCore`) */
|
||||
const formatDate = (source: WordSource): string => {
|
||||
const year = fieldOf(source, "Year");
|
||||
return year ? xsl.formatDatePrivate(fieldOf(source, "Day"), fieldOf(source, "Month"), year, Chicago.Date) : Strings.NoDateShortUnCap;
|
||||
};
|
||||
|
||||
/** The date a source was read, such as "May 4, 2022", or nothing when it has no year (`formatDateAccessed`) */
|
||||
const formatDateAccessed = (source: WordSource): string =>
|
||||
xsl.formatDatePrivate(
|
||||
fieldOf(source, "DayAccessed"),
|
||||
fieldOf(source, "MonthAccessed"),
|
||||
fieldOf(source, "YearAccessed"),
|
||||
APA.DateAccessed,
|
||||
);
|
||||
|
||||
/** The city, the publisher and the year, such as "Naples: Forno Press, 2010" (`templateCPYNoDot`) */
|
||||
const templateCPYNoDot = (source: WordSource): string =>
|
||||
templateANoDot(templateCityStateProvince(source), fieldOf(source, "Publisher"), getYear(source));
|
||||
|
||||
/** The city, the publisher and the year, with a dot after them (`templateCPY`) */
|
||||
const templateCPY = (source: WordSource): string =>
|
||||
templateA(templateCityStateProvince(source), fieldOf(source, "Publisher"), getYear(source));
|
||||
|
||||
/** The date, the edition and the pages, such as "4 May 2001, 3rd ed.: 10-20." (`templateDEP`) */
|
||||
const templateDEP = (source: WordSource): string =>
|
||||
templateE(formatDate(source), formatIf(Strings.EditionShortUnCap, fieldOf(source, "Edition")), fieldOf(source, "Pages"));
|
||||
|
||||
/**
|
||||
* The recording number, the year and the medium, each with a dot after it, such as "KR-101. 2005. CD." (`templateRYM`).
|
||||
* The year is never empty, as it is "n.d." when the source has none
|
||||
*/
|
||||
const templateRYM = (source: WordSource): string => {
|
||||
const recordingNumber = fieldOf(source, "RecordingNumber");
|
||||
const medium = fieldOf(source, "Medium");
|
||||
return (
|
||||
xsl.appendDot(recordingNumber) +
|
||||
(recordingNumber ? General.Space : "") +
|
||||
xsl.appendDot(getYear(source)) +
|
||||
(medium ? General.Space : "") +
|
||||
xsl.appendDot(medium)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* The court, the city and the date, in brackets, such as "(Supreme Court, Washington 28 June 2001)." (`templateCCD`).
|
||||
* The date is never empty, as it is "n.d." when the source has no year, so the brackets are always written
|
||||
*/
|
||||
const templateCCD = (source: WordSource): string => {
|
||||
const court = fieldOf(source, "Court");
|
||||
const city = fieldOf(source, "City");
|
||||
return xsl.appendDot(
|
||||
General.OpenBracket +
|
||||
court +
|
||||
(court ? General.ListSeparator : "") +
|
||||
city +
|
||||
(city ? General.Space : "") +
|
||||
formatDate(source) +
|
||||
General.CloseBracket,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* A journal's publisher, volume, issue, month and year, and pages, such as " 12, no. 4 (May 2010): 233-250."
|
||||
* (`templateVIYP`). It starts with a space or a comma when the journal has a name, which comes before it. The year is
|
||||
* never empty, as it is "n.d." when the source has none, so neither is this
|
||||
*/
|
||||
const templateVIYP = (source: WordSource): string => {
|
||||
const journalName = fieldOf(source, "JournalName");
|
||||
const publisher = fieldOf(source, "Publisher");
|
||||
const volume = fieldOf(source, "Volume");
|
||||
const issue = fieldOf(source, "Issue");
|
||||
const month = fieldOf(source, "Month");
|
||||
const pages = fieldOf(source, "Pages");
|
||||
const monthYear = (fieldOf(source, "Year") && month ? month + General.Space : "") + getYear(source);
|
||||
return xsl.appendDot(
|
||||
(publisher ? (journalName ? General.Space : "") + General.OpenBracket + publisher + General.CloseBracket : "") +
|
||||
(volume ? (journalName || publisher ? General.Space : "") + volume : "") +
|
||||
(((journalName || publisher || volume) && issue) || (!volume && !issue && journalName) ? General.ListSeparator : "") +
|
||||
formatIf(Strings.NumberShortUnCap, issue) +
|
||||
General.Space +
|
||||
(volume || issue ? General.OpenBracket + monthYear + General.CloseBracket : monthYear) +
|
||||
(pages ? General.EnumSeparator + pages : ""),
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* The city, the publisher, and the date in brackets with the pages after it, such as "Paris: Press, (4 May 2001): 10-20."
|
||||
* (`templateCPDMY`). The date is never empty, as it is "n.d." when the source has no year, so the template's pages
|
||||
* without a date are never written
|
||||
*/
|
||||
const templateCPDMY = (source: WordSource): string => {
|
||||
const pages = fieldOf(source, "Pages");
|
||||
return templateA(
|
||||
templateCityStateProvince(source),
|
||||
fieldOf(source, "Publisher"),
|
||||
General.OpenBracket + formatDate(source) + General.CloseBracket + (pages ? General.EnumSeparator + pages : ""),
|
||||
);
|
||||
};
|
||||
|
||||
/** A website's address, and when it was read, such as "https://example.com (accessed May 4, 2022)" (`templateDACURL`) */
|
||||
const templateDACURL = (source: WordSource): string => {
|
||||
const url = fieldOf(source, "URL");
|
||||
const date = formatDateAccessed(source);
|
||||
return (
|
||||
url +
|
||||
(url && date ? General.Space : "") +
|
||||
(date ? General.OpenBracket + formatIf(Strings.AccessedUnCap, date) + General.CloseBracket : "")
|
||||
);
|
||||
};
|
||||
|
||||
/** A report's type, department, institution, city, publisher and year, and pages (`templateRICPY`) */
|
||||
const templateRICPY = (source: WordSource): string =>
|
||||
textOf(
|
||||
xsl.printList([
|
||||
fieldOf(source, "ThesisType"),
|
||||
fieldOf(source, "Department"),
|
||||
fieldOf(source, "Institution"),
|
||||
templateCPYNoDot(source),
|
||||
fieldOf(source, "Pages"),
|
||||
]),
|
||||
);
|
||||
|
||||
/**
|
||||
* A source's entry in the bibliography, as the style writes the paragraph (`b:Bibliography`)
|
||||
*
|
||||
* @param authorMain - Its authors, or a dash when they're the authors of the entry before it
|
||||
*/
|
||||
const bibliographyEntry = (source: WordSource, authorMain: string): FormattedText => {
|
||||
const field = (name: Field): string => fieldOf(source, name);
|
||||
const names = (role: Role): WordNames | undefined => source.names[role];
|
||||
const cEditors = countOf(names("Editor"));
|
||||
const cTranslators = countOf(names("Translator"));
|
||||
const cComposers = countOf(names("Composer"));
|
||||
const cCompilers = countOf(names("Compiler"));
|
||||
const cProducers = countOf(names("ProducerName"));
|
||||
const cConductors = countOf(names("Conductor"));
|
||||
|
||||
const author = formatPersonsAuthor(names("Author"));
|
||||
const compiler = formatPersons(names("Compiler"));
|
||||
const compilerLF = formatPersonsAuthor(names("Compiler"));
|
||||
const editor = formatPersons(names("Editor"));
|
||||
const editorLF = formatPersonsAuthor(names("Editor"));
|
||||
const translator = formatPersons(names("Translator"));
|
||||
const translatorLF = formatPersonsAuthor(names("Translator"));
|
||||
const performer = formatPersons(names("Performer"));
|
||||
const intervieweeLF = formatPersonsAuthor(names("Interviewee"));
|
||||
const producerName = formatPersons(names("ProducerName"));
|
||||
const interviewer = formatPersons(names("Interviewer"));
|
||||
const writer = formatPersons(names("Writer"));
|
||||
const writerLF = formatPersonsAuthor(names("Writer"));
|
||||
const director = formatPersons(names("Director"));
|
||||
const inventorLF = formatPersonsAuthor(names("Inventor"));
|
||||
const bookAuthor = formatPersons(names("BookAuthor"));
|
||||
const performerLF = formatPersonsAuthor(names("Performer"));
|
||||
const conductorLF = formatPersonsAuthor(names("Conductor"));
|
||||
const conductor = formatPersons(names("Conductor"));
|
||||
const composerLF = formatPersonsAuthor(names("Composer"));
|
||||
const composer = formatPersons(names("Composer"));
|
||||
const artist = formatPersonsAuthor(names("Artist"));
|
||||
|
||||
// The year is "n.d." when a source has none, so the date, and the parts of an entry with the year, such as the city,
|
||||
// the publisher and the year, are never empty: they are written with no test, and with a space before what follows
|
||||
// them
|
||||
const writerLFDot = xsl.appendDot(writerLF);
|
||||
const dateDot = xsl.appendDot(formatDate(source));
|
||||
const tempCPY = templateCPY(source);
|
||||
const tempRICPY = templateRICPY(source);
|
||||
const tempCPDMY = templateCPDMY(source);
|
||||
const tempDEP = templateDEP(source);
|
||||
const tempRYM = templateRYM(source);
|
||||
const tempTC = templateC(field("Theater"), field("City"));
|
||||
const tempIC = templateC(field("Institution"), field("City"));
|
||||
const tempDY = templateC(field("Distributor"), getYear(source));
|
||||
const tempCPD = templateA(templateCityStateProvince(source), field("Publisher"), formatDate(source));
|
||||
const tempSC = templateC(field("Station"), field("City"));
|
||||
const tempCP = templateCP(source);
|
||||
const tempCCD = templateCCD(source);
|
||||
const tempVIYP = templateVIYP(source);
|
||||
const tempDaU = xsl.appendDot(templateDACURL(source));
|
||||
|
||||
const titleDot = xsl.appendDot(field("Title"));
|
||||
const albumTitleDot = xsl.appendDot(field("AlbumTitle"));
|
||||
const pagesDot = xsl.appendDot(field("Pages"));
|
||||
const bookTitle = field("BookTitle");
|
||||
const bookTitleDot = xsl.appendDot(bookTitle);
|
||||
const conferenceNameDot = xsl.appendDot(field("ConferenceName"));
|
||||
const broadcasterDot = xsl.appendDot(field("Broadcaster"));
|
||||
const interviewTitle = field("Title");
|
||||
const publisher = field("Publisher");
|
||||
const publicationTitle = field("PublicationTitle");
|
||||
const publicationTitleDot = xsl.appendDot(publicationTitle);
|
||||
const institutionDot = xsl.appendDot(field("Institution"));
|
||||
const journalName = field("JournalName");
|
||||
const internetSiteTitleDot = xsl.appendDot(field("InternetSiteTitle"));
|
||||
const mediumDot = xsl.appendDot(field("Medium"));
|
||||
const issueDot = xsl.appendDot(field("Issue"));
|
||||
const numberVolumesDot = xsl.appendDot(formatIf(Strings.VolumesAfterShortUnCap, field("NumberVolumes")));
|
||||
const noIssueDot = xsl.appendDot(formatIf(Strings.NumberShortUnCap, field("Issue")));
|
||||
const editionDot = xsl.appendDot(field("Edition"));
|
||||
const broadcastTitle = field("BroadcastTitle");
|
||||
const versionDot = xsl.appendDot(field("Version"));
|
||||
const broadcastTitleDot = xsl.appendDot(broadcastTitle);
|
||||
const periodicalTitle = field("PeriodicalTitle");
|
||||
const periodicalTitleDot = xsl.appendDot(periodicalTitle);
|
||||
const productionCompany = field("ProductionCompany");
|
||||
const volume = field("Volume");
|
||||
const caseNoDot = field("CaseNumber");
|
||||
|
||||
const prefixVersionDot = versionDot ? Strings.VersionShortCap + General.Space + versionDot : "";
|
||||
const prefixEditorDot = prefixed(editor, cEditors, Strings.EditorShortCap, Strings.EditorShortCap);
|
||||
const prefixTranslatorDot = prefixed(translator, cTranslators, Strings.TranslatorShortCap, Strings.TranslatorsShortCap);
|
||||
const sufixEditorLFDot = suffixed(editorLF, cEditors, Strings.EditorShortUnCap, Strings.EditorsShortUnCap);
|
||||
const prefixConductorDot = prefixed(conductor, cConductors, Strings.ConductorShortCap, Strings.ConductorsShortCap);
|
||||
const prefixComposerDot = prefixed(composer, cComposers, Strings.ComposerShortCap, Strings.ComposersShortCap);
|
||||
const prefixCompilerDot = prefixed(compiler, cCompilers, Strings.CompilerShortCap, Strings.CompilersShortCap);
|
||||
const sufixCompilerLFDot = suffixed(compilerLF, cCompilers, Strings.CompilerShortUnCap, Strings.CompilersShortUnCap);
|
||||
const sufixTranslatorLFDot = suffixed(translatorLF, cTranslators, Strings.TranslatorShortUnCap, Strings.TranslatorsShortUnCap);
|
||||
|
||||
const prefixVolume = formatIf(volumeFormatOf(volume, Strings.VolumeShortCap, Strings.VolumesShortCap), volume);
|
||||
const prefixVolumeDot = xsl.appendDot(prefixVolume);
|
||||
// The volume, and "in" the book's title in italics, which is written with its formatting
|
||||
const inBook = bookTitleDot !== "" && prefixVolumeDot !== "";
|
||||
const volumeBookTitle = join(
|
||||
prefixVolume,
|
||||
inBook ? General.ListSeparator : "",
|
||||
bookTitle ? xsl.stringFormat(inBook ? Strings.InNameUnCap : Strings.InNameCap, applyItalic(bookTitle)) : "",
|
||||
);
|
||||
const theCapShortPrefixVolumeDot = prefixVolumeDot;
|
||||
|
||||
const prod = producerName || productionCompany;
|
||||
const prodDot = xsl.appendDot(prod);
|
||||
const prefixProdDot = prod
|
||||
? (cProducers > 1 ? Strings.ProducersShortCap + General.Space : cProducers === 1 ? Strings.ProducerShortCap + General.Space : "") +
|
||||
prodDot
|
||||
: "";
|
||||
|
||||
const authorDot = xsl.appendDot(author);
|
||||
const sectionAuthorDot = authorDot;
|
||||
const bookAuthorDot = xsl.appendDot(bookAuthor);
|
||||
const performerLFDot = xsl.appendDot(performerLF);
|
||||
const artistDot = xsl.appendDot(artist);
|
||||
const interviewerDot = xsl.appendDot(interviewer);
|
||||
const intervieweeLFDot = xsl.appendDot(intervieweeLF);
|
||||
const conductorLFDot = xsl.appendDot(conductorLF);
|
||||
const inventorLFDot = xsl.appendDot(inventorLF);
|
||||
const writerDot = xsl.appendDot(writer);
|
||||
const composerLFDot = xsl.appendDot(composerLF);
|
||||
|
||||
const theAuthorSufixDot = xsl.appendDot(
|
||||
author
|
||||
? authorMain
|
||||
: editorLF &&
|
||||
["Book", "Misc", "ArticleInAPeriodical", "ConferenceProceedings", "InternetSite", "DocumentFromInternetSite"].includes(
|
||||
source.type,
|
||||
)
|
||||
? suffixed(editorLF, cEditors, Strings.EditorShortUnCap, Strings.EditorsShortUnCap)
|
||||
: compilerLF && source.type === "Misc"
|
||||
? suffixed(compilerLF, cCompilers, Strings.CompilerShortUnCap, Strings.CompilersShortUnCap)
|
||||
: translatorLF && (source.type === "Book" || source.type === "Misc")
|
||||
? suffixed(translatorLF, cTranslators, Strings.TranslatorShortUnCap, Strings.TranslatorsShortUnCap)
|
||||
: "",
|
||||
);
|
||||
|
||||
const theUnCapLongByAuthor = formatIf(Strings.ByUnCap, bookAuthor);
|
||||
const theCapLongByAuthor = formatIf(Strings.ByCap, bookAuthor);
|
||||
const theCapLongPrefixEditorDot = xsl.appendDot(author ? formatIf(Strings.EditedByCap, editor) : "");
|
||||
const theCapLongPrefixCompilerDot = xsl.appendDot(author || editor ? formatIf(Strings.CompiledByCap, compiler) : "");
|
||||
const theCapLongPrefixTranslatorDot = xsl.appendDot(author || editor || compiler ? formatIf(Strings.TranslatedByCap, translator) : "");
|
||||
const theCapLongPrefixEditedBy = formatIf(Strings.EditedByCap, editor);
|
||||
const theCapLongPrefixEditedByDot = xsl.appendDot(theCapLongPrefixEditedBy);
|
||||
const theUnCapLongPrefixEditedBy = formatIf(Strings.EditedByUnCap, editor);
|
||||
const theUnCapLongPrefixEditedByDot = xsl.appendDot(theUnCapLongPrefixEditedBy);
|
||||
const theCapLongPrefixTranslatedBy = formatIf(Strings.TranslatedByCap, translator);
|
||||
const theCapLongPrefixTranslatedByDot = xsl.appendDot(theCapLongPrefixTranslatedBy);
|
||||
const theUnCapLongPrefixTranslatedBy = formatIf(Strings.TranslatedByUnCap, translator);
|
||||
const theUnCapLongPrefixTranslatedByDot = xsl.appendDot(theUnCapLongPrefixTranslatedBy);
|
||||
|
||||
const theCPAuthorSufixDot = xsl.appendDot(
|
||||
author ? authorMain : suffixed(editorLF, cEditors, Strings.EditorShortUnCap, Strings.EditorsShortUnCap),
|
||||
);
|
||||
// The style writes the editors of conference proceedings, and of others, with the same variable as a book's
|
||||
const theCPCapLongPrefixEditorDot = theCapLongPrefixEditorDot;
|
||||
const theCapLongPrefixDirectedByDot = xsl.appendDot(formatIf(Strings.DirectedByCap, director));
|
||||
const theCapLongPrefixPerformedByDot = xsl.appendDot(formatIf(Strings.PerformedByCap, performer));
|
||||
const theCapLongPrefixProducedByDot = xsl.appendDot(formatIf(Strings.ProducedByCap, prod));
|
||||
|
||||
const entries: Readonly<Record<WordSourceType, () => FormattedText>> = {
|
||||
Book: () =>
|
||||
join(
|
||||
theAuthorSufixDot,
|
||||
when(titleDot, spaceIf(theAuthorSufixDot), applyItalic(titleDot)),
|
||||
when(editionDot, spaceIf(theAuthorSufixDot, titleDot), editionDot),
|
||||
when(theCapLongPrefixEditorDot, spaceIf(theAuthorSufixDot, titleDot, editionDot), theCapLongPrefixEditorDot),
|
||||
when(
|
||||
theCapLongPrefixTranslatorDot,
|
||||
spaceIf(theAuthorSufixDot, titleDot, theCapLongPrefixEditorDot, editionDot),
|
||||
theCapLongPrefixTranslatorDot,
|
||||
),
|
||||
when(
|
||||
theCapShortPrefixVolumeDot,
|
||||
spaceIf(theAuthorSufixDot, titleDot, theCapLongPrefixEditorDot, theCapLongPrefixTranslatorDot, editionDot),
|
||||
theCapShortPrefixVolumeDot,
|
||||
),
|
||||
when(
|
||||
numberVolumesDot,
|
||||
spaceIf(
|
||||
theAuthorSufixDot,
|
||||
titleDot,
|
||||
theCapLongPrefixEditorDot,
|
||||
theCapLongPrefixTranslatorDot,
|
||||
theCapShortPrefixVolumeDot,
|
||||
editionDot,
|
||||
),
|
||||
numberVolumesDot,
|
||||
),
|
||||
spaceIf(
|
||||
theAuthorSufixDot,
|
||||
titleDot,
|
||||
theCapLongPrefixEditorDot,
|
||||
theCapLongPrefixTranslatorDot,
|
||||
theCapShortPrefixVolumeDot,
|
||||
editionDot,
|
||||
numberVolumesDot,
|
||||
),
|
||||
tempCPY,
|
||||
),
|
||||
ConferenceProceedings: () =>
|
||||
join(
|
||||
theCPAuthorSufixDot,
|
||||
when(titleDot, spaceIf(theCPAuthorSufixDot), quoted(titleDot)),
|
||||
when(theCPCapLongPrefixEditorDot, spaceIf(theCPAuthorSufixDot, titleDot), theCPCapLongPrefixEditorDot),
|
||||
when(
|
||||
conferenceNameDot,
|
||||
spaceIf(theCPAuthorSufixDot, titleDot, theCPCapLongPrefixEditorDot),
|
||||
applyItalic(conferenceNameDot),
|
||||
),
|
||||
spaceIf(theCPAuthorSufixDot, titleDot, theCPCapLongPrefixEditorDot, conferenceNameDot),
|
||||
tempCPY,
|
||||
when(pagesDot, General.Space, pagesDot),
|
||||
),
|
||||
BookSection: () =>
|
||||
join(
|
||||
sectionAuthorDot,
|
||||
volume
|
||||
? when(titleDot, spaceIf(sectionAuthorDot), applyItalic(titleDot), General.Space)
|
||||
: join(when(titleDot, spaceIf(sectionAuthorDot), quoted(titleDot)), spaceIf(sectionAuthorDot, titleDot, bookAuthorDot)),
|
||||
printSpaceAndList([
|
||||
volume ? volumeBookTitle : bookTitle ? xsl.stringFormat(Strings.InNameCap, applyItalic(bookTitle)) : "",
|
||||
!volume && !bookTitleDot ? theCapLongByAuthor : theUnCapLongByAuthor,
|
||||
!volume && !bookTitleDot && !theCapLongByAuthor ? theCapLongPrefixEditedBy : theUnCapLongPrefixEditedBy,
|
||||
theUnCapLongPrefixTranslatedBy,
|
||||
field("Pages"),
|
||||
]),
|
||||
spaceIf(sectionAuthorDot, titleDot, bookAuthorDot, bookTitleDot, prefixEditorDot, prefixTranslatorDot, volume),
|
||||
tempCPY,
|
||||
),
|
||||
// The journal's volume, issue, date and pages are never empty, so its name has no dot after it, and they follow
|
||||
// it with no space, as they start with one, or with a comma
|
||||
JournalArticle: () =>
|
||||
join(
|
||||
authorDot || sufixEditorLFDot,
|
||||
when(titleDot, spaceIf(authorDot, sufixEditorLFDot), quoted(titleDot)),
|
||||
when(theCPCapLongPrefixEditorDot && authorDot, General.Space, theCPCapLongPrefixEditorDot),
|
||||
when(journalName, spaceIf(authorDot, titleDot, sufixEditorLFDot), applyItalic(journalName)),
|
||||
journalName ? "" : spaceIf(authorDot, titleDot, sufixEditorLFDot),
|
||||
tempVIYP,
|
||||
),
|
||||
Report: () =>
|
||||
join(
|
||||
authorDot,
|
||||
when(titleDot, spaceIf(authorDot), publisher ? applyItalic(titleDot) : quoted(titleDot)),
|
||||
spaceIf(authorDot, titleDot),
|
||||
tempRICPY,
|
||||
),
|
||||
SoundRecording: () => {
|
||||
const titles = (titleSpace: string, albumSpace: string): FormattedText =>
|
||||
join(
|
||||
when(titleDot && albumTitleDot, titleSpace, quoted(titleDot)),
|
||||
when(titleDot && !albumTitleDot, titleSpace, applyItalic(titleDot)),
|
||||
when(albumTitleDot, albumSpace, applyItalic(albumTitleDot)),
|
||||
);
|
||||
if (performerLF) {
|
||||
return join(
|
||||
performerLFDot,
|
||||
titles(General.Space, General.Space),
|
||||
when(prefixConductorDot, General.Space, prefixConductorDot),
|
||||
when(prefixComposerDot, General.Space, prefixComposerDot),
|
||||
General.Space,
|
||||
tempRYM,
|
||||
);
|
||||
}
|
||||
return conductorLFDot
|
||||
? join(
|
||||
conductorLFDot,
|
||||
titles(General.Space, General.Space),
|
||||
when(prefixComposerDot, General.Space, prefixComposerDot),
|
||||
General.Space,
|
||||
tempRYM,
|
||||
)
|
||||
: join(
|
||||
composerLFDot,
|
||||
titles(spaceIf(composerLFDot), spaceIf(composerLFDot, titleDot)),
|
||||
spaceIf(composerLFDot, titleDot, albumTitleDot),
|
||||
tempRYM,
|
||||
);
|
||||
},
|
||||
// The style writes a space before the writers, at the start of the paragraph, which Word doesn't show
|
||||
Performance: () =>
|
||||
join(
|
||||
when(writerLFDot, General.Space, writerLFDot),
|
||||
when(titleDot, spaceIf(writerLFDot), applyItalic(titleDot)),
|
||||
when(theCapLongPrefixDirectedByDot, spaceIf(titleDot, writerDot), theCapLongPrefixDirectedByDot),
|
||||
when(
|
||||
theCapLongPrefixPerformedByDot,
|
||||
spaceIf(titleDot, writerDot, theCapLongPrefixDirectedByDot),
|
||||
theCapLongPrefixPerformedByDot,
|
||||
),
|
||||
when(tempTC, spaceIf(titleDot, writerDot, theCapLongPrefixDirectedByDot, theCapLongPrefixPerformedByDot), tempTC),
|
||||
spaceIf(titleDot, writerDot, theCapLongPrefixDirectedByDot, theCapLongPrefixPerformedByDot, tempTC),
|
||||
dateDot,
|
||||
),
|
||||
Art: () =>
|
||||
publicationTitle
|
||||
? join(
|
||||
normalizeSpace(artistDot),
|
||||
when(titleDot, spaceIf(artistDot), quoted(titleDot)),
|
||||
when(institutionDot, spaceIf(artistDot, titleDot), institutionDot),
|
||||
spaceIf(artistDot, titleDot, institutionDot),
|
||||
applyItalic(publicationTitleDot),
|
||||
General.Space,
|
||||
tempCPY,
|
||||
)
|
||||
: join(
|
||||
normalizeSpace(artistDot),
|
||||
when(titleDot, spaceIf(artistDot), applyItalic(titleDot)),
|
||||
when(tempIC, spaceIf(artistDot, titleDot), tempIC),
|
||||
),
|
||||
DocumentFromInternetSite: () =>
|
||||
join(
|
||||
theAuthorSufixDot,
|
||||
when(titleDot, spaceIf(theAuthorSufixDot), quoted(titleDot)),
|
||||
when(prefixVersionDot, spaceIf(theAuthorSufixDot, titleDot), prefixVersionDot),
|
||||
when(internetSiteTitleDot, spaceIf(theAuthorSufixDot, titleDot, versionDot), applyItalic(internetSiteTitleDot)),
|
||||
when(
|
||||
theCPCapLongPrefixEditorDot,
|
||||
spaceIf(theAuthorSufixDot, titleDot, versionDot, internetSiteTitleDot),
|
||||
theCPCapLongPrefixEditorDot,
|
||||
),
|
||||
when(prodDot, spaceIf(theAuthorSufixDot, titleDot, versionDot, internetSiteTitleDot, theCPCapLongPrefixEditorDot), prodDot),
|
||||
spaceIf(theAuthorSufixDot, titleDot, versionDot, internetSiteTitleDot, theCPCapLongPrefixEditorDot, prodDot),
|
||||
dateDot,
|
||||
when(tempDaU, General.Space, tempDaU),
|
||||
),
|
||||
InternetSite: () =>
|
||||
join(
|
||||
theAuthorSufixDot,
|
||||
when(titleDot, spaceIf(theAuthorSufixDot), applyItalic(titleDot)),
|
||||
when(theCPCapLongPrefixEditorDot, spaceIf(theAuthorSufixDot, titleDot), theCPCapLongPrefixEditorDot),
|
||||
when(prefixVersionDot, spaceIf(theAuthorSufixDot, titleDot, theCPCapLongPrefixEditorDot), prefixVersionDot),
|
||||
when(prodDot, spaceIf(theAuthorSufixDot, titleDot, theCPCapLongPrefixEditorDot, versionDot), prodDot),
|
||||
spaceIf(theAuthorSufixDot, titleDot, theCPCapLongPrefixEditorDot, versionDot, prodDot),
|
||||
dateDot,
|
||||
when(tempDaU, General.Space, tempDaU),
|
||||
),
|
||||
Patent: () =>
|
||||
join(
|
||||
inventorLFDot,
|
||||
when(titleDot, spaceIf(inventorLFDot), titleDot),
|
||||
when(prefixEditorDot, spaceIf(inventorLFDot, titleDot), prefixEditorDot),
|
||||
when(prefixTranslatorDot, spaceIf(inventorLFDot, titleDot, prefixEditorDot), prefixTranslatorDot),
|
||||
when(tempCP, spaceIf(inventorLFDot, titleDot, prefixEditorDot, prefixTranslatorDot), tempCP),
|
||||
spaceIf(inventorLFDot, titleDot, prefixEditorDot, prefixTranslatorDot, tempCP),
|
||||
dateDot,
|
||||
),
|
||||
Case: () => join(applyItalic(titleDot), when(caseNoDot, spaceIf(titleDot), caseNoDot), spaceIf(titleDot, caseNoDot), tempCCD),
|
||||
Misc: () =>
|
||||
join(
|
||||
theAuthorSufixDot,
|
||||
when(titleDot, spaceIf(theAuthorSufixDot), quoted(titleDot)),
|
||||
when(publicationTitleDot, spaceIf(theAuthorSufixDot, titleDot), applyItalic(publicationTitleDot)),
|
||||
when(prefixVolumeDot, spaceIf(theAuthorSufixDot, titleDot, publicationTitleDot), prefixVolumeDot),
|
||||
when(noIssueDot, spaceIf(theAuthorSufixDot, titleDot, publicationTitleDot, prefixVolumeDot), noIssueDot),
|
||||
when(
|
||||
theCPCapLongPrefixEditorDot,
|
||||
spaceIf(theAuthorSufixDot, titleDot, publicationTitleDot, prefixVolumeDot, issueDot),
|
||||
theCPCapLongPrefixEditorDot,
|
||||
),
|
||||
when(
|
||||
theCapLongPrefixTranslatorDot,
|
||||
spaceIf(theAuthorSufixDot, titleDot, publicationTitleDot, prefixVolumeDot, issueDot, theCPCapLongPrefixEditorDot),
|
||||
theCapLongPrefixTranslatorDot,
|
||||
),
|
||||
when(
|
||||
theCapLongPrefixCompilerDot,
|
||||
spaceIf(
|
||||
theAuthorSufixDot,
|
||||
titleDot,
|
||||
publicationTitleDot,
|
||||
prefixVolumeDot,
|
||||
issueDot,
|
||||
theCPCapLongPrefixEditorDot,
|
||||
theCapLongPrefixTranslatorDot,
|
||||
),
|
||||
theCapLongPrefixCompilerDot,
|
||||
),
|
||||
spaceIf(
|
||||
theAuthorSufixDot,
|
||||
titleDot,
|
||||
publicationTitleDot,
|
||||
prefixVolumeDot,
|
||||
issueDot,
|
||||
theCPCapLongPrefixEditorDot,
|
||||
theCapLongPrefixTranslatorDot,
|
||||
theCapLongPrefixCompilerDot,
|
||||
),
|
||||
tempCPD,
|
||||
when(pagesDot, General.Space, pagesDot),
|
||||
),
|
||||
ElectronicSource: () => {
|
||||
// The authors, or else the editors, the translators or the compilers, last name first
|
||||
const lfAuthor = authorDot || sufixEditorLFDot || sufixTranslatorLFDot || sufixCompilerLFDot;
|
||||
const before = [lfAuthor, titleDot, publicationTitleDot, editionDot, prefixVolumeDot, mediumDot];
|
||||
return join(
|
||||
lfAuthor,
|
||||
when(titleDot && publicationTitleDot, spaceIf(lfAuthor), quoted(titleDot)),
|
||||
when(titleDot && !publicationTitleDot, spaceIf(lfAuthor), applyItalic(titleDot)),
|
||||
when(publicationTitleDot, spaceIf(lfAuthor, titleDot), applyItalic(publicationTitleDot)),
|
||||
when(editionDot, spaceIf(lfAuthor, titleDot, publicationTitleDot), editionDot),
|
||||
when(prefixVolumeDot, spaceIf(lfAuthor, titleDot, publicationTitleDot, editionDot), prefixVolumeDot),
|
||||
when(mediumDot, spaceIf(lfAuthor, titleDot, publicationTitleDot, editionDot, prefixVolumeDot), mediumDot),
|
||||
when(authorDot && theCPCapLongPrefixEditorDot, spaceIf(...before), theCPCapLongPrefixEditorDot),
|
||||
when(theCapLongPrefixTranslatorDot && (authorDot || sufixEditorLFDot), spaceIf(...before), theCapLongPrefixTranslatorDot),
|
||||
when(prefixCompilerDot && (authorDot || sufixEditorLFDot || sufixTranslatorLFDot), spaceIf(...before), prefixCompilerDot),
|
||||
when(prefixProdDot, spaceIf(...before), prefixProdDot),
|
||||
spaceIf(...before, prefixProdDot),
|
||||
tempCPD,
|
||||
);
|
||||
},
|
||||
// An article's date, edition and pages are never empty, so the periodical's title has no dot after it when it
|
||||
// follows the authors, and they follow a periodical's title that starts the entry with no space
|
||||
ArticleInAPeriodical: () =>
|
||||
join(
|
||||
theAuthorSufixDot,
|
||||
when(periodicalTitle && !theAuthorSufixDot, applyItalic(periodicalTitleDot)),
|
||||
when(titleDot, spaceIf(theAuthorSufixDot, periodicalTitle), quoted(titleDot)),
|
||||
when(periodicalTitle && theAuthorSufixDot, General.Space, applyItalic(periodicalTitle)),
|
||||
theAuthorSufixDot && periodicalTitle ? General.ListSeparator : spaceIf(theAuthorSufixDot, titleDot),
|
||||
tempDEP,
|
||||
),
|
||||
Film: () =>
|
||||
join(
|
||||
when(writerDot, writerLFDot),
|
||||
when(titleDot, spaceIf(writerDot), applyItalic(titleDot)),
|
||||
when(mediumDot, spaceIf(titleDot, writerDot), mediumDot),
|
||||
when(theCapLongPrefixDirectedByDot, spaceIf(titleDot, writerDot, mediumDot), theCapLongPrefixDirectedByDot),
|
||||
when(
|
||||
theCapLongPrefixProducedByDot,
|
||||
spaceIf(titleDot, writerDot, theCapLongPrefixDirectedByDot, mediumDot),
|
||||
theCapLongPrefixProducedByDot,
|
||||
),
|
||||
when(
|
||||
theCapLongPrefixPerformedByDot,
|
||||
spaceIf(titleDot, writerDot, theCapLongPrefixDirectedByDot, theCapLongPrefixProducedByDot, mediumDot),
|
||||
theCapLongPrefixPerformedByDot,
|
||||
),
|
||||
spaceIf(
|
||||
titleDot,
|
||||
writerDot,
|
||||
theCapLongPrefixDirectedByDot,
|
||||
theCapLongPrefixProducedByDot,
|
||||
theCapLongPrefixPerformedByDot,
|
||||
mediumDot,
|
||||
),
|
||||
tempDY,
|
||||
),
|
||||
Interview: () => {
|
||||
const interviewTitleDot = titleDot;
|
||||
const start = join(
|
||||
when(intervieweeLFDot, interviewerDot ? intervieweeLF : intervieweeLFDot),
|
||||
when(
|
||||
interviewerDot,
|
||||
intervieweeLFDot ? General.ListSeparator : "",
|
||||
xsl.stringFormatDot(intervieweeLFDot ? Strings.InterviewByUnCap : Strings.InterviewByCap, interviewer),
|
||||
),
|
||||
when(
|
||||
interviewTitle,
|
||||
spaceIf(interviewerDot, intervieweeLFDot),
|
||||
broadcastTitleDot
|
||||
? join(intervieweeLFDot ? General.Space : "", quoted(interviewTitleDot))
|
||||
: join(spaceIf(intervieweeLFDot), applyItalic(interviewTitle)),
|
||||
),
|
||||
);
|
||||
if (field("Broadcaster")) {
|
||||
return join(
|
||||
start,
|
||||
when(broadcastTitleDot, spaceIf(interviewerDot, intervieweeLFDot, interviewTitle), applyItalic(broadcastTitleDot)),
|
||||
spaceIf(interviewerDot, intervieweeLFDot, interviewTitle, broadcastTitleDot),
|
||||
broadcasterDot,
|
||||
when(tempSC, General.Space, tempSC),
|
||||
General.Space,
|
||||
dateDot,
|
||||
);
|
||||
}
|
||||
return join(
|
||||
start,
|
||||
when(
|
||||
broadcastTitleDot,
|
||||
spaceIf(interviewerDot, intervieweeLFDot, interviewTitle),
|
||||
applyItalic(editor || translator ? broadcastTitle : broadcastTitleDot),
|
||||
),
|
||||
when(
|
||||
theCapLongPrefixEditedByDot,
|
||||
broadcastTitleDot
|
||||
? join(
|
||||
General.ListSeparator,
|
||||
theCapLongPrefixTranslatedByDot ? theUnCapLongPrefixEditedBy : theUnCapLongPrefixEditedByDot,
|
||||
)
|
||||
: theCapLongPrefixTranslatedByDot
|
||||
? theCapLongPrefixEditedBy
|
||||
: theCapLongPrefixEditedByDot,
|
||||
),
|
||||
when(
|
||||
theCapLongPrefixTranslatedByDot,
|
||||
broadcastTitleDot || theCapLongPrefixEditedByDot
|
||||
? join(General.ListSeparator, theUnCapLongPrefixTranslatedByDot)
|
||||
: theCapLongPrefixTranslatedByDot,
|
||||
),
|
||||
spaceIf(
|
||||
interviewerDot,
|
||||
intervieweeLFDot,
|
||||
interviewTitle,
|
||||
broadcastTitleDot,
|
||||
theCapLongPrefixTranslatedByDot,
|
||||
theCapLongPrefixEditedByDot,
|
||||
),
|
||||
tempCPDMY,
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const entry = entries[source.type]();
|
||||
// Word's XSLT writes a line break after the entry, which Word reads as a space, when the entry ends with an element,
|
||||
// such as an artwork's title in italics when it has no institution or city
|
||||
const last = entry[entry.length - 1] as FormattedRun | undefined;
|
||||
return last?.italics ? join(entry, General.Space) : entry;
|
||||
};
|
||||
|
||||
/**
|
||||
* Turabian, the style of Kate Turabian's manual for writers of papers, as Word writes it: citations such as
|
||||
* "(Baker 2010, 50)", and a bibliography of entries such as "Baker, Anna. *The Art of Pizza.* Naples: Forno Press, 2010.",
|
||||
* with a dash for the authors of an entry with the same authors as the one before it.
|
||||
*/
|
||||
export const turabian: StyleDefinition = {
|
||||
name: "Turabian",
|
||||
file: "TURABIAN.XSL",
|
||||
version: "6",
|
||||
citation,
|
||||
bibliography: (sources: readonly WordSource[]): FormattedBibliography =>
|
||||
bibliographyOf(sources, formatPersonsAuthor, bibliographyEntry),
|
||||
};
|
||||
@@ -0,0 +1,229 @@
|
||||
// cspell:ignore Émile Mabe Müller Ørsted Ægir Œuvre Oakes Straße Strasse
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { italic, join } from "./formatted-text";
|
||||
import { LOCALS } from "./locals";
|
||||
import { applyItalic, isOneOf, lastCharOf, sortByKey, translate, xslTemplates } from "./xsl";
|
||||
|
||||
const { appendDot, formatDatePrivate, formatName, nameInitial, needDot, printList, stringFormat, stringFormatDot } = xslTemplates(
|
||||
LOCALS.General,
|
||||
);
|
||||
|
||||
const person = (last: string, first = "", middle = ""): { readonly last: string; readonly first: string; readonly middle: string } => ({
|
||||
last,
|
||||
first,
|
||||
middle,
|
||||
});
|
||||
|
||||
describe("XPath's functions", () => {
|
||||
it("reads the last character, or none", () => {
|
||||
expect(lastCharOf("Pizza")).to.equal("a");
|
||||
expect(lastCharOf("")).to.equal("");
|
||||
});
|
||||
|
||||
it("finds a character among characters, and finds no character, as contains() does", () => {
|
||||
expect(isOneOf("?", ".!?")).to.equal(true);
|
||||
expect(isOneOf("a", ".!?")).to.equal(false);
|
||||
expect(isOneOf("", ".!?")).to.equal(true);
|
||||
});
|
||||
|
||||
it("replaces characters, and removes those with nothing to replace them", () => {
|
||||
expect(translate("a-b c", "- ", "_")).to.equal("a_bc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("nameInitial", () => {
|
||||
it("writes the initial of a name, with a dot", () => {
|
||||
expect(nameInitial("Charles")).to.equal("C.");
|
||||
});
|
||||
|
||||
it("writes only the first initial of names with spaces in them", () => {
|
||||
expect(nameInitial("Mary Ann")).to.equal("M.");
|
||||
});
|
||||
|
||||
it("writes the initial after each hyphen, with the hyphen", () => {
|
||||
expect(nameInitial("Jean-Paul")).to.equal("J.-P.");
|
||||
expect(nameInitial("Anne-Marie-Claude")).to.equal("A.-M.-C.");
|
||||
});
|
||||
|
||||
it("writes no initial for a name that starts with a hyphen, but the one after it", () => {
|
||||
expect(nameInitial("-Jo")).to.equal("-J.");
|
||||
});
|
||||
|
||||
it("writes nothing for an empty name, or one of spaces", () => {
|
||||
expect(nameInitial("")).to.equal("");
|
||||
expect(nameInitial(" ")).to.equal("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatName", () => {
|
||||
const patterns = { FML: "%L, %f %m", FM: "%F %M", ML: "%L, %m", FL: "%L, %F" } as const;
|
||||
|
||||
it("writes each name the person has with the pattern for them", () => {
|
||||
expect(formatName(person("Dickens", "Charles", "John"), patterns)).to.equal("Dickens, C. J.");
|
||||
expect(formatName(person("Dickens", "Charles"), patterns)).to.equal("Dickens, Charles");
|
||||
expect(formatName(person("Dickens", "", "John"), patterns)).to.equal("Dickens, J.");
|
||||
expect(formatName(person("", "Charles", "John"), patterns)).to.equal("Charles John");
|
||||
});
|
||||
|
||||
it("writes a name alone with Word's simple patterns", () => {
|
||||
expect(formatName(person("Plato"), patterns)).to.equal("Plato");
|
||||
expect(formatName(person("", "Plato"), patterns)).to.equal("Plato");
|
||||
expect(formatName(person("", "", "Plato"), patterns)).to.equal("Plato");
|
||||
expect(formatName(person(""), patterns)).to.equal("");
|
||||
});
|
||||
|
||||
it("writes %% as %, and nothing for an unknown part or a % at the end", () => {
|
||||
expect(formatName(person("Lee", "Ann"), { ...patterns, FL: "%L%% %x%l %" })).to.equal("Lee% L. ");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatDatePrivate", () => {
|
||||
const patterns = { DMY: "%D %M %Y", DM: "%D %M", MY: "%M %Y", DY: "%D %Y" } as const;
|
||||
|
||||
it("writes the date with the pattern for its parts", () => {
|
||||
expect(formatDatePrivate("4", "May", "2001", patterns)).to.equal("4 May 2001");
|
||||
expect(formatDatePrivate("", "May", "2001", patterns)).to.equal("May 2001");
|
||||
});
|
||||
|
||||
it("writes the year alone when there's no month", () => {
|
||||
expect(formatDatePrivate("4", "", "2001", patterns)).to.equal("2001");
|
||||
expect(formatDatePrivate("", "", "2001", patterns)).to.equal("2001");
|
||||
});
|
||||
|
||||
it("writes nothing with no year", () => {
|
||||
expect(formatDatePrivate("4", "May", "", patterns)).to.equal("");
|
||||
});
|
||||
|
||||
it("writes %% as %, and nothing for an unknown part or a % at the end", () => {
|
||||
expect(formatDatePrivate("4", "May", "2001", { ...patterns, DMY: "%Y%%%x %" })).to.equal("2001% ");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stringFormat", () => {
|
||||
it("replaces each parameter, with its formatting", () => {
|
||||
expect(stringFormat("Retrieved %1, from %2", "May 4", italic("Site"))).to.deep.equal([
|
||||
{ text: "Retrieved " },
|
||||
{ text: "May 4" },
|
||||
{ text: ", from " },
|
||||
{ text: "Site", italics: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it("writes %% as %, and nothing for a parameter that isn't given or a % at the end", () => {
|
||||
expect(stringFormat("%%%3 %")).to.deep.equal([{ text: "%" }, { text: " " }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("stringFormatDot", () => {
|
||||
it("writes nothing for an empty format", () => {
|
||||
expect(stringFormatDot("")).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("adds a dot after a parameter that doesn't end a sentence", () => {
|
||||
expect(stringFormatDot("Ed. %1", "Lee")).to.deep.equal([{ text: "Ed. " }, { text: "Lee" }, { text: "." }]);
|
||||
expect(stringFormatDot("Ed. %1", "Lee?")).to.deep.equal([{ text: "Ed. " }, { text: "Lee?" }]);
|
||||
expect(stringFormatDot("Ed. %1", "")).to.deep.equal([{ text: "Ed. " }]);
|
||||
expect(stringFormatDot("Ed. %3", "Lee")).to.deep.equal([{ text: "Ed. " }]);
|
||||
});
|
||||
|
||||
it("adds a dot after a character that doesn't end a sentence", () => {
|
||||
expect(stringFormatDot("%1 ed", "2nd")).to.deep.equal([{ text: "2nd" }, { text: " ed" }, { text: "." }]);
|
||||
expect(stringFormatDot("%1 ed.", "2nd")).to.deep.equal([{ text: "2nd" }, { text: " ed." }]);
|
||||
});
|
||||
|
||||
it("adds a dot after %%, and none after a % at the end", () => {
|
||||
expect(stringFormatDot("100%%")).to.deep.equal([{ text: "100" }, { text: "%" }, { text: "." }]);
|
||||
expect(stringFormatDot("100%")).to.deep.equal([{ text: "100" }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("appendDot and needDot", () => {
|
||||
it("adds a dot to text that doesn't end a sentence", () => {
|
||||
expect(appendDot("Pizza")).to.equal("Pizza.");
|
||||
expect(appendDot("Pizza!")).to.equal("Pizza!");
|
||||
expect(appendDot("")).to.equal("");
|
||||
});
|
||||
|
||||
it("gives the dot text needs", () => {
|
||||
expect(needDot("Pizza")).to.equal(".");
|
||||
expect(needDot("Pizza?")).to.equal("");
|
||||
expect(needDot("")).to.equal("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("printList", () => {
|
||||
it("separates the items written, and ends with a dot", () => {
|
||||
expect(printList(["Paris", "", italic("Press"), "2001"])).to.deep.equal([
|
||||
{ text: "Paris" },
|
||||
{ text: ", " },
|
||||
{ text: "Press", italics: true },
|
||||
{ text: ", " },
|
||||
{ text: "2001" },
|
||||
{ text: "." },
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses the group separator once, before the next item written", () => {
|
||||
expect(printList(["A", "group", "", "B", "C"])).to.deep.equal(join("A", "; ", "B", ", ", "C", "."));
|
||||
});
|
||||
|
||||
it("keeps a group separator before the first item for after it", () => {
|
||||
expect(printList(["group", "A", "B"])).to.deep.equal(join("A", "; ", "B", "."));
|
||||
});
|
||||
|
||||
it("writes nothing for no items", () => {
|
||||
expect(printList(["", "group"])).to.deep.equal([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyItalic", () => {
|
||||
it("writes text in italics, and nothing for none", () => {
|
||||
expect(applyItalic("Title")).to.deep.equal([{ text: "Title", italics: true }]);
|
||||
expect(applyItalic("")).to.deep.equal([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortByKey", () => {
|
||||
const sorted = (keys: readonly string[]): readonly string[] => sortByKey(keys, (key) => key);
|
||||
|
||||
it("sorts in small letters, keeping the order of keys that differ only in case", () => {
|
||||
expect(sorted(["van Dyke", "Ward", "NA", "Na", "abe"])).to.deep.equal(["abe", "NA", "Na", "van Dyke", "Ward"]);
|
||||
});
|
||||
|
||||
it("ignores hyphens and apostrophes, but not spaces", () => {
|
||||
expect(sorted(["O'Neil", "Oakes", "Smith-Jones", "Smithers", "Dean", "de Vries"])).to.deep.equal([
|
||||
"de Vries",
|
||||
"Dean",
|
||||
"Oakes",
|
||||
"O'Neil",
|
||||
"Smithers",
|
||||
"Smith-Jones",
|
||||
]);
|
||||
});
|
||||
|
||||
it("sorts letters with accents by their letters, then by their accents", () => {
|
||||
expect(sorted(["Zoë", "Zoe", "Müller", "Mora", "Mabe", "Émile", "Eve"])).to.deep.equal([
|
||||
"Émile",
|
||||
"Eve",
|
||||
"Mabe",
|
||||
"Mora",
|
||||
"Müller",
|
||||
"Zoe",
|
||||
"Zoë",
|
||||
]);
|
||||
});
|
||||
|
||||
it("sorts letters that are two letters in one as those letters", () => {
|
||||
expect(sorted(["Ørsted", "Ægir", "Adams", "Œuvre", "Oakes", "Straße", "Strasse", "Strand"])).to.deep.equal([
|
||||
"Adams",
|
||||
"Ægir",
|
||||
"Oakes",
|
||||
"Œuvre",
|
||||
"Ørsted",
|
||||
"Strand",
|
||||
"Strasse",
|
||||
"Straße",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* The templates Word's styles of citation share, written in TypeScript: names and their initials, dates, formats such
|
||||
* as "Retrieved %1, from %2", lists of fields and their separators, and the order of a bibliography.
|
||||
*
|
||||
* Each follows its XSL template, including where that doesn't do what it looks like it should, so the styles write what
|
||||
* Word writes. Each XSL template's name is in its description.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
// cspell:ignore Mabe Müller
|
||||
import { type FormattedText, type TextLike, formatted, italic, join, textOf } from "./formatted-text";
|
||||
import type { DatePatterns, NamePatterns } from "./locals";
|
||||
import type { WordPerson } from "../word-source";
|
||||
|
||||
/** The punctuation a style writes with: Word's own (`LOCALS.General`), or the style's, where it has its own */
|
||||
export type Punctuation = {
|
||||
readonly Dot: string;
|
||||
readonly DotInitial: string;
|
||||
readonly EndChars: string;
|
||||
readonly Hyphens: string;
|
||||
readonly ListSeparator: string;
|
||||
readonly GroupSeparator: string;
|
||||
readonly SimpleAuthor: { readonly F: string; readonly L: string; readonly M: string };
|
||||
readonly SimpleDate: { readonly D: string; readonly M: string; readonly Y: string };
|
||||
};
|
||||
|
||||
/** The last character of the text, or "" when it is empty, as `substring($text, string-length($text))` */
|
||||
export const lastCharOf = (text: string): string => text.slice(-1);
|
||||
|
||||
/**
|
||||
* Whether a character is one of the characters, as XPath's `contains($characters, $character)`, which is true of ""
|
||||
*/
|
||||
export const isOneOf = (character: string, characters: string): boolean => characters.includes(character);
|
||||
|
||||
/** The text with each character of `from` replaced by the one at its place in `to`, or removed, as XPath's `translate` */
|
||||
export const translate = (text: string, from: string, to: string): string =>
|
||||
[...text]
|
||||
.map((character) => {
|
||||
const index = from.indexOf(character);
|
||||
return index < 0 ? character : (to[index] ?? "");
|
||||
})
|
||||
.join("");
|
||||
|
||||
/** The parts of a format: %%, a % and the character after it, or the text up to the next % */
|
||||
const formatPartsOf = (format: string): readonly string[] => format.match(/%%|%[^]?|[^%]+/g) ?? [];
|
||||
|
||||
/** The templates Word's styles share that write with their punctuation */
|
||||
export type XslTemplates = {
|
||||
readonly nameInitial: (name: string) => string;
|
||||
readonly formatName: (person: WordPerson, patterns: NamePatterns) => string;
|
||||
readonly formatDatePrivate: (day: string, month: string, year: string, patterns: DatePatterns) => string;
|
||||
readonly stringFormat: (format: string, ...parameters: readonly TextLike[]) => FormattedText;
|
||||
readonly stringFormatDot: (format: string, ...parameters: readonly TextLike[]) => FormattedText;
|
||||
readonly appendDot: (text: string) => string;
|
||||
readonly needDot: (text: string) => string;
|
||||
readonly printList: (items: readonly (TextLike | "group")[]) => FormattedText;
|
||||
};
|
||||
|
||||
/**
|
||||
* The templates Word's styles share, writing with a style's punctuation.
|
||||
*
|
||||
* @param punctuation - The punctuation the style writes with
|
||||
*/
|
||||
export const xslTemplates = (punctuation: Punctuation): XslTemplates => {
|
||||
const dot = punctuation.Dot;
|
||||
const endsWithEndChar = (text: string): boolean => isOneOf(lastCharOf(text), punctuation.EndChars);
|
||||
|
||||
/** The initials of a name, such as "J.-P." of "Jean-Paul", or "M." of "Mary Ann" (`formatNameInitial`) */
|
||||
const nameInitial = (name: string): string => {
|
||||
if (name.length === 0) {
|
||||
return "";
|
||||
}
|
||||
const withoutSpaces = translate(name, " \u00a0", "");
|
||||
// Each letter after a hyphen, with the hyphen (handleHyphens)
|
||||
let hyphenated = "";
|
||||
for (let rest = withoutSpaces; rest.length >= 2;) {
|
||||
if (isOneOf(rest[0], punctuation.Hyphens)) {
|
||||
hyphenated += rest.slice(0, 2) + punctuation.DotInitial;
|
||||
rest = rest.slice(2);
|
||||
} else {
|
||||
rest = rest.slice(1);
|
||||
}
|
||||
}
|
||||
const first = withoutSpaces.slice(0, 1);
|
||||
return (isOneOf(first, punctuation.Hyphens) ? "" : first + punctuation.DotInitial) + hyphenated;
|
||||
};
|
||||
|
||||
/** One part of a person's name for a pattern: %F, %M or %L the name, %f, %m or %l its initials (`formatNameOneItem`) */
|
||||
const namePart = (person: WordPerson, code: string): string => {
|
||||
switch (code) {
|
||||
case "F":
|
||||
return person.first;
|
||||
case "M":
|
||||
return person.middle;
|
||||
case "L":
|
||||
return person.last;
|
||||
case "f":
|
||||
return nameInitial(person.first);
|
||||
case "m":
|
||||
return nameInitial(person.middle);
|
||||
case "l":
|
||||
return nameInitial(person.last);
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A person's name, written with the pattern for the names they have (`formatNameCore` and `StringFormatName`). The
|
||||
* template's `withDot` and `upperLast` are tested without a `$`, so they never add a dot or capitals
|
||||
*/
|
||||
const formatName = (person: WordPerson, patterns: NamePatterns): string => {
|
||||
const { first, middle, last } = person;
|
||||
const pattern =
|
||||
!first && !middle && !last
|
||||
? ""
|
||||
: !first && !middle
|
||||
? punctuation.SimpleAuthor.L
|
||||
: !first && !last
|
||||
? punctuation.SimpleAuthor.M
|
||||
: !first
|
||||
? patterns.ML
|
||||
: !middle && !last
|
||||
? punctuation.SimpleAuthor.F
|
||||
: !middle
|
||||
? patterns.FL
|
||||
: !last
|
||||
? patterns.FM
|
||||
: patterns.FML;
|
||||
return pattern.replace(/%(.)|%$/g, (_match, code: string | undefined) => (code === "%" ? "%" : code ? namePart(person, code) : ""));
|
||||
};
|
||||
|
||||
/**
|
||||
* A date, written with the pattern for the parts it has, or the year alone when it has no month (`formatDateCorePrivate`
|
||||
* and `StringFormatDate`). A month and a day with no year, or a month alone, are written as nothing
|
||||
*/
|
||||
const formatDatePrivate = (day: string, month: string, year: string, patterns: DatePatterns): string => {
|
||||
const pattern = !year ? "" : !month ? punctuation.SimpleDate.Y : !day ? patterns.MY : patterns.DMY;
|
||||
return pattern.replace(/%(.)|%$/g, (_match, code: string | undefined) =>
|
||||
code === "%" ? "%" : code === "D" ? day : code === "M" ? month : code === "Y" ? year : "",
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* A format, such as "Retrieved %1, from %2", with each %1 to %9 replaced by its parameter, with its formatting, and
|
||||
* %% by % (`StringFormat`)
|
||||
*/
|
||||
const stringFormat = (format: string, ...parameters: readonly TextLike[]): FormattedText =>
|
||||
join(
|
||||
...formatPartsOf(format).map((part) =>
|
||||
part === "%%" ? "%" : part.startsWith("%") ? (parameters[Number(part.slice(1)) - 1] ?? "") : part,
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* A format with each parameter replaced, as {@link stringFormat}, and a dot after it unless it ends with a character
|
||||
* that ends a sentence, such as a dot or a question mark, or with an empty parameter (`StringFormatDot`)
|
||||
*/
|
||||
const stringFormatDot = (format: string, ...parameters: readonly TextLike[]): FormattedText => {
|
||||
// The template checks for a dot at the last part of the format: after %%, after a parameter that doesn't end with
|
||||
// a character that ends a sentence, or after a character that isn't one. A % at the end isn't checked
|
||||
const parts = formatPartsOf(format);
|
||||
const last = parts[parts.length - 1] ?? "";
|
||||
const needsDot =
|
||||
last === "%%"
|
||||
? true
|
||||
: last.startsWith("%")
|
||||
? last.length === 2 && !isOneOf(lastCharOf(textOf(parameters[Number(last.slice(1)) - 1] ?? "")), punctuation.EndChars)
|
||||
: last.length > 0 && !isOneOf(lastCharOf(last), punctuation.EndChars);
|
||||
const text = stringFormat(format, ...parameters);
|
||||
return needsDot ? join(text, dot) : text;
|
||||
};
|
||||
|
||||
/** The text, and a dot after it unless it ends with a character that ends a sentence (`appendField_Dot`) */
|
||||
const appendDot = (text: string): string => (text.length === 0 ? "" : endsWithEndChar(text) ? text : text + dot);
|
||||
|
||||
/** A dot, unless the text is empty or ends with a character that ends a sentence (`need_Dot`) */
|
||||
const needDot = (text: string): string => (text.length === 0 || endsWithEndChar(text) ? "" : dot);
|
||||
|
||||
/**
|
||||
* The items of a list with the list's separator between them, or the group separator after a `group` item, and a dot
|
||||
* after the last unless it ends a sentence (`PrintList` and `PrintList2`). A text item is written as text, and a
|
||||
* formatted one with its formatting
|
||||
*/
|
||||
const printList = (items: readonly (TextLike | "group")[]): FormattedText => {
|
||||
const { parts, lastDisplayed } = items.reduce<{
|
||||
readonly parts: readonly TextLike[];
|
||||
readonly separator: string;
|
||||
readonly lastDisplayed: string;
|
||||
}>(
|
||||
(list, item) => {
|
||||
if (item === "group") {
|
||||
return { ...list, separator: punctuation.GroupSeparator };
|
||||
}
|
||||
const text = textOf(item);
|
||||
if (text.length === 0) {
|
||||
return list;
|
||||
}
|
||||
const separated = list.lastDisplayed.length > 0;
|
||||
return {
|
||||
parts: [...list.parts, ...(separated ? [list.separator] : []), item],
|
||||
separator: separated ? punctuation.ListSeparator : list.separator,
|
||||
lastDisplayed: text,
|
||||
};
|
||||
},
|
||||
{ parts: [], separator: punctuation.ListSeparator, lastDisplayed: "" },
|
||||
);
|
||||
return join(...parts, needDot(lastDisplayed));
|
||||
};
|
||||
|
||||
return { nameInitial, formatName, formatDatePrivate, stringFormat, stringFormatDot, appendDot, needDot, printList };
|
||||
};
|
||||
|
||||
/**
|
||||
* The text in italics, as a style's `ApplyItalicTitleNS` and `ApplyItalicFieldNS` write it, as English has italics
|
||||
* (`NoItalics` is "no")
|
||||
*/
|
||||
export const applyItalic = (text: TextLike): FormattedText =>
|
||||
textOf(text).length === 0 && formatted(text).length === 0 ? [] : italic(text);
|
||||
|
||||
// The letters a letter that is two letters in one, or has a stroke through it, is sorted as
|
||||
const SORTED_AS: Readonly<Record<string, string>> = { æ: "ae", œ: "oe", ø: "o", ß: "ss", ł: "l", đ: "d", ð: "d", þ: "th", ı: "i" };
|
||||
|
||||
/** A sort key's letters, without the accents, hyphens and apostrophes that Word ignores when it sorts, in small letters */
|
||||
const primaryKeyOf = (key: string): string =>
|
||||
key
|
||||
.toLowerCase()
|
||||
.normalize("NFD")
|
||||
.replace(/[̀-ͯ]/g, "")
|
||||
.replace(/[-'’]/g, "")
|
||||
.replace(new RegExp(`[${Object.keys(SORTED_AS).join("")}]`, "g"), (letter) => SORTED_AS[letter]);
|
||||
|
||||
const compareStrings = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
|
||||
|
||||
/**
|
||||
* The items sorted by their sort keys, as a style's `xsl:sort` sorts them in Word: in small letters, without the
|
||||
* hyphens and apostrophes in them, and then by their accents. Items with the same key keep their order.
|
||||
*
|
||||
* A letter with an accent is sorted as the letter. Word for Mac sorts some of them in an order of its own, such as
|
||||
* "Müller" before "Mabe", so it may put such names in another order when it updates a bibliography.
|
||||
*/
|
||||
export const sortByKey = <T>(items: readonly T[], keyOf: (item: T) => string): readonly T[] =>
|
||||
items
|
||||
.map((item, index) => ({ item, index, key: keyOf(item) }))
|
||||
.sort(
|
||||
(a, b) =>
|
||||
compareStrings(primaryKeyOf(a.key), primaryKeyOf(b.key)) ||
|
||||
compareStrings(a.key.toLowerCase(), b.key.toLowerCase()) ||
|
||||
a.index - b.index,
|
||||
)
|
||||
.map(({ item }) => item);
|
||||
@@ -0,0 +1,186 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { File } from "@file/file";
|
||||
|
||||
import { SourceType } from "./source";
|
||||
import { createSourceXml, fieldOf, organizationOf, peopleOf, wordSourceOf } from "./word-source";
|
||||
|
||||
const format = (component: Parameters<Formatter["format"]>[0]): unknown => {
|
||||
const file = new File({ sections: [] });
|
||||
return new Formatter().format(component, { file, viewWrapper: file.Document, stack: [] });
|
||||
};
|
||||
|
||||
describe("wordSourceOf", () => {
|
||||
it("names each field and role as Word's XML does, and gives each field as text", () => {
|
||||
const source = wordSourceOf(
|
||||
{
|
||||
tag: "Dic06",
|
||||
type: SourceType.BOOK,
|
||||
authors: [{ lastName: "Dickens", firstName: "Charles", middleName: "John" }],
|
||||
editors: [{ lastName: "Hemingway" }],
|
||||
title: "How to Write Bibliographies",
|
||||
websiteName: "Site",
|
||||
stateOrProvince: "Illinois",
|
||||
reportType: "Thesis",
|
||||
patentType: "Utility",
|
||||
year: 2006,
|
||||
day: 4,
|
||||
volume: 3,
|
||||
numberOfVolumes: 4,
|
||||
issue: 2,
|
||||
},
|
||||
1,
|
||||
);
|
||||
|
||||
expect(source).to.deep.equal({
|
||||
tag: "Dic06",
|
||||
type: "Book",
|
||||
names: {
|
||||
Author: { people: [{ last: "Dickens", first: "Charles", middle: "John" }] },
|
||||
Editor: { people: [{ last: "Hemingway", first: "", middle: "" }] },
|
||||
},
|
||||
fields: {
|
||||
Title: "How to Write Bibliographies",
|
||||
InternetSiteTitle: "Site",
|
||||
StateProvince: "Illinois",
|
||||
ThesisType: "Thesis",
|
||||
Type: "Utility",
|
||||
Year: "2006",
|
||||
Day: "4",
|
||||
Volume: "3",
|
||||
NumberVolumes: "4",
|
||||
Issue: "2",
|
||||
},
|
||||
order: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("names each type of source as Word does", () => {
|
||||
expect(Object.values(SourceType).map((type) => wordSourceOf({ tag: "T", type }, 1).type)).to.deep.equal([
|
||||
"Book",
|
||||
"BookSection",
|
||||
"JournalArticle",
|
||||
"ArticleInAPeriodical",
|
||||
"ConferenceProceedings",
|
||||
"Report",
|
||||
"InternetSite",
|
||||
"DocumentFromInternetSite",
|
||||
"ElectronicSource",
|
||||
"Art",
|
||||
"SoundRecording",
|
||||
"Performance",
|
||||
"Film",
|
||||
"Interview",
|
||||
"Patent",
|
||||
"Case",
|
||||
"Misc",
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves out empty fields and roles with nobody in them", () => {
|
||||
expect(wordSourceOf({ tag: "T", type: "book", title: "", authors: [] }, 1)).to.deep.equal({
|
||||
tag: "T",
|
||||
type: "Book",
|
||||
names: {},
|
||||
fields: {},
|
||||
order: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("gives an organization the role of author or performer", () => {
|
||||
const source = wordSourceOf({ tag: "T", type: "soundRecording", corporateAuthor: "Board", corporatePerformer: "Band" }, 1);
|
||||
|
||||
expect(source.names).to.deep.equal({ Author: { corporate: "Board" }, Performer: { corporate: "Band" } });
|
||||
expect(organizationOf(source, "Author")).to.equal("Board");
|
||||
expect(peopleOf(source, "Author")).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("throws for a source with no tag", () => {
|
||||
expect(() => wordSourceOf({ tag: "", type: "book" }, 1)).toThrow("A bibliography's source has no tag");
|
||||
});
|
||||
|
||||
it("throws for a source whose type isn't one of SourceType's, such as Word's own name for it", () => {
|
||||
expect(() => wordSourceOf({ tag: "T", type: "InternetSite" as "website" }, 1)).toThrow(
|
||||
'The source "T" has the type "InternetSite", which isn\'t a type of source. Give one of SourceType\'s, such as SourceType.BOOK',
|
||||
);
|
||||
expect(() => wordSourceOf({ tag: "T", type: "constructor" as "book" }, 1)).toThrow('has the type "constructor"');
|
||||
});
|
||||
|
||||
it("throws for a source with both people and an organization in one role", () => {
|
||||
expect(() => wordSourceOf({ tag: "T", type: "book", authors: [{ lastName: "Lee" }], corporateAuthor: "Board" }, 1)).toThrow(
|
||||
'The source "T" has both authors and corporateAuthor',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fieldOf, peopleOf and organizationOf", () => {
|
||||
const source = wordSourceOf({ tag: "T", type: "book", title: "Title", authors: [{ lastName: "Lee" }] }, 1);
|
||||
|
||||
it("reads a field, or gives an empty one, as Word's styles do", () => {
|
||||
expect(fieldOf(source, "Title")).to.equal("Title");
|
||||
expect(fieldOf(source, "Year")).to.equal("");
|
||||
});
|
||||
|
||||
it("reads the people with a role, or none", () => {
|
||||
expect(peopleOf(source, "Author")).to.deep.equal([{ last: "Lee", first: "", middle: "" }]);
|
||||
expect(peopleOf(source, "Editor")).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("reads the organization with a role, or none", () => {
|
||||
expect(organizationOf(source, "Author")).to.equal("");
|
||||
expect(organizationOf(source, "Editor")).to.equal("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("createSourceXml", () => {
|
||||
it("writes a source as Word does: its tag, type, people, fields and the order it's cited in", () => {
|
||||
const source = wordSourceOf(
|
||||
{
|
||||
tag: "Dic06",
|
||||
type: "book",
|
||||
authors: [
|
||||
{ lastName: "Dickens", firstName: "Charles", middleName: "John" },
|
||||
{ lastName: "", firstName: "Plato" },
|
||||
{ lastName: "Homer" },
|
||||
],
|
||||
corporatePerformer: "Band",
|
||||
title: "Bibliographies",
|
||||
year: "2006",
|
||||
},
|
||||
2,
|
||||
);
|
||||
|
||||
expect(format(createSourceXml(source))).to.deep.equal({
|
||||
"b:Source": [
|
||||
{ "b:Tag": ["Dic06"] },
|
||||
{ "b:SourceType": ["Book"] },
|
||||
{
|
||||
"b:Author": [
|
||||
{
|
||||
"b:Author": [
|
||||
{
|
||||
"b:NameList": [
|
||||
{ "b:Person": [{ "b:Last": ["Dickens"] }, { "b:First": ["Charles"] }, { "b:Middle": ["John"] }] },
|
||||
{ "b:Person": [{ "b:First": ["Plato"] }] },
|
||||
{ "b:Person": [{ "b:Last": ["Homer"] }] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{ "b:Performer": [{ "b:Corporate": ["Band"] }] },
|
||||
],
|
||||
},
|
||||
{ "b:Title": ["Bibliographies"] },
|
||||
{ "b:Year": ["2006"] },
|
||||
{ "b:RefOrder": ["2"] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("writes a source with no people and no fields", () => {
|
||||
expect(format(createSourceXml(wordSourceOf({ tag: "T", type: "miscellaneous" }, 1)))).to.deep.equal({
|
||||
"b:Source": [{ "b:Tag": ["T"] }, { "b:SourceType": ["Misc"] }, { "b:RefOrder": ["1"] }],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,278 @@
|
||||
/**
|
||||
* Sources as Word keeps them: each field and role of people by its name in the bibliography's XML, which is what Word's
|
||||
* styles of citation read. The styles of `docx/bibliography` are written from Word's, so they read sources this way too.
|
||||
*
|
||||
* Reference: ooxml-schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { BuilderElement, StringContainer, type XmlComponent } from "docx";
|
||||
|
||||
import type { Person, Source, SourceType } from "./source";
|
||||
|
||||
/** The roles of the people who made a source, in the order the schema lists them */
|
||||
export const ROLES = [
|
||||
"Artist",
|
||||
"Author",
|
||||
"BookAuthor",
|
||||
"Compiler",
|
||||
"Composer",
|
||||
"Conductor",
|
||||
"Counsel",
|
||||
"Director",
|
||||
"Editor",
|
||||
"Interviewee",
|
||||
"Interviewer",
|
||||
"Inventor",
|
||||
"Performer",
|
||||
"ProducerName",
|
||||
"Translator",
|
||||
"Writer",
|
||||
] as const;
|
||||
|
||||
/** A role of the people who made a source, by its name in the bibliography's XML */
|
||||
export type Role = (typeof ROLES)[number];
|
||||
|
||||
/** Each field, by its name in the bibliography's XML, and the option of a {@link Source} it is from */
|
||||
const FIELDS = {
|
||||
Title: "title",
|
||||
ShortTitle: "shortTitle",
|
||||
BookTitle: "bookTitle",
|
||||
JournalName: "journalName",
|
||||
PeriodicalTitle: "periodicalTitle",
|
||||
ConferenceName: "conferenceName",
|
||||
InternetSiteTitle: "websiteName",
|
||||
PublicationTitle: "publicationTitle",
|
||||
AlbumTitle: "albumTitle",
|
||||
BroadcastTitle: "broadcastTitle",
|
||||
Year: "year",
|
||||
Month: "month",
|
||||
Day: "day",
|
||||
YearAccessed: "yearAccessed",
|
||||
MonthAccessed: "monthAccessed",
|
||||
DayAccessed: "dayAccessed",
|
||||
City: "city",
|
||||
StateProvince: "stateOrProvince",
|
||||
CountryRegion: "countryOrRegion",
|
||||
Publisher: "publisher",
|
||||
ProductionCompany: "productionCompany",
|
||||
Distributor: "distributor",
|
||||
Institution: "institution",
|
||||
Department: "department",
|
||||
ThesisType: "reportType",
|
||||
Edition: "edition",
|
||||
Volume: "volume",
|
||||
NumberVolumes: "numberOfVolumes",
|
||||
Issue: "issue",
|
||||
Pages: "pages",
|
||||
Medium: "medium",
|
||||
Version: "version",
|
||||
StandardNumber: "standardNumber",
|
||||
URL: "url",
|
||||
RecordingNumber: "recordingNumber",
|
||||
Theater: "theater",
|
||||
Broadcaster: "broadcaster",
|
||||
Station: "station",
|
||||
Type: "patentType",
|
||||
PatentNumber: "patentNumber",
|
||||
CaseNumber: "caseNumber",
|
||||
AbbreviatedCaseNumber: "abbreviatedCaseNumber",
|
||||
Court: "court",
|
||||
Reporter: "reporter",
|
||||
Comments: "comments",
|
||||
} as const satisfies Readonly<Record<string, keyof Source>>;
|
||||
|
||||
/** A field of a source, by its name in the bibliography's XML */
|
||||
export type Field = keyof typeof FIELDS;
|
||||
|
||||
/** The people with each role, and the option of a {@link Source} they are from */
|
||||
const PEOPLE = {
|
||||
Artist: "artists",
|
||||
Author: "authors",
|
||||
BookAuthor: "bookAuthors",
|
||||
Compiler: "compilers",
|
||||
Composer: "composers",
|
||||
Conductor: "conductors",
|
||||
Counsel: "counsel",
|
||||
Director: "directors",
|
||||
Editor: "editors",
|
||||
Interviewee: "interviewees",
|
||||
Interviewer: "interviewers",
|
||||
Inventor: "inventors",
|
||||
Performer: "performers",
|
||||
ProducerName: "producers",
|
||||
Translator: "translators",
|
||||
Writer: "writers",
|
||||
} as const satisfies Readonly<Record<Role, keyof Source>>;
|
||||
|
||||
/** The roles an organization can have in place of people, and the option of a {@link Source} it is from */
|
||||
const ORGANIZATIONS = { Author: "corporateAuthor", Performer: "corporatePerformer" } as const satisfies Partial<Record<Role, keyof Source>>;
|
||||
|
||||
/** Each type of source, and its name in the bibliography's XML */
|
||||
const SOURCE_TYPES = {
|
||||
book: "Book",
|
||||
bookSection: "BookSection",
|
||||
journalArticle: "JournalArticle",
|
||||
articleInAPeriodical: "ArticleInAPeriodical",
|
||||
conferenceProceedings: "ConferenceProceedings",
|
||||
report: "Report",
|
||||
website: "InternetSite",
|
||||
documentFromWebsite: "DocumentFromInternetSite",
|
||||
electronicSource: "ElectronicSource",
|
||||
art: "Art",
|
||||
soundRecording: "SoundRecording",
|
||||
performance: "Performance",
|
||||
film: "Film",
|
||||
interview: "Interview",
|
||||
patent: "Patent",
|
||||
case: "Case",
|
||||
miscellaneous: "Misc",
|
||||
} as const satisfies Readonly<Record<(typeof SourceType)[keyof typeof SourceType], string>>;
|
||||
|
||||
/** A type of source, by its name in the bibliography's XML */
|
||||
export type WordSourceType = (typeof SOURCE_TYPES)[keyof typeof SOURCE_TYPES];
|
||||
|
||||
/** A person, as Word keeps one: each of their names, empty when it isn't given */
|
||||
export type WordPerson = { readonly last: string; readonly first: string; readonly middle: string };
|
||||
|
||||
/** The people with a role, or the organization that has it */
|
||||
export type WordNames = { readonly people: readonly WordPerson[] } | { readonly corporate: string };
|
||||
|
||||
/**
|
||||
* A source as Word keeps it. Its fields and people are by their names in the bibliography's XML, and its order is where it
|
||||
* is in the order the document cites its sources (`b:RefOrder`), from 1.
|
||||
*/
|
||||
export type WordSource = {
|
||||
readonly tag: string;
|
||||
readonly type: WordSourceType;
|
||||
readonly names: Readonly<Partial<Record<Role, WordNames>>>;
|
||||
readonly fields: Readonly<Partial<Record<Field, string>>>;
|
||||
readonly order: number;
|
||||
};
|
||||
|
||||
const personOf = ({ lastName, firstName = "", middleName = "" }: Person): WordPerson => ({
|
||||
last: lastName,
|
||||
first: firstName,
|
||||
middle: middleName,
|
||||
});
|
||||
|
||||
/**
|
||||
* A source as Word keeps it, numbered as cited in the order given.
|
||||
*
|
||||
* @throws If it has no tag, a type that isn't one of {@link SourceType}'s, or both people and an organization with the
|
||||
* same role
|
||||
*/
|
||||
export const wordSourceOf = (source: Source, order: number): WordSource => {
|
||||
if (!source.tag) {
|
||||
throw new Error('A bibliography\'s source has no tag. Give each source the tag its citations refer to it by, such as "Dic06"');
|
||||
}
|
||||
// Only the types' own keys, as every object has others, such as "constructor"
|
||||
if (!Object.keys(SOURCE_TYPES).includes(source.type)) {
|
||||
throw new Error(
|
||||
`The source "${source.tag}" has the type "${source.type}", which isn't a type of source. Give one of SourceType's, such as SourceType.BOOK`,
|
||||
);
|
||||
}
|
||||
const names: Partial<Record<Role, WordNames>> = {};
|
||||
for (const role of ROLES) {
|
||||
const people = source[PEOPLE[role]];
|
||||
const organization = role in ORGANIZATIONS ? source[ORGANIZATIONS[role as keyof typeof ORGANIZATIONS]] : undefined;
|
||||
if (organization && people?.length) {
|
||||
throw new Error(
|
||||
`The source "${source.tag}" has both ${PEOPLE[role]} and ${ORGANIZATIONS[role as keyof typeof ORGANIZATIONS]}. Give one or the other`,
|
||||
);
|
||||
}
|
||||
if (organization) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
names[role] = { corporate: organization };
|
||||
} else if (people?.length) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
names[role] = { people: people.map(personOf) };
|
||||
}
|
||||
}
|
||||
const fields: Partial<Record<Field, string>> = {};
|
||||
for (const [field, option] of Object.entries(FIELDS) as readonly (readonly [Field, keyof Source])[]) {
|
||||
const value = source[option];
|
||||
if (value !== undefined && value !== "") {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
fields[field] = String(value);
|
||||
}
|
||||
}
|
||||
return { tag: source.tag, type: SOURCE_TYPES[source.type], names, fields, order };
|
||||
};
|
||||
|
||||
/** A field of a source, or "" when it doesn't have it, as Word's styles read a field */
|
||||
export const fieldOf = (source: WordSource, field: Field): string => source.fields[field] ?? "";
|
||||
|
||||
/** The people with a role, or none when it has an organization or nobody in it */
|
||||
export const peopleOf = (source: WordSource, role: Role): readonly WordPerson[] => {
|
||||
const names = source.names[role];
|
||||
return names && "people" in names ? names.people : [];
|
||||
};
|
||||
|
||||
/** The organization with a role, or "" when it has people or nobody in it */
|
||||
export const organizationOf = (source: WordSource, role: Role): string => {
|
||||
const names = source.names[role];
|
||||
return names && "corporate" in names ? names.corporate : "";
|
||||
};
|
||||
|
||||
const text = (name: string, value: string): XmlComponent => new StringContainer(`b:${name}`, value);
|
||||
|
||||
const personXml = ({ last, first, middle }: WordPerson): XmlComponent =>
|
||||
new BuilderElement({
|
||||
name: "b:Person",
|
||||
children: [
|
||||
...(last ? [text("Last", last)] : []),
|
||||
...(first ? [text("First", first)] : []),
|
||||
...(middle ? [text("Middle", middle)] : []),
|
||||
],
|
||||
});
|
||||
|
||||
/**
|
||||
* A source's XML, as Word writes it: its tag, type, people and fields, and the order it is cited in.
|
||||
*
|
||||
* ## XSD Schema
|
||||
* ```xml
|
||||
* <xsd:complexType name="CT_SourceType">
|
||||
* <xsd:sequence>
|
||||
* <xsd:choice minOccurs="0" maxOccurs="unbounded">
|
||||
* <xsd:element name="AbbreviatedCaseNumber" type="s:ST_String"/>
|
||||
* <xsd:element name="Author" type="CT_AuthorType"/>
|
||||
* ...
|
||||
* <xsd:element name="Year" type="s:ST_String"/>
|
||||
* </xsd:choice>
|
||||
* </xsd:sequence>
|
||||
* </xsd:complexType>
|
||||
* ```
|
||||
*/
|
||||
export const createSourceXml = (source: WordSource): XmlComponent => {
|
||||
const roles = ROLES.filter((role) => source.names[role] !== undefined);
|
||||
return new BuilderElement({
|
||||
name: "b:Source",
|
||||
children: [
|
||||
text("Tag", source.tag),
|
||||
text("SourceType", source.type),
|
||||
...(roles.length > 0
|
||||
? [
|
||||
new BuilderElement({
|
||||
name: "b:Author",
|
||||
children: roles.map((role) => {
|
||||
const names = source.names[role]!;
|
||||
return new BuilderElement({
|
||||
name: `b:${role}`,
|
||||
children: [
|
||||
"corporate" in names
|
||||
? text("Corporate", names.corporate)
|
||||
: new BuilderElement({ name: "b:NameList", children: names.people.map(personXml) }),
|
||||
],
|
||||
});
|
||||
}),
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(Object.keys(FIELDS) as readonly Field[])
|
||||
.filter((field) => source.fields[field] !== undefined)
|
||||
.map((field) => text(field, source.fields[field]!)),
|
||||
text("RefOrder", String(source.order)),
|
||||
],
|
||||
});
|
||||
};
|
||||
@@ -6,6 +6,7 @@ import { obfuscate } from "@file/fonts/obfuscate-ttf-to-odttf";
|
||||
import { Footer, Header } from "@file/header";
|
||||
import { LevelFormat } from "@file/numbering";
|
||||
import { Bookmark, ExternalHyperlink, ImageRun, Paragraph, TextRun, WpsShapeRun } from "@file/paragraph";
|
||||
import { BuilderElement } from "@file/xml-components";
|
||||
import * as convenienceFunctions from "@util/convenience-functions";
|
||||
|
||||
import { Compiler } from "./next-compiler";
|
||||
@@ -113,6 +114,24 @@ describe("Compiler", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("should pack a bibliography's sources as Word does, in a custom XML part with its properties", async () => {
|
||||
const sources = new BuilderElement({ name: "b:Sources" });
|
||||
const zipFile = compiler.compile(new File({ sections: [], bibliography: { sources } }));
|
||||
|
||||
expect(await zipFile.file("customXml/item1.xml")?.async("text")).toBe(
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><b:Sources/>',
|
||||
);
|
||||
expect(await zipFile.file("customXml/itemProps1.xml")?.async("text")).to.match(
|
||||
/^<\?xml version="1.0" encoding="UTF-8" standalone="no"\?><ds:datastoreItem ds:itemID="\{[0-9A-F-]{36}\}" xmlns:ds="http:\/\/schemas.openxmlformats.org\/officeDocument\/2006\/customXml"><ds:schemaRefs><ds:schemaRef ds:uri="http:\/\/schemas.openxmlformats.org\/officeDocument\/2006\/bibliography"\/><\/ds:schemaRefs><\/ds:datastoreItem>$/,
|
||||
);
|
||||
expect(await zipFile.file("customXml/_rels/item1.xml.rels")?.async("text")).toContain(
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps" Target="itemProps1.xml"/>',
|
||||
);
|
||||
expect(await zipFile.file("word/_rels/document.xml.rels")?.async("text")).toContain(
|
||||
'Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml" Target="../customXml/item1.xml"',
|
||||
);
|
||||
});
|
||||
|
||||
it("should give an image in a comment a relationship from the comments part", async () => {
|
||||
const image = new ImageRun({ type: "png", data: Buffer.from("", "base64"), transformation: { width: 10, height: 10 } });
|
||||
const zipFile = compiler.compile(
|
||||
|
||||
@@ -91,6 +91,12 @@ type IXmlifyedFileMapping = {
|
||||
readonly MacroEvents?: IXmlifyedFile;
|
||||
/** The relationships of the macros' VBA project (word/_rels/vbaProject.bin.rels), to their events */
|
||||
readonly MacroRelationships?: IXmlifyedFile;
|
||||
/** The sources of the document's citations and bibliographies (customXml/item1.xml) */
|
||||
readonly BibliographySources?: IXmlifyedFile;
|
||||
/** The properties of the sources' part (customXml/itemProps1.xml) */
|
||||
readonly BibliographySourcesProperties?: IXmlifyedFile;
|
||||
/** The relationships of the sources' part (customXml/_rels/item1.xml.rels), to its properties */
|
||||
readonly BibliographySourcesRelationships?: IXmlifyedFile;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -795,6 +801,61 @@ export class Compiler {
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
...(file.Bibliography
|
||||
? {
|
||||
BibliographySources: {
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.Bibliography.sources, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
stack: [],
|
||||
}),
|
||||
{
|
||||
indent: prettify,
|
||||
declaration: {
|
||||
standalone: "yes",
|
||||
encoding: "UTF-8",
|
||||
},
|
||||
},
|
||||
),
|
||||
path: "customXml/item1.xml",
|
||||
},
|
||||
BibliographySourcesProperties: {
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.Bibliography.properties, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
stack: [],
|
||||
}),
|
||||
{
|
||||
indent: prettify,
|
||||
declaration: {
|
||||
standalone: "no",
|
||||
encoding: "UTF-8",
|
||||
},
|
||||
},
|
||||
),
|
||||
path: "customXml/itemProps1.xml",
|
||||
},
|
||||
BibliographySourcesRelationships: {
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.Bibliography.relationships, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
stack: [],
|
||||
}),
|
||||
{
|
||||
indent: prettify,
|
||||
declaration: {
|
||||
standalone: "yes",
|
||||
encoding: "UTF-8",
|
||||
},
|
||||
},
|
||||
),
|
||||
path: "customXml/_rels/item1.xml.rels",
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
// After every part that can refer to them, which adds them to the package as it is written
|
||||
PackageParts: xmlifyPackageParts(file, prettify),
|
||||
// After every part that can have lists, such as headers and footers, as the lists they use are added to the
|
||||
|
||||
@@ -18,6 +18,7 @@ import { dateTimeValue } from "@util/values";
|
||||
import type { ICustomPropertyOptions } from "../custom-properties";
|
||||
import type { IDocumentBackgroundOptions, PageNumberEstimator } from "../document";
|
||||
import { DocumentAttributes } from "../document/document-attributes";
|
||||
import type { DocumentBibliography } from "../document-bibliography";
|
||||
import type { DocumentMacros } from "../document-macros";
|
||||
import type { ISectionOptions } from "../file";
|
||||
import type { INumberingOptions } from "../numbering";
|
||||
@@ -54,6 +55,7 @@ import type { IThemeOptions } from "../theme";
|
||||
* @property pageNumbers - Works out the page each bookmark is on, so the page numbers of tables of contents and page references are written with the document
|
||||
* @property macros - The document's VBA macros, which make it a macro-enabled document (.docm)
|
||||
* @property protection - What people can change in the document in Word, and the password that turns that protection off
|
||||
* @property bibliography - The sources the document's citations and bibliographies refer to
|
||||
*/
|
||||
export type IPropertiesOptions = {
|
||||
readonly sections: readonly ISectionOptions[];
|
||||
@@ -118,6 +120,11 @@ export type IPropertiesOptions = {
|
||||
* between `EditableRangeStart` and `EditableRangeEnd` can still be changed by anyone
|
||||
*/
|
||||
readonly protection?: IDocumentProtectionOptions;
|
||||
/**
|
||||
* The sources that the document's citations and bibliographies refer to, and the style they're written in, such as
|
||||
* APA. `createBibliography` from `docx/bibliography` writes them. Word lists them in its Source Manager
|
||||
*/
|
||||
readonly bibliography?: DocumentBibliography;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Document bibliography module: the sources that a document's citations and bibliographies refer to.
|
||||
*
|
||||
* Word keeps a document's sources in a custom XML part, customXml/item1.xml, whose root is a `b:Sources` element, and
|
||||
* lists them in its Source Manager. The part's properties, customXml/itemProps1.xml, give it an id and name the schema
|
||||
* of its XML, the bibliography's.
|
||||
*
|
||||
* Reference: ooxml-schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd and shared-customXmlDataProperties.xsd
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { BuilderElement, type XmlComponent } from "@file/xml-components";
|
||||
|
||||
/**
|
||||
* A document's bibliography, for the document's `bibliography`: the sources its citations and bibliographies refer to.
|
||||
* `createBibliography` from `docx/bibliography` writes it.
|
||||
*
|
||||
* @publicApi
|
||||
*/
|
||||
export type DocumentBibliography = {
|
||||
/**
|
||||
* The document's sources, as Word keeps them: a `b:Sources` element in the bibliography's namespace, with the style
|
||||
* the citations and bibliographies are written in. It is written after the document's body
|
||||
*/
|
||||
readonly sources: XmlComponent;
|
||||
};
|
||||
|
||||
/**
|
||||
* The properties of the part that a document's sources are in (customXml/itemProps1.xml): its id, and the schema of its
|
||||
* XML, the bibliography's.
|
||||
*
|
||||
* ## XSD Schema
|
||||
* ```xml
|
||||
* <xsd:complexType name="CT_DatastoreItem">
|
||||
* <xsd:sequence>
|
||||
* <xsd:element name="schemaRefs" type="CT_DatastoreSchemaRefs" minOccurs="0"/>
|
||||
* </xsd:sequence>
|
||||
* <xsd:attribute name="itemID" type="s:ST_Guid" use="required"/>
|
||||
* </xsd:complexType>
|
||||
* ```
|
||||
*
|
||||
* @param itemId - The part's id, a GUID in braces, such as "{6E3A1B2C-4D5E-4F60-8A7B-9C0D1E2F3A4B}"
|
||||
*/
|
||||
export const createSourcesProperties = (itemId: string): XmlComponent =>
|
||||
new BuilderElement<{ readonly itemId: string; readonly namespace: string }>({
|
||||
name: "ds:datastoreItem",
|
||||
attributes: {
|
||||
itemId: { key: "ds:itemID", value: itemId },
|
||||
namespace: { key: "xmlns:ds", value: "http://schemas.openxmlformats.org/officeDocument/2006/customXml" },
|
||||
},
|
||||
children: [
|
||||
new BuilderElement({
|
||||
name: "ds:schemaRefs",
|
||||
children: [
|
||||
new BuilderElement<{ readonly uri: string }>({
|
||||
name: "ds:schemaRef",
|
||||
attributes: { uri: { key: "ds:uri", value: "http://schemas.openxmlformats.org/officeDocument/2006/bibliography" } },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
export { type DocumentBibliography } from "./document-bibliography";
|
||||
@@ -485,6 +485,20 @@ describe("File", () => {
|
||||
expect(captionStyles[0]["w:style"]).to.deep.include({ "w:rPr": [{ "w:b": {} }, { "w:bCs": {} }] });
|
||||
});
|
||||
|
||||
it("should write Word's bibliography style, which bibliographies' paragraphs are in, and format it with styles.default", () => {
|
||||
const stylesOf = (doc: File): readonly unknown[] => {
|
||||
const styles = new Formatter().format(doc.Styles)["w:styles"];
|
||||
return styles.filter((child: { readonly "w:style"?: readonly { readonly _attr?: Record<string, string> }[] }) =>
|
||||
child["w:style"]?.some((part) => part._attr?.["w:styleId"] === "Bibliography"),
|
||||
);
|
||||
};
|
||||
|
||||
expect(stylesOf(new File({ sections: [] }))).to.deep.equal([new Formatter().format(createDefaultStyles().bibliography)]);
|
||||
expect(stylesOf(new File({ styles: { default: { bibliography: { run: { size: 20 } } } }, sections: [] }))).to.deep.equal([
|
||||
new Formatter().format(createDefaultStyles({ bibliography: { run: { size: 20 } } }).bibliography),
|
||||
]);
|
||||
});
|
||||
|
||||
it("should create with even and odd headers and footers", () => {
|
||||
const doc = new File({
|
||||
evenAndOddHeaderAndFooters: true,
|
||||
@@ -679,6 +693,63 @@ describe("File", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("#bibliography", () => {
|
||||
const CUSTOM_XML = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml";
|
||||
|
||||
it("should have no sources part without a bibliography", () => {
|
||||
const doc = new File({ sections: [] });
|
||||
|
||||
expect(doc.Bibliography).toBeUndefined();
|
||||
expect(JSON.stringify(new Formatter().format(doc.Document.Relationships))).not.toContain(CUSTOM_XML);
|
||||
expect(JSON.stringify(new Formatter().format(doc.ContentTypes))).not.toContain("customXml");
|
||||
});
|
||||
|
||||
it("should keep the sources in a custom XML part, with its properties, as Word does", () => {
|
||||
const sources = new Paragraph("Sources");
|
||||
const doc = new File({ bibliography: { sources }, sections: [] });
|
||||
|
||||
expect(doc.Bibliography?.sources).toBe(sources);
|
||||
const properties = new Formatter().format(doc.Bibliography!.properties);
|
||||
expect(properties["ds:datastoreItem"][0]._attr["ds:itemID"]).to.match(/^\{[0-9A-F]{8}(-[0-9A-F]{4}){3}-[0-9A-F]{12}\}$/);
|
||||
expect(new Formatter().format(doc.Bibliography!.relationships)).toEqual({
|
||||
Relationships: [
|
||||
{ _attr: { xmlns: "http://schemas.openxmlformats.org/package/2006/relationships" } },
|
||||
{
|
||||
Relationship: {
|
||||
_attr: {
|
||||
Id: "rId1",
|
||||
Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps",
|
||||
Target: "itemProps1.xml",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(new Formatter().format(doc.ContentTypes))).toContain(
|
||||
JSON.stringify({
|
||||
ContentType: "application/vnd.openxmlformats-officedocument.customXmlProperties+xml",
|
||||
PartName: "/customXml/itemProps1.xml",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should relate the document to the sources after the theme and the macros", () => {
|
||||
const project = Uint8Array.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1, 0x00]);
|
||||
const relationships = JSON.stringify(
|
||||
new Formatter().format(
|
||||
new File({ bibliography: { sources: new Paragraph("") }, macros: { project }, sections: [] }).Document.Relationships,
|
||||
),
|
||||
);
|
||||
|
||||
expect(relationships).toContain(JSON.stringify({ Id: "rId8", Type: CUSTOM_XML, Target: "../customXml/item1.xml" }));
|
||||
expect(
|
||||
JSON.stringify(
|
||||
new Formatter().format(new File({ bibliography: { sources: new Paragraph("") }, sections: [] }).Document.Relationships),
|
||||
),
|
||||
).toContain(JSON.stringify({ Id: "rId7", Type: CUSTOM_XML, Target: "../customXml/item1.xml" }));
|
||||
});
|
||||
});
|
||||
|
||||
describe("#macros", () => {
|
||||
// The start of a compound file, which is all the document checks a VBA project for
|
||||
const project = Uint8Array.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1, 0x00]);
|
||||
|
||||
@@ -6,11 +6,14 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { uniqueUuid } from "@util/convenience-functions";
|
||||
|
||||
import { AppProperties } from "./app-properties/app-properties";
|
||||
import { ContentTypes } from "./content-types/content-types";
|
||||
import { CoreProperties, type IPropertiesOptions } from "./core-properties";
|
||||
import { CustomProperties } from "./custom-properties";
|
||||
import { HeaderFooterReferenceType, type ISectionPropertiesOptions } from "./document/body/section-properties";
|
||||
import { createSourcesProperties } from "./document-bibliography/document-bibliography";
|
||||
import { createMacroEvents } from "./document-macros/document-macros";
|
||||
import { DocumentWrapper } from "./document-wrapper";
|
||||
import { EndnotesWrapper } from "./endnotes-wrapper";
|
||||
@@ -89,6 +92,18 @@ type FileMacros = {
|
||||
readonly relationships: Relationships;
|
||||
};
|
||||
|
||||
/**
|
||||
* A document's sources, as the document writes them.
|
||||
*/
|
||||
type FileBibliography = {
|
||||
/** The sources (customXml/item1.xml) */
|
||||
readonly sources: XmlComponent;
|
||||
/** The properties of their part (customXml/itemProps1.xml) */
|
||||
readonly properties: XmlComponent;
|
||||
/** Their part's relationships (customXml/_rels/item1.xml.rels), to its properties */
|
||||
readonly relationships: Relationships;
|
||||
};
|
||||
|
||||
/**
|
||||
* Represents a Word document file.
|
||||
*
|
||||
@@ -192,6 +207,7 @@ export class File {
|
||||
private readonly theme: Theme;
|
||||
private readonly packageParts: PackageParts;
|
||||
private readonly macros?: FileMacros;
|
||||
private readonly bibliography?: FileBibliography;
|
||||
|
||||
public constructor(options: IPropertiesOptions) {
|
||||
if (options.macros !== undefined) {
|
||||
@@ -239,6 +255,23 @@ export class File {
|
||||
if (this.macros?.events !== undefined) {
|
||||
this.contentTypes.addOverride("application/vnd.ms-word.vbaData+xml", "/word/vbaData.xml");
|
||||
}
|
||||
if (options.bibliography !== undefined) {
|
||||
const relationships = new Relationships();
|
||||
relationships.addRelationship(
|
||||
1,
|
||||
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps",
|
||||
"itemProps1.xml",
|
||||
);
|
||||
this.bibliography = {
|
||||
sources: options.bibliography.sources,
|
||||
properties: createSourcesProperties(`{${uniqueUuid().toUpperCase()}}`),
|
||||
relationships,
|
||||
};
|
||||
this.contentTypes.addOverride(
|
||||
"application/vnd.openxmlformats-officedocument.customXmlProperties+xml",
|
||||
"/customXml/itemProps1.xml",
|
||||
);
|
||||
}
|
||||
this.packageParts = new PackageParts(this.contentTypes);
|
||||
this.documentWrapper = new DocumentWrapper({ background: options.background, pageNumbers: options.pageNumbers });
|
||||
this.settings = new Settings({
|
||||
@@ -334,6 +367,14 @@ export class File {
|
||||
"vbaProject.bin",
|
||||
);
|
||||
}
|
||||
if (this.bibliography !== undefined) {
|
||||
this.documentWrapper.Relationships.addRelationship(
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
this.currentRelationshipId++,
|
||||
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",
|
||||
"../customXml/item1.xml",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private addSection({ headers = {}, footers = {}, children, properties }: ISectionOptions): void {
|
||||
@@ -583,4 +624,12 @@ export class File {
|
||||
public get Macros(): FileMacros | undefined {
|
||||
return this.macros;
|
||||
}
|
||||
|
||||
/**
|
||||
* The document's sources, when it has a bibliography: the part they're in (customXml/item1.xml), its properties
|
||||
* (customXml/itemProps1.xml), and its relationships, to its properties.
|
||||
*/
|
||||
public get Bibliography(): FileBibliography | undefined {
|
||||
return this.bibliography;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ export * from "./fonts";
|
||||
export * from "./textbox";
|
||||
export * from "./theme";
|
||||
export * from "./document-macros";
|
||||
export * from "./document-bibliography";
|
||||
// Parts that drawings add to the package when it is written, such as docx/charts' charts
|
||||
export * from "./package-part";
|
||||
export { type OleObjectRelationshipType, type RelationshipType } from "./relationships/relationship/relationship";
|
||||
|
||||
@@ -38,6 +38,14 @@ export type MacroRelationshipType =
|
||||
| "http://schemas.microsoft.com/office/2006/relationships/vbaProject"
|
||||
| "http://schemas.microsoft.com/office/2006/relationships/wordVbaData";
|
||||
|
||||
/**
|
||||
* The types of the relationships to a document's sources, which are in a custom XML part, and from that part to its
|
||||
* properties.
|
||||
*/
|
||||
export type CustomXmlRelationshipType =
|
||||
| "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml"
|
||||
| "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps";
|
||||
|
||||
/**
|
||||
* The type of the relationship to an OLE object that isn't a package, such as a file docx/embedded-files embeds in an
|
||||
* OLE package. It isn't one of the {@link RelationshipType}s, as a {@link PackagePart} gives its relationship type in its
|
||||
@@ -57,7 +65,7 @@ export const TargetModeType = {
|
||||
|
||||
type IRelationshipAttributes = {
|
||||
readonly id: string;
|
||||
readonly type: RelationshipType | MacroRelationshipType | OleObjectRelationshipType;
|
||||
readonly type: RelationshipType | MacroRelationshipType | OleObjectRelationshipType | CustomXmlRelationshipType;
|
||||
readonly target: string;
|
||||
readonly targetMode?: (typeof TargetModeType)[keyof typeof TargetModeType];
|
||||
};
|
||||
@@ -80,7 +88,7 @@ type IRelationshipAttributes = {
|
||||
|
||||
export const createRelationship = (
|
||||
id: string,
|
||||
type: RelationshipType | MacroRelationshipType | OleObjectRelationshipType,
|
||||
type: RelationshipType | MacroRelationshipType | OleObjectRelationshipType | CustomXmlRelationshipType,
|
||||
target: string,
|
||||
targetMode?: (typeof TargetModeType)[keyof typeof TargetModeType],
|
||||
): XmlComponent =>
|
||||
|
||||
@@ -12,6 +12,7 @@ import { XmlComponent } from "@file/xml-components";
|
||||
|
||||
import { RelationshipsAttributes } from "./attributes";
|
||||
import {
|
||||
type CustomXmlRelationshipType,
|
||||
type MacroRelationshipType,
|
||||
type OleObjectRelationshipType,
|
||||
type RelationshipType,
|
||||
@@ -57,7 +58,7 @@ export class Relationships extends XmlComponent {
|
||||
*/
|
||||
public addRelationship(
|
||||
id: number | string,
|
||||
type: RelationshipType | MacroRelationshipType | OleObjectRelationshipType,
|
||||
type: RelationshipType | MacroRelationshipType | OleObjectRelationshipType | CustomXmlRelationshipType,
|
||||
target: string,
|
||||
targetMode?: (typeof TargetModeType)[keyof typeof TargetModeType],
|
||||
): void {
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { XmlComponent } from "@file/xml-components";
|
||||
|
||||
import { DocumentDefaults, type IDocumentDefaultsOptions } from "./defaults";
|
||||
import {
|
||||
BibliographyStyle,
|
||||
CaptionStyle,
|
||||
EndnoteReferenceStyle,
|
||||
EndnoteText,
|
||||
@@ -53,6 +54,7 @@ import { DocumentAttributes } from "../document/document-attributes";
|
||||
* @property strong - Strong paragraph style options
|
||||
* @property listParagraph - List paragraph style options
|
||||
* @property caption - Caption paragraph style options
|
||||
* @property bibliography - Bibliography paragraph style options
|
||||
* @property hyperlink - Hyperlink character style options
|
||||
* @property footnoteReference - Footnote reference character style options
|
||||
* @property footnoteText - Footnote text paragraph style options
|
||||
@@ -85,6 +87,11 @@ export type IDefaultStylesOptions = {
|
||||
* own, so a `run` replaces its italic, size and color
|
||||
*/
|
||||
readonly caption?: IBaseParagraphStyleOptions;
|
||||
/**
|
||||
* The style of the paragraphs of bibliographies, the lists of sources that `Bibliography` from `docx/bibliography`
|
||||
* writes. It has no formatting of its own, as each style of citation, such as APA, indents them itself
|
||||
*/
|
||||
readonly bibliography?: IBaseParagraphStyleOptions;
|
||||
/** Hyperlink character style options */
|
||||
readonly hyperlink?: IBaseCharacterStyleOptions;
|
||||
/** Footnote reference character style options */
|
||||
@@ -172,6 +179,7 @@ export const createDefaultStyles = (
|
||||
}),
|
||||
listParagraph: new ListParagraph(options.listParagraph || {}),
|
||||
caption: new CaptionStyle(options.caption || {}),
|
||||
bibliography: new BibliographyStyle(options.bibliography || {}),
|
||||
hyperlink: new HyperlinkStyle(options.hyperlink || {}),
|
||||
footnoteReference: new FootnoteReferenceStyle(options.footnoteReference || {}),
|
||||
footnoteText: new FootnoteText(options.footnoteText || {}),
|
||||
|
||||
@@ -392,6 +392,27 @@ describe("Default Styles", () => {
|
||||
expect(tree["w:style"]).to.deep.include({ "w:pPr": [{ "w:spacing": { _attr: { "w:after": 200 } } }] });
|
||||
});
|
||||
|
||||
it("BibliographyStyle#constructor is Word's bibliography style, with no formatting of its own", () => {
|
||||
expect(new Formatter().format(new defaultStyles.BibliographyStyle({}))).to.deep.equal({
|
||||
"w:style": [
|
||||
{ _attr: { "w:type": "paragraph", "w:styleId": "Bibliography" } },
|
||||
{ "w:name": { _attr: { "w:val": "Bibliography" } } },
|
||||
{ "w:basedOn": { _attr: { "w:val": "Normal" } } },
|
||||
{ "w:next": { _attr: { "w:val": "Normal" } } },
|
||||
{ "w:uiPriority": { _attr: { "w:val": 37 } } },
|
||||
{ "w:unhideWhenUsed": EMPTY_OBJECT },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("BibliographyStyle#constructor formats bibliographies with the options given", () => {
|
||||
const tree = new Formatter().format(new defaultStyles.BibliographyStyle({ run: { size: 20 } }));
|
||||
|
||||
expect(tree["w:style"]).to.deep.include({
|
||||
"w:rPr": [{ "w:sz": { _attr: { "w:val": 20 } } }, { "w:szCs": { _attr: { "w:val": 20 } } }],
|
||||
});
|
||||
});
|
||||
|
||||
it("LineNumberStyle#constructor is Word's line number style, with no formatting of its own", () => {
|
||||
expect(new Formatter().format(new defaultStyles.LineNumberStyle({}))).to.deep.equal({
|
||||
"w:style": [
|
||||
|
||||
@@ -227,6 +227,27 @@ export class CaptionStyle extends StyleForParagraph {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the Bibliography paragraph style.
|
||||
*
|
||||
* Word gives the paragraphs of the bibliographies it writes (References > Bibliography) the paragraph style named
|
||||
* "Bibliography", and this is that style as Word writes it. It has no formatting of its own: each style of citation,
|
||||
* such as APA, indents the paragraphs of its bibliography itself.
|
||||
*/
|
||||
export class BibliographyStyle extends StyleForParagraph {
|
||||
public constructor(options: IBaseParagraphStyleOptions) {
|
||||
super({
|
||||
id: "Bibliography",
|
||||
name: "Bibliography",
|
||||
basedOn: "Normal",
|
||||
next: "Normal",
|
||||
uiPriority: 37,
|
||||
unhideWhenUsed: true,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the Footnote Text paragraph style.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Checks a style of citation of docx/bibliography against what Word writes: the citations and bibliographies of the
|
||||
* corpora in src/bibliography/styles/fixtures, as markup.
|
||||
*
|
||||
* The fixtures of corpora a to d are what Word for Mac wrote for them. Corpus s is sources of every type with each of
|
||||
* their fields in turn left out, and its fixtures are what Word's own style, its XSL, writes for them when it is run with
|
||||
* libxslt and Word's English wording. That gives the same as Word for corpora a to d.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import type { File } from "@file/file";
|
||||
import type { BaseXmlComponent } from "@file/xml-components";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
|
||||
import { type CitedSourceOptions, citationOrderOf, formatBibliography, formatCitation } from "../bibliography/format";
|
||||
import type { Source } from "../bibliography/source";
|
||||
import corpora from "../bibliography/styles/fixtures/corpora.json";
|
||||
import { type FormattedText, italic, join } from "../bibliography/styles/formatted-text";
|
||||
import type { StyleDefinition } from "../bibliography/styles/style";
|
||||
import { fieldOf, wordSourceOf } from "../bibliography/word-source";
|
||||
|
||||
/** A corpus: its sources, as docx's options, and its citations, each the sources it cites */
|
||||
type Corpus = { readonly sources: readonly Source[]; readonly citations: readonly (readonly CitedSourceOptions[])[] };
|
||||
|
||||
/** What a style writes for a corpus, as markup: each citation, and the bibliography, if it is checked */
|
||||
export type CorpusOutput = {
|
||||
readonly citations: readonly string[];
|
||||
readonly bibliography?:
|
||||
{ readonly hangingIndent: boolean; readonly paragraphs: readonly string[] } | { readonly rows: readonly (readonly string[])[] };
|
||||
};
|
||||
|
||||
const escape = (text: string): string => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
|
||||
/** Text as markup: <b>, <i> and <u> around the text with that formatting, and <br> for a line break */
|
||||
export const markupOf = (text: FormattedText): string =>
|
||||
text
|
||||
.map((run) => {
|
||||
if (run.lineBreak) {
|
||||
return "<br>";
|
||||
}
|
||||
const marks = [run.bold && "b", run.italics && "i", run.underline && "u"].filter((mark): mark is string => !!mark);
|
||||
return (
|
||||
marks.map((mark) => `<${mark}>`).join("") +
|
||||
escape(run.text) +
|
||||
[...marks]
|
||||
.reverse()
|
||||
.map((mark) => `</${mark}>`)
|
||||
.join("")
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
|
||||
/** What the style writes for a corpus, as markup */
|
||||
export const outputOf = (style: StyleDefinition, corpus: Corpus): Required<CorpusOutput> => {
|
||||
const tags = corpus.sources.map(({ tag }) => tag);
|
||||
const order = citationOrderOf(
|
||||
tags,
|
||||
corpus.citations.flatMap((citation) => citation.map(({ source }) => source)),
|
||||
);
|
||||
const sources = corpus.sources.map((source) => wordSourceOf(source, order.get(source.tag)!));
|
||||
const bibliography = formatBibliography(style, sources);
|
||||
return {
|
||||
citations: corpus.citations.map((citation) => markupOf(formatCitation(style, sources, citation))),
|
||||
bibliography:
|
||||
"rows" in bibliography
|
||||
? { rows: bibliography.rows.map((row) => row.map(markupOf)) }
|
||||
: { hangingIndent: bibliography.hangingIndent, paragraphs: bibliography.paragraphs.map(markupOf) },
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Describes the style's tests against what Word writes: a test of each corpus's citations, and of its bibliography where
|
||||
* the fixture has it.
|
||||
*
|
||||
* @param expected - The style's fixture, with what Word writes for each corpus
|
||||
*/
|
||||
export const describeWordOutput = (style: StyleDefinition, expected: Readonly<Record<string, CorpusOutput | string>>): void => {
|
||||
for (const [name, corpus] of Object.entries(corpora as unknown as Readonly<Record<string, Corpus>>)) {
|
||||
// Each fixture has each corpus, and notes
|
||||
const output = expected[name] as CorpusOutput;
|
||||
describe(`corpus ${name}`, () => {
|
||||
it("writes the citations as Word does", () => {
|
||||
expect(outputOf(style, corpus).citations).toEqual(output.citations);
|
||||
});
|
||||
if (output.bibliography) {
|
||||
it("writes the bibliography as Word does", () => {
|
||||
expect(outputOf(style, corpus).bibliography).toEqual(output.bibliography);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A style for testing citations and bibliographies. A citation is each source's tag, the flags Word works out for it and
|
||||
* the switches it is cited with, in brackets, and a bibliography is each source's tag and title, in italics, sorted by
|
||||
* tag: in paragraphs with a hanging indent, or in a table of each source's order and entry.
|
||||
*/
|
||||
export const testStyle = (layout: "paragraphs" | "rows" = "paragraphs"): StyleDefinition => ({
|
||||
name: "Test",
|
||||
file: "TEST.XSL",
|
||||
version: "1",
|
||||
citation: (cited) =>
|
||||
join(
|
||||
cited.first ? "(" : "",
|
||||
cited.prefix ?? "",
|
||||
[
|
||||
cited.source.tag,
|
||||
...(cited.repeatedAuthor ? ["repeated"] : []),
|
||||
...(cited.nonUniqueLastName ? ["initials"] : []),
|
||||
...(cited.minAuthors > 1 ? [`${cited.minAuthors} authors`] : []),
|
||||
...(cited.hideAuthor ? ["no author"] : []),
|
||||
...(cited.hideYear ? ["no year"] : []),
|
||||
...(cited.hideTitle ? ["no title"] : []),
|
||||
...(cited.pages ? [`p. ${cited.pages}`] : []),
|
||||
...(cited.volume ? [`vol. ${cited.volume}`] : []),
|
||||
].join(", "),
|
||||
cited.suffix ?? "",
|
||||
cited.last ? ")" : "; ",
|
||||
),
|
||||
bibliography: (sources) => {
|
||||
const sorted = [...sources].sort((a, b) => a.tag.localeCompare(b.tag));
|
||||
const entry = (source: (typeof sources)[number]): FormattedText => join(`${source.tag} `, italic(fieldOf(source, "Title")), " ");
|
||||
return layout === "rows"
|
||||
? { rows: sorted.map((source) => [join(`[${source.order}] `), entry(source)] as const) }
|
||||
: { paragraphs: sorted.map(entry), hangingIndent: true };
|
||||
},
|
||||
});
|
||||
|
||||
/** A component's XML, written as part of a document's body */
|
||||
export const xmlOf = (component: BaseXmlComponent, file: File): string =>
|
||||
stringifyXmlable(new Formatter().format(component, { file, viewWrapper: file.Document, stack: [] }));
|
||||
@@ -28,6 +28,7 @@ const ENTRIES: Readonly<Record<string, Entry>> = {
|
||||
html: { name: "html", global: "docxHtml" },
|
||||
macros: { name: "macros", global: "docxMacros" },
|
||||
"embedded-files": { name: "embedded-files", global: "docxEmbeddedFiles" },
|
||||
bibliography: { name: "bibliography", global: "docxBibliography" },
|
||||
};
|
||||
|
||||
// API Extractor, which bundles the declarations, copies in those of any module that isn't a library, so it would copy
|
||||
|
||||
Reference in New Issue
Block a user