Skip to content

Commit 2217455

Browse files
committed
Merge origin/develop into bugfix/issue-1380
2 parents b774d3e + fd5c1d0 commit 2217455

15 files changed

Lines changed: 554 additions & 61 deletions

File tree

‎resources/packs-dev/foundation-alt/pack.json‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎resources/packs.lock.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@
33
"packs": {
44
"foundation": {
55
"version": "0.1.0",
6-
"digest": "d03435c6e050a047ed50ba041c8553e28bab6e3f180cb99f43c8ed32d7bac096"
6+
"digest": "52e19dd5c697a670aa0a73f7213a81e1cdcf82920ae4c80fb62f9bb39b9c71de"
77
},
88
"foundation-alt": {
99
"version": "0.1.0",
10-
"digest": "bf4429c297a46d30ee7fab8afb729b1c9a9eb5f7d8b47b8a74a75694dc30b486"
10+
"digest": "8f7ef24aa04600bf3e907c4f66c92a1130e2d8bac8ecb42457dc80c6c86256ce"
1111
}
1212
}
1313
}

‎resources/packs/foundation/pack.json‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎src/engine/tree.ts‎

Lines changed: 133 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { AppearPreset, ComponentDefinition, ElementNode, GraphNode, InstanceNode, NodeTree, OwnerRef, ProjectState } from '@shared/types';
22
import { repeatProp, STYLE_SCOPES, isAppearPreset, isBinding, slotFallback } from '@shared/types';
33
import { pageParents } from '@shared/page-tree';
4+
import { CODE_TEXT_ATTR, CODE_TEXT_HOOK } from '@shared/code-text';
45

56
export class EngineError extends Error {
67
constructor(
@@ -134,26 +135,150 @@ export function enclosingRepeatProp(def: ComponentDefinition, nodeId: string): s
134135
/**
135136
* The links a list repeats whose visible text and destination are two fields of the same item (a contact method's
136137
* value and link): `{ text, link }` field names. Read from the definition's own tree, so a project's copy with
137-
* renamed fields pairs the same way; a code component has no tree to read and pairs nothing. A destination shared
138-
* by two different texts belongs to neither, so it is left out.
138+
* renamed fields pairs the same way, or from a code component's markup (codeItemLinks). A destination shared by two
139+
* different texts belongs to neither, so it is left out.
139140
*/
140141
export function itemLinkPairs(def: ComponentDefinition, listProp: string): Array<{ text: string; link: string }> {
141142
const schema = Object.hasOwn(def.properties, listProp) ? def.properties[listProp] : undefined;
142-
if (!def.tree || schema?.type !== 'list') return [];
143+
if (schema?.type !== 'list') return [];
144+
const shown: Array<{ text: string; link: string }> = [];
145+
if (def.tree) {
146+
for (const n of Object.values(def.tree.nodes)) {
147+
if (n.kind !== 'link' || !isBinding(n.label) || !isBinding(n.link) || !('$item' in n.label) || !('$item' in n.link)) continue;
148+
if (enclosingRepeatProp(def, n.id) === listProp) shown.push({ text: n.label.$item, link: n.link.$item });
149+
}
150+
} else if (def.kind === 'code') shown.push(...codeItemLinks(def.source ?? '', listProp));
143151
const found = new Map<string, { text: string; link: string }>();
144-
for (const n of Object.values(def.tree.nodes)) {
145-
if (n.kind !== 'link' || !isBinding(n.label) || !isBinding(n.link) || !('$item' in n.label) || !('$item' in n.link)) continue;
146-
const text = n.label.$item;
147-
const link = n.link.$item;
152+
for (const { text, link } of shown) {
148153
if (!Object.hasOwn(schema.fields, text) || !Object.hasOwn(schema.fields, link)) continue;
149154
if (schema.fields[text].type !== 'string' || schema.fields[link].type !== 'link') continue;
150-
if (enclosingRepeatProp(def, n.id) !== listProp) continue;
151155
found.set(`${text}\u0000${link}`, { text, link });
152156
}
153157
const pairs = [...found.values()];
154158
return pairs.filter((p) => pairs.filter((q) => q.link === p.link).length === 1);
155159
}
156160

161+
/** `name.field` alone: an item's field, as a link's destination or its only content. */
162+
const ITEM_FIELD = /^\s*([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)\s*$/;
163+
/** The text hook's call for an item's field (src/shared/code-text.ts): its list, field and the item it names. */
164+
const ITEM_TEXT_HOOK = new RegExp(`^\\s*${CODE_TEXT_HOOK}\\s*\\?\\.\\s*\\(\\s*(['"])([A-Za-z][\\w]*)\\.([A-Za-z][\\w]*)\\1\\s*,\\s*([A-Za-z_$][\\w$]*)\\s*\\.`);
165+
/** The SoLinks of a code source, read once per source. */
166+
const codeLinkCache = new Map<string, CodeItemLink[]>();
167+
type CodeItemLink = { list: string; text: string; link: string };
168+
169+
/**
170+
* The links a code component draws for each item of a list, read from the marker that already tells the canvas which
171+
* field a link shows (src/shared/code-text.ts):
172+
* `<SoLink data-so-text={so_text?.('items.value', item.id)} link={item.link}>{item.value}</SoLink>` reads as
173+
* `{ text: 'value', link: 'link' }` of `items`. The marker names the list, so no reading of the blocks around it is
174+
* needed; a link whose marker, destination and content are not all the same item's, or whose tag spreads attributes
175+
* that could replace the link, pairs nothing.
176+
*/
177+
function codeItemLinks(source: string, listProp: string): Array<{ text: string; link: string }> {
178+
let links = codeLinkCache.get(source);
179+
if (!links) {
180+
links = readCodeItemLinks(source);
181+
if (codeLinkCache.size >= 64) codeLinkCache.delete(codeLinkCache.keys().next().value!);
182+
codeLinkCache.set(source, links);
183+
}
184+
return links.filter((l) => l.list === listProp).map(({ text, link }) => ({ text, link }));
185+
}
186+
187+
/**
188+
* Every marked `<SoLink …>{item.field}</SoLink>` of a source, in one forward pass that steps over comments, scripts and
189+
* styles, which draw no links.
190+
*/
191+
function readCodeItemLinks(source: string): CodeItemLink[] {
192+
const out: CodeItemLink[] = [];
193+
const next = /<SoLink|<!--|<(script|style)\b/g;
194+
for (let m = next.exec(source); m; m = next.exec(source)) {
195+
const at = m.index;
196+
if (m[0] === '<!--' || m[1]) {
197+
const close = m[1] ? source.indexOf(`</${m[1]}>`, at) : source.indexOf('-->', at + 4);
198+
if (close < 0) break;
199+
next.lastIndex = close + 1;
200+
continue;
201+
}
202+
const tag = readTag(source, at + '<SoLink'.length);
203+
next.lastIndex = Math.max(tag.end, at + 1);
204+
if (!tag.attrs) continue;
205+
const close = source.indexOf('</SoLink>', tag.end);
206+
// No link closes after this one, so none of the rest has content to read.
207+
if (close < 0) break;
208+
// Content is one short expression: a longer run is not read.
209+
const content = close - tag.end > 400 ? null : /^\s*\{([^{}]*)\}\s*$/.exec(source.slice(tag.end, close));
210+
const shown = content && ITEM_FIELD.exec(content[1]);
211+
const marker = tag.attrs.get(CODE_TEXT_ATTR);
212+
const hook = marker && ITEM_TEXT_HOOK.exec(marker);
213+
const to = tag.attrs.get('link');
214+
const link = to && ITEM_FIELD.exec(to);
215+
// An href or a click handler of its own decides where the link goes instead.
216+
if (!shown || !hook || !link || [...tag.attrs.keys()].some((k) => k === 'href' || /^on(:|[a-z])/i.test(k))) continue;
217+
const [, item, text] = shown;
218+
// An item made in the markup (`{@const item = …}`) is not the stored one, whatever its ID.
219+
if (new RegExp(`\\{@const\\s+${item.replace(/\$/g, '\\$')}\\b`).test(source)) continue;
220+
if (hook[4] === item && link[1] === item && hook[3] === text) out.push({ list: hook[2], text, link: link[2] });
221+
}
222+
return out;
223+
}
224+
225+
/**
226+
* The attributes of a tag from just after its name, with the expressions in braces as written (strings in them
227+
* skipped, braces counted), and where it ends. No attributes when it spreads any, or cannot be read to its `>`.
228+
*/
229+
function readTag(src: string, from: number): { attrs: Map<string, string> | null; end: number } {
230+
const attrs = new Map<string, string>();
231+
let i = from;
232+
const expression = (): string | null => {
233+
const start = i;
234+
let depth = 0;
235+
for (; i < src.length; i++) {
236+
const c = src[i];
237+
if (c === '"' || c === "'" || c === '`') {
238+
const q = src.indexOf(c, i + 1);
239+
// Unclosed to the end: nothing after it is read again.
240+
if (q < 0) return ((i = src.length), null);
241+
i = q;
242+
} else if (c === '{') depth++;
243+
else if (c === '}' && --depth === 0) return src.slice(start + 1, i++);
244+
}
245+
return null;
246+
};
247+
if (!/\s|>|\//.test(src[i] ?? '')) return { attrs: null, end: i };
248+
while (i < src.length) {
249+
while (/\s/.test(src[i] ?? '')) i++;
250+
if (src[i] === '>') return { attrs, end: i + 1 };
251+
if (src.startsWith('/>', i)) return { attrs: null, end: i + 2 };
252+
// A spread, or the `{link}` shorthand: either way what the link opens is not read here.
253+
if (src[i] === '{') return { attrs: null, end: i + 1 };
254+
const name = /^[^\s=/>"'{}<]+/.exec(src.slice(i, i + 200));
255+
if (!name) return { attrs: null, end: i };
256+
i += name[0].length;
257+
let value = '';
258+
while (/\s/.test(src[i] ?? '')) i++;
259+
if (src[i] === '=') {
260+
i++;
261+
while (/\s/.test(src[i] ?? '')) i++;
262+
if (src[i] === '{') {
263+
const v = expression();
264+
if (v === null) return { attrs: null, end: i };
265+
value = v;
266+
} else if (src[i] === '"' || src[i] === "'") {
267+
const q = src.indexOf(src[i], i + 1);
268+
if (q < 0) return { attrs: null, end: src.length };
269+
// Text around expressions, whose quotes can sit inside them, is not read: the tag pairs nothing.
270+
if (src.slice(i, q).includes('{')) return { attrs: null, end: q + 1 };
271+
value = '';
272+
i = q + 1;
273+
} else return { attrs: null, end: i };
274+
}
275+
// An attribute named twice is not one value.
276+
if (attrs.has(name[0])) return { attrs: null, end: i };
277+
attrs.set(name[0], value);
278+
}
279+
return { attrs: null, end: i };
280+
}
281+
157282
/**
158283
* Whether a code component places the override classes it is given (so style changes, hiding included, show).
159284
* A theme's declares the controls its root takes; a project's own shows it in its script by taking `class`

‎src/generator/checks.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3047,10 +3047,10 @@ export function pageHeadings(state: ProjectState, pageId: string, opts: { shell?
30473047

30483048
/**
30493049
* An entry's page as the website has it, around its own text: its collection's layout read for the entry. The text
3050-
* itself is left out, since its links are checked as the entry's own.
3050+
* itself is left out, since its links are checked as the entry's own, unless `body` asks for the page in full.
30513051
*/
3052-
function entryArticle(state: ProjectState, collection: Collection, entry: EntryDoc): NodeTree {
3053-
const tree = materializeTemplate(state, collection, entry, entryNeighbours(state, collection.settings.id, entry.id), { body: false });
3052+
export function entryArticle(state: ProjectState, collection: Collection, entry: EntryDoc, opts: { body?: boolean } = {}): NodeTree {
3053+
const tree = materializeTemplate(state, collection, entry, entryNeighbours(state, collection.settings.id, entry.id), { body: opts.body === true });
30543054
entryTrees.set(tree, { collectionId: collection.settings.id, entryId: entry.id });
30553055
return tree;
30563056
}

‎src/generator/index.ts‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ import { addDiscoveryFiles, hasMarkdownMirror } from './llms';
117117
import { MARKDOWN_MIRROR_FILE } from '@shared/llms';
118118
import { crawlerRules, NOAI_META, siteMount, siteRobotsTxt } from '@shared/crawler-policy';
119119
import { derived, isTracked, type GenerationCache } from './cache';
120-
import { createSeoResolver, entryMetadata, pageMetadata, type SeoMetadata } from './seo-metadata';
120+
import { createSeoResolver, entryMetadata, pageMetadata, sameAddress, type SeoMetadata } from './seo-metadata';
121121
import { ogLocale, twitterHandle, type EffectiveSeo } from '@shared/seo';
122122
import { VIDEO_HELPER_FILE, VIDEO_JS, VIDEO_PLAYER_FILE, usesVideo, videoPlayerSvelte } from './video';
123123
import { APPEAR_CSS, APPEAR_FILE, appearJs, usesAppear } from './appear';
@@ -4332,7 +4332,8 @@ export function generatePage(state: ProjectState, page: PageDoc, opts: GenerateO
43324332
const article = pageArticle(page);
43334333
const base = publicUrl(site);
43344334
const alternates = pageAlternates(state, page);
4335-
const head = seoHead(state, meta, { article: !!article, alternates: alternates.map((a) => a.language) });
4335+
// Open Graph names every published language, whether or not search engines may list that version.
4336+
const head = seoHead(state, meta, { article: !!article, alternates: translationVersions(state, page).map((a) => a.language) });
43364337
// The first section's main picture, asked for straight after the title so it starts loading first.
43374338
const hero = heroPreload(ctx);
43384339
if (hero) head.splice(1, 0, hero);
@@ -4689,11 +4690,10 @@ export function fillParts(text, values) {
46894690
}
46904691

46914692
/**
4692-
* The versions of a published page in each language it has, itself among them, in page order: what its
4693-
* alternate-language links name. None for a draft, for a page without translations, and for a set whose pages
4694-
* clash on language (which the editor never lets happen).
4693+
* The versions of a published page in each language it has, itself among them, in page order. None for a draft, for a
4694+
* page without translations, and for a set whose pages clash on language (which the editor never lets happen).
46954695
*/
4696-
export function pageAlternates(state: ProjectState, page: PageDoc): Array<{ language: string; route: string; pageId: string }> {
4696+
function translationVersions(state: ProjectState, page: PageDoc): Array<{ language: string; route: string; pageId: string }> {
46974697
const group = translationGroup(page);
46984698
if (!group || isDraftPage(state, page)) return [];
46994699
const members = translationMembers(state, group)
@@ -4703,6 +4703,21 @@ export function pageAlternates(state: ProjectState, page: PageDoc): Array<{ lang
47034703
return members.length < 2 || languages.size < members.length ? [] : members;
47044704
}
47054705

4706+
/**
4707+
* The versions a page's alternate-language links name, as the sitemap's do: the published versions that search engines
4708+
* may list. A version hidden from search engines or a copy of another address is named by none, and a page that is one
4709+
* lists none, so a set left with one version has no links.
4710+
*/
4711+
export function pageAlternates(state: ProjectState, page: PageDoc): Array<{ language: string; route: string; pageId: string }> {
4712+
const searchable = (id: string) => {
4713+
const meta = pageMetadata(state, id);
4714+
return !!meta && !meta.noindex && (!meta.url || sameAddress(meta.canonical, meta.url));
4715+
};
4716+
if (!searchable(page.id)) return [];
4717+
const members = translationVersions(state, page).filter((m) => searchable(m.pageId));
4718+
return members.length < 2 ? [] : members;
4719+
}
4720+
47064721
export type { LiveRedirect } from '@shared/redirects';
47074722

47084723
/**

‎src/generator/search.ts‎

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,11 @@
1212
* posts only send visitors on, so they are never results; a page found always links to where it is now.
1313
*/
1414
import type { Collection, ComponentDefinition, EntryDoc, NodeTree, PageDoc, ProjectState, ResponsiveStyles } from '@shared/types';
15-
import { slotChildren } from '@shared/types';
15+
import { isEntryBinding, slotChildren } from '@shared/types';
1616
import { richTextToPlain, toRichText } from '@shared/richtext';
17-
import { renderedContent, showsEntryText } from './checks';
18-
import { siteEntries } from '@shared/collections';
17+
import { entryArticle, renderedContent, type RenderedContent } from './checks';
18+
import { showsBody } from './entry-template';
19+
import { collectionKind, siteEntries } from '@shared/collections';
1920
import { isDraftPage, publishedState } from './index';
2021

2122
/** The search code, imported by the Site search component from the runtime folder. */
@@ -76,17 +77,22 @@ export function hiddenLayers(tree: NodeTree): Set<string> {
7677
const inside = n?.kind === 'element' ? n.children : n?.kind === 'instance' ? Object.keys(n.slots ?? {}).flatMap((k) => slotChildren(n, k)) : [];
7778
for (const c of inside) hide(c);
7879
};
79-
for (const n of Object.values(tree.nodes)) if (hiddenEverywhere(n.kind === 'instance' ? n.overrides?.root : n.styles)) hide(n.id);
80+
for (const n of Object.values(tree.nodes)) if (n && typeof n === 'object' && hiddenEverywhere(n.kind === 'instance' ? n.overrides?.root : n.styles)) hide(n.id);
8081
return out;
8182
}
8283

8384
/** The words a page shows, one line per field that shows any: its text, rich text, button labels and list items. */
8485
export function pageText(state: ProjectState, page: PageDoc): string {
86+
return treeText(state, page);
87+
}
88+
89+
/** The words a tree shows, one line per field that shows any, less the content `skip` says is found otherwise. */
90+
function treeText(state: ProjectState, tree: NodeTree, skip?: (c: RenderedContent) => boolean): string {
8591
const lines: string[] = [];
86-
const hidden = hiddenLayers(page);
87-
for (const c of renderedContent(state, page)) {
92+
const hidden = hiddenLayers(tree);
93+
for (const c of renderedContent(state, tree)) {
8894
// Where a link goes is not something the visitor reads, and what custom code shows of a setting is unknown.
89-
if (c.kind !== 'text' || c.custom || hidden.has(c.nodeId)) continue;
95+
if (c.kind !== 'text' || c.custom || hidden.has(c.nodeId) || skip?.(c)) continue;
9096
let text = '';
9197
if (typeof c.value === 'string' || typeof c.value === 'number') text = c.rich && typeof c.value === 'string' ? plain(c.value) : String(c.value);
9298
else if (c.rich && Array.isArray(c.value)) text = plain(c.value);
@@ -111,12 +117,38 @@ export function entrySearchHidden(entry: EntryDoc): boolean {
111117
return !!entry.seo?.searchHidden;
112118
}
113119

120+
/**
121+
* The entry fields a record's layout shows that search does not read from its page: the title, excerpt and text, found
122+
* as the entry's own, and the links to the entries before and after it, which name other records.
123+
*/
124+
const FOUND_OTHERWISE: ReadonlySet<string> = new Set(['title', 'excerpt', 'body', 'prevEntry', 'prevEntry.title', 'prevEntry.label', 'nextEntry', 'nextEntry.title', 'nextEntry.label', 'entryNavLabel']);
125+
126+
/** The entry field a piece of an entry's page reads, by the layout's own binding at the node that shows it. */
127+
function readsEntry(template: NodeTree | undefined, c: RenderedContent): string | undefined {
128+
const node = template?.nodes && Object.hasOwn(template.nodes, c.nodeId) ? (template.nodes[c.nodeId] as unknown as Record<string, unknown>) : undefined;
129+
if (!node || !c.source) return undefined;
130+
const props = node.props as Record<string, unknown> | undefined;
131+
const binding = c.source.kind === 'node' ? node[c.source.field] : !c.source.itemId && props && Object.hasOwn(props, c.source.prop) ? props[c.source.prop] : undefined;
132+
return isEntryBinding(binding) ? binding.$entry : undefined;
133+
}
134+
114135
/**
115136
* The words of an entry search finds: its excerpt, and its text where its page shows it (a collection layout without
116-
* the entry's text leaves it off the website, as the Markdown copies do), one line per field that has any.
137+
* the entry's text leaves it off the website, as the Markdown copies do), one line per field that has any. A record
138+
* (an entry of a structured collection) is also found by everything else its page shows: its custom fields and
139+
* groupings as its layout places them (a price as the site writes it, a choice by its label, its categories' names),
140+
* and the layout's own words, less what a condition or a hide leaves off its page.
117141
*/
118142
export function entryText(state: ProjectState, collection: Collection, entry: EntryDoc): string {
119-
return [oneLine(entry.excerpt), showsEntryText(state, collection, entry) ? oneLine(plain(entry.body)) : ''].filter(Boolean).join('\n');
143+
// The page in full, its text included, so a section that shows something only beside the text shows it here too;
144+
// the text itself is read once, from the entry.
145+
const article = entryArticle(state, collection, entry, { body: true });
146+
const lines = [oneLine(entry.excerpt), showsBody(collection, article) ? oneLine(plain(entry.body)) : ''];
147+
if (collectionKind(collection.settings) === 'structured') {
148+
const template = collection.settings.template;
149+
lines.push(treeText(state, article, (c) => FOUND_OTHERWISE.has(readsEntry(template, c) ?? '')));
150+
}
151+
return lines.filter(Boolean).join('\n');
120152
}
121153

122154
/**

0 commit comments

Comments
 (0)