Skip to content

Commit

Permalink
fix lumeland#556 get attribute data from CSS query
Browse files Browse the repository at this point in the history
Tasks:
- improve `getDataValue()` function
- add test cases
- update CHANGELOG
  • Loading branch information
ngdangtu-vn committed Jan 20, 2024
1 parent 27c7bfc commit 5c8e246
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Go to the `v1` branch to see the changelog of Lume 1.
// New
import { gl } from "npm:date-fns/locale/gl";
```
- Allow to get value from attribute in CSS query of `getDataValue()` function. See `metas` plugin for a clear example.

### Fixed
- Pages filtered with `filter_pages` plugin are exported to the sitemap.
Expand Down
20 changes: 16 additions & 4 deletions core/utils/data_values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ export function getDataValue(data: Partial<Data>, value?: unknown) {
}

if (value.startsWith("$")) {
const document = data.page?.document;
const query = value.slice(1);
const element = document?.querySelector(query);
return element?.innerHTML;
return queryCss(value, data.page?.document);
}
}

Expand All @@ -37,3 +34,18 @@ export function getDataValue(data: Partial<Data>, value?: unknown) {

return value;
}

function queryCss(value: string, document?: Document) {
// https://regexr.com/7qnot
const checkForAttrPattern = /^\$(.+)\s+(?:attr\(([\w\-]+)\))$/;
const checkResult = value.match(checkForAttrPattern);

const hasAttr = checkResult?.[0];
if (hasAttr) {
const [_, query, name] = checkResult;
return document?.querySelector(query)?.getAttribute(name);
}

const query = value.slice(1);
return document?.querySelector(query)?.innerHTML;
}
32 changes: 32 additions & 0 deletions tests/core/utils/data_values.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { assertStrictEquals as equals } from "../../../deps/assert.ts";
import { getDataValue } from "../../../core/utils/data_values.ts";
import { build, getSite } from "../../utils.ts";
import metas from "../../../plugins/metas.ts";

Deno.test("Test getDataValue() function", async (t) => {
const site = getSite({ src: "metas" });

site.use(metas());
site.process([".html"], async (pages) => {
for (const page of pages) {
const { data } = page;
if (!data.cover) continue;

await t.step(
"Data query: =",
() => equals(getDataValue(data, data.metas.image), data.cover),
);

await t.step(
"CSS query: $",
() =>
equals(
getDataValue(data, '$meta[property="og:image"] attr(content)'),
new URL(site.url(data.cover), site.url(page.data.url, true)).href,
),
);
}
});

await build(site);
});

0 comments on commit 5c8e246

Please sign in to comment.