Skip to content

Commit

Permalink
feat: extract
Browse files Browse the repository at this point in the history
  • Loading branch information
ikkz committed Dec 30, 2024
1 parent 07d0042 commit 4b850de
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion release.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
{
"fields": {
"question": "This is the stem of the question. It supports various content formats in Anki, including bold, formulas, etc.",
"items": "<ul><li>T: All sub-questions should be in an unordered list format</li><li>T: Each sub-question must begin with \"T:\" or \"F:\", indicating whether the sub-question is true or false<br></li><li>T: Pay special attention to ensuring \"T/F\" is followed by an English half-width colon<br></li></ul>",
"items": "T===<br>All sub-questions should meet the format constriant<br><br>T===<br>Each sub-question must begin with a line \"T===\" or \"F===\", indicating whether the sub-question is true or false<br><br>T===<br>Pay special attention to ensuring \"T/F\" is followed by three or more equal signs",
"note": "note"
}
}
Expand Down
39 changes: 39 additions & 0 deletions src/utils/extract-tf-items.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
function isBrNode(node?: Node | null): node is HTMLBRElement {
return node?.nodeType === Node.ELEMENT_NODE && node.nodeName === 'BR';
}

export interface TfItem {
node: HTMLDivElement;
answer: boolean;
Expand All @@ -7,6 +11,41 @@ export function extractTfItems(field: HTMLElement): TfItem[] {
if (!field) {
return [];
}
const textContent = field.textContent?.trim();
if (!textContent) {
return [];
}
if (!/[TF]={3,}/.test(textContent)) {
return extractTfItemsLegacy(field);
}

const items: TfItem[] = [];
const childNodes = Array.from(field.childNodes);
for (const node of childNodes) {
const childText = node.textContent || '';
const match = childText.match(/^(T|F)={3,}/);
const last = items[items.length - 1];
if (match) {
items.push({
answer: match[1] === 'T',
node: document.createElement('div'),
});
if (last) {
while (isBrNode(last.node.lastChild)) {
last.node.lastChild.remove();
}
}
} else {
if (last && !(last.node.childNodes.length === 0 && isBrNode(node))) {
last.node.appendChild(node);
}
}
}
console.log(items);
return items;
}

export function extractTfItemsLegacy(field: HTMLElement): TfItem[] {
const itemNodes = field.querySelector('ul')?.querySelectorAll(':scope > li');
if (!itemNodes?.length) {
return [];
Expand Down

0 comments on commit 4b850de

Please sign in to comment.