Notes/src/services/attribute_formatter.ts

47 lines
1.0 KiB
TypeScript
Raw Normal View History

"use strict";
2021-05-02 19:59:16 +02:00
import { AttributeRow } from "../becca/entities/rows.js";
2024-02-17 19:15:50 +02:00
2024-02-18 11:26:05 +02:00
function formatAttrForSearch(attr: AttributeRow, searchWithValue: boolean) {
2025-01-09 18:07:02 +02:00
let searchStr = "";
2021-05-02 19:59:16 +02:00
2025-01-09 18:07:02 +02:00
if (attr.type === "label") {
searchStr += "#";
} else if (attr.type === "relation") {
searchStr += "~";
} else {
2021-05-02 19:59:16 +02:00
throw new Error(`Unrecognized attribute type ${JSON.stringify(attr)}`);
}
searchStr += attr.name;
if (searchWithValue && attr.value) {
2025-01-09 18:07:02 +02:00
if (attr.type === "relation") {
2021-05-02 19:59:16 +02:00
searchStr += ".noteId";
}
2025-01-09 18:07:02 +02:00
searchStr += "=";
2021-05-02 19:59:16 +02:00
searchStr += formatValue(attr.value);
}
return searchStr;
}
2024-02-17 19:15:50 +02:00
function formatValue(val: string) {
if (!/[^\w]/.test(val)) {
2021-05-02 19:59:16 +02:00
return val;
2025-01-09 18:07:02 +02:00
} else if (!val.includes('"')) {
return `"${val}"`;
2025-01-09 18:07:02 +02:00
} else if (!val.includes("'")) {
return `'${val}'`;
2025-01-09 18:07:02 +02:00
} else if (!val.includes("`")) {
return `\`${val}\``;
2025-01-09 18:07:02 +02:00
} else {
return `"${val.replace(/"/g, '\\"')}"`;
2021-05-02 19:59:16 +02:00
}
}
export default {
2021-05-02 19:59:16 +02:00
formatAttrForSearch
};