Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Add updated in Deck and NoteType #6

Merged
merged 1 commit into from
Mar 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 1 addition & 20 deletions __snapshots__/deck.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,7 @@ snapshot[`parseDeck() 1`] = `
description: "システム英単語系の問題集",
id: 44845749858349580,
name: "system-english",
},
}
`;

snapshot[`parseDeck() 2`] = `
{
ok: true,
value: {
id: 44845749858349580,
name: "system-english",
},
}
`;

snapshot[`parseDeck() 3`] = `
{
ok: false,
value: {
message: "Deck name not found.",
name: "InvalidDeckError",
updated: 1676275415,
},
}
`;
1 change: 1 addition & 0 deletions __snapshots__/noteType.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ snapshot[`parseNoteType() 1`] = `
{{type:Text}}",
},
],
updated: 1676275810,
},
}
`;
19 changes: 2 additions & 17 deletions deck.test.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,7 @@
import { assertSnapshot } from "./deps/testing.ts";
import { parseDeck } from "./deck.ts";
import lines from "./sample-deck1.json" assert { type: "json" };

Deno.test("parseDeck()", async (t) => {
await assertSnapshot(
t,
parseDeck(`id,44845749858349584
name,system-english
description,システム英単語系の問題集`),
);
await assertSnapshot(
t,
parseDeck(`id,44845749858349584
name,system-english`),
);
await assertSnapshot(
t,
parseDeck(`id,44845749858349584
name,
description,システム英単語系の問題集`),
);
await assertSnapshot(t, parseDeck(lines));
});
92 changes: 76 additions & 16 deletions deck.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,90 @@
import type { Result } from "./deps/scrapbox.ts";
import { parse } from "./deps/csv.ts";
import { BaseLine } from "./deps/scrapbox.ts";
import type { Deck } from "./deps/deno-anki.ts";
import { packRows, parseToRows } from "./deps/scrapbox-parser.ts";

/** deckデータの書式が不正だったときに投げるエラー */
export interface InvalidDeckError {
name: "InvalidDeckError";
message: string;
}

export const parseDeck = (csv: string): Result<Deck, InvalidDeckError> => {
const data = parse(csv);
const csvData = new Map<string, string>(data.map(([f, s]) => [f, s]));
const name = csvData.get("name");
if (!name) return { ok: false, value: makeError("Deck name not found.") };
const id_ = csvData.get("id");
if (!id_) return { ok: false, value: makeError("Deck id not found.") };
const id = parseInt(id_);
if (isNaN(id)) {
return { ok: false, value: makeError("Deck id is not number.") };
}
/** ページ本文からDeckを抽出する
*
* @param lines メタデータつきページ本文
* @return 解析結果。テーブルが見つからなければ`undefined`を返す
*/
export const parseDeck = (
lines: BaseLine[],
): Result<Deck | undefined, InvalidDeckError> => {
if (lines.length === 0) return { ok: true, value: undefined };
const packs = packRows(
parseToRows(lines.map((line) => line.text).join("\n")),
{ hasTitle: true },
);

/** deck id */
let id: number | undefined;
/** deck name */
let name: string | undefined;
/** deck description */
let description: string | undefined;
/** the updated time of the deck (UNIX time) */
let updated = 0;

/** 現在読んでいる`pack.rows[0]`の行番号 */
let counter = 0;
// deckが書かれたtableから各設定を読み出す
for (const pack of packs) {
switch (pack.type) {
case "title":
case "line":
counter++;
break;
case "codeBlock":
counter += pack.rows.length;
break;
case "table": {
updated = Math.max(
...lines.slice(counter, counter + pack.rows.length).map((line) =>
line.updated
),
updated,
);
counter += pack.rows.length;
// filenameが"deck"のもののみ通す
if (!pack.rows[0].text.endsWith("deck")) break;
const table = Object.fromEntries(
pack.rows.map(({ text }) => text.trim().split(/\s+/)),
) as Record<string, string>;

const deck: Deck = { name, id };
const description = csvData.get("description");
if (description) deck.description = description;
if (Object.hasOwn(table, "name") && !name) {
if (!table.name) {
return { ok: false, value: makeError("Deck name not found.") };
}
name = table.name;
}
if (Object.hasOwn(table, "id") && !id) {
if (!table.id) {
return { ok: false, value: makeError("Deck id not found.") };
}
const idNum = parseInt(table.id);
if (isNaN(idNum)) {
return { ok: false, value: makeError("Deck id is not number.") };
}
id = idNum;
}
description ??= table["description"];

break;
}
}
}

return { ok: true, value: deck };
return {
ok: true,
value: id && name ? { id, name, description, updated } : undefined,
};
};

const makeError = (message: string): InvalidDeckError => ({
Expand Down
45 changes: 27 additions & 18 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import {
getTable,
getPage,
NotFoundError,
NotLoggedInError,
NotMemberError,
Page,
Result,
TooLongURIError,
} from "./deps/scrapbox.ts";
import {
Deck,
Expand All @@ -16,23 +17,25 @@ import { JSZip } from "./deps/jsZip.ts";
import { SqlJsStatic } from "./deps/sql.ts";
import { parseNotes, Path } from "./note.ts";
import { InvalidDeckError, parseDeck } from "./deck.ts";
import { InvalidNoteTypeError, parseNoteType } from "./noteType.ts";
import {
defaultNoteType,
InvalidNoteTypeError,
parseNoteType,
} from "./noteType.ts";

/** 既定のdeck */
const defaultDeck: Deck = {
name: "default",
id: 1,
};

/** 既定のNote type */
// @ts-ignore NoteTypeしか帰ってこないはず
const defaultNoteType: NoteType = parseNoteType(`name,Basic (Cloze)
id,1677417085373
isCloze,true`).value;

type DeckResult = Result<
Deck,
InvalidDeckError | NotFoundError | NotLoggedInError | NotMemberError
Deck | undefined,
| InvalidDeckError
| NotFoundError
| NotLoggedInError
| NotMemberError
| TooLongURIError
>;

/** 読み込んだdecksのcache
Expand All @@ -54,17 +57,21 @@ const getDeck = (path: Path | undefined): Promise<DeckResult> => {
if (deck) return deck;

const promise = (async () => {
const result = await getTable(path.project, path.title, "deck");
const result = await getPage(path.project, path.title);
if (!result.ok) return result;
return parseDeck(result.value);
return parseDeck(result.value.lines);
})();
decks.set(toKey(path), promise);
return promise;
};

type NoteTypeResult = Result<
NoteType,
InvalidNoteTypeError | NotFoundError | NotLoggedInError | NotMemberError
NoteType | undefined,
| InvalidNoteTypeError
| NotFoundError
| NotLoggedInError
| NotMemberError
| TooLongURIError
>;

/** 読み込んだnote typesのcache
Expand All @@ -84,9 +91,9 @@ const getNoteType = (path: Path | undefined): Promise<NoteTypeResult> => {
if (noteType) return noteType;

const promise = (async () => {
const result = await getTable(path.project, path.title, "note type");
const result = await getPage(path.project, path.title);
if (!result.ok) return result;
return parseNoteType(result.value);
return parseNoteType(result.value.lines);
})();
noteTypes.set(toKey(path), promise);
return promise;
Expand All @@ -113,12 +120,14 @@ export const makeApkg = async (
if (!deckRes.ok) {
console.warn(`${deckRes.value.name} ${deckRes.value.message}`);
}
const deck = deckRes.ok ? deckRes.value : defaultDeck;
const deck = deckRes.ok ? (deckRes.value ?? defaultDeck) : defaultDeck;
const noteTypeRes = await getNoteType(noteTypeRef);
if (!noteTypeRes.ok) {
console.warn(`${noteTypeRes.value.name} ${noteTypeRes.value.message}`);
}
const noteType = noteTypeRes.ok ? noteTypeRes.value : defaultNoteType;
const noteType = noteTypeRes.ok
? (noteTypeRes.value ?? defaultNoteType)
: defaultNoteType;
return notes_.map((note) => ({ deck, noteType, ...note }));
}))).flat();

Expand Down
12 changes: 2 additions & 10 deletions noteType.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
import { parseNoteType } from "./noteType.ts";
import { assertSnapshot } from "./deps/testing.ts";
import lines from "./sample-noteType1.json" assert { type: "json" };

Deno.test("parseNoteType()", async (t) => {
await assertSnapshot(
t,
parseNoteType(
`name,システム英単語用穴埋め問題
id,343480954545
isCloze,true
latex
css,https://scrapbox.io/api/code/takker/システム英単語用穴埋め問題案1/css`,
),
);
await assertSnapshot(t, parseNoteType(lines));
});
Loading