From 86b8ff120962000ece4b75c8fab28f18edf8cfa4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:01:39 -0500 Subject: [PATCH 01/38] feat(import): the import review names the hosts a page loads stylesheets and scripts from, in plain words and as an outside list for programs, starts such an import on Code sections with the reason, and the result names the hosts whose files were not brought along; nothing is fetched --- backend/app/authoring_tools.py | 2 +- backend/app/site_import.py | 61 ++++++++++++++++-- frontend/src/features/library/bring.ts | 28 +++++++- frontend/src/features/library/importer.ts | 20 +++++- frontend/src/features/library/site-import.ts | 67 +++++++++++++++++--- frontend/src/features/library/types.ts | 4 +- frontend/src/styles/library.css | 5 ++ 7 files changed, 168 insertions(+), 19 deletions(-) diff --git a/backend/app/authoring_tools.py b/backend/app/authoring_tools.py index 172a9bcb..f2f8e071 100644 --- a/backend/app/authoring_tools.py +++ b/backend/app/authoring_tools.py @@ -50,7 +50,7 @@ {'starter': IDENT, 'values': FIELD_VALUES, 'update_components': {'type': 'boolean', 'default': False}}, ['starter']), tool('library_import_html', 'Import a finished HTML page as one code section: style tags become its css, the first inline script its js, the body markup its html. Allows code sections on the site. One undo step; the result runs in the exported site, not on the canvas. With bring_in elements the open editor window then converts it to editable elements (a second undo step) and conversion holds its result sentence; with no window open it stays a code section and conversion says so.', {'html': {'type': 'string', 'minLength': 1, 'maxLength': 1048576}, 'css': {'type': 'string', 'maxLength': 262144}, 'name': {'type': 'string', 'maxLength': 120}, 'parent': NODE, 'page': NODE, 'index': {'type': 'integer', 'minimum': 0}, 'bring_in': BRING_IN}, ['html']), - tool('library_import_site', 'Import a static site from a zip (data: the .zip bytes as base64): every HTML file becomes a page holding one code section with its local stylesheets and first script, pictures and WOFF2 fonts are stored as assets, and links between the pages follow their new routes. action review (default) changes nothing and lists the pages with their routes, the assets, the skipped files with reasons, canReplace and the revision; show it to the person. action import adds them as new pages (mode new) or swaps the content of pages whose route matches (mode replace, only when the review says canReplace), in one undo step; pass the review\'s revision as expected_revision (the older name revision is still accepted) so a site changed since is refused. At most about 48 MiB of zip through this tool, 1,000 files outside node_modules, __MACOSX and dot folders (40,000 entries in all), 100 pages and 128 MiB unpacked. A zip of a project\'s source (package.json with no HTML page, .ts, .tsx, .jsx, .vue or .svelte files under its src folder or loaded by a page, a %PUBLIC_URL% placeholder, or a module script that imports a package by name with no import map) is refused: build it and zip the output folder. With bring_in elements the open editor window then converts the imported pages to editable elements (a second undo step) and conversion holds its result sentence; with no window open they stay code sections and conversion says so.', + tool('library_import_site', 'Import a static site from a zip (data: the .zip bytes as base64): every HTML file becomes a page holding one code section with its local stylesheets and first script, pictures and WOFF2 fonts are stored as assets, and links between the pages follow their new routes. action review (default) changes nothing and lists the pages with their routes, warnings and outside (the stylesheets and scripts the page loads from other hosts, in document order: kind, host and url, at most 20, with outsideMore counting the rest; they are named, never fetched, and do not come along), the assets, the skipped files with reasons, canReplace and the revision; show it to the person. action import adds them as new pages (mode new) or swaps the content of pages whose route matches (mode replace, only when the review says canReplace), in one undo step; pass the review\'s revision as expected_revision (the older name revision is still accepted) so a site changed since is refused. At most about 48 MiB of zip through this tool, 1,000 files outside node_modules, __MACOSX and dot folders (40,000 entries in all), 100 pages and 128 MiB unpacked. A zip of a project\'s source (package.json with no HTML page, .ts, .tsx, .jsx, .vue or .svelte files under its src folder or loaded by a page, a %PUBLIC_URL% placeholder, or a module script that imports a package by name with no import map) is refused: build it and zip the output folder. With bring_in elements the open editor window then converts the imported pages to editable elements (a second undo step) and conversion holds its result sentence; with no window open they stay code sections and conversion says so.', {'data': {'type': 'string', 'minLength': 4, 'maxLength': 67108864}, 'action': {'type': 'string', 'enum': ['review', 'import'], 'default': 'review'}, 'mode': {'type': 'string', 'enum': ['new', 'replace'], 'default': 'new'}, 'bring_in': BRING_IN, 'expected_revision': {**REVISION, 'description': 'The revision the review returned. A site changed since then is refused without changing anything.'}, 'revision': {'type': 'integer', 'minimum': 0, 'description': 'Older name for expected_revision, still accepted; expected_revision wins when both are given.'}}, ['data'], destructive=True), tool('send_to_formpublisher', 'Send the open site to FormPublisher on this computer, as File > Send to FormPublisher does: delivered "live" when FormPublisher is running (returns its site id and revision), or "inbox" with the path of the zip it will import next time it runs. Also returns warnings: the export\'s own warning strings, the same as export_site gives. Does not change the site.', {'locale': {'type': 'string', 'maxLength': 40}}), diff --git a/backend/app/site_import.py b/backend/app/site_import.py index 3b6b2d51..3649140f 100644 --- a/backend/app/site_import.py +++ b/backend/app/site_import.py @@ -13,7 +13,7 @@ import zipfile import zlib from html import escape, unescape -from urllib.parse import unquote, urlsplit +from urllib.parse import unquote, urlsplit, urlunsplit from .assets import SIZE_LIMITS, check_upload_svg, ingest, own_asset, sniff_extension from .config import MAX_IMAGE_BYTES, MAX_SITE_ARCHIVE_BYTES @@ -62,6 +62,51 @@ PAIR = re.compile(r'''([A-Za-z_:][-A-Za-z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>=`]+)))?''') CSS_URL = re.compile(r'''url\(\s*(?:"([^"]*)"|'([^']*)'|([^()'"\s]*))\s*\)''', re.I) CSS_IMPORT = re.compile(r'''@import\s+(?:url\(\s*)?["']?([^"')\s;]+)["']?\s*\)?([^;{}@]*);''', re.I) +OUTSIDE_SHOWN = 20 +URL_MAX = 2048 +HOST_MAX = 253 +HOST_CHARS = frozenset('abcdefghijklmnopqrstuvwxyz0123456789-') +DEFAULT_PORTS = {'http': 80, 'https': 443} + + +def outside_file(kind: str, reference: str) -> dict | None: + """A file a page loads from another host, as the review names it: its kind, the lower-cased ASCII host (with the port + only when it is not the scheme's default; any port of a protocol-relative URL) and the URL without credentials. None + for anything that is not plainly an http, https or protocol-relative URL with a host of letters, digits and hyphens.""" + value = reference.strip(' \t\n\r\f').replace('\t', '').replace('\n', '').replace('\r', '') + if not value or len(value) > URL_MAX or not value.isprintable(): + return None + try: + parts = urlsplit(value) + port = parts.port + raw = parts.hostname or '' + except ValueError: + return None + scheme = parts.scheme.lower() + if not (scheme in DEFAULT_PORTS or (not scheme and value.startswith('//'))) or not parts.netloc: + return None + raw = raw[:-1] if raw.endswith('.') else raw + if not raw or len(raw) > HOST_MAX: + return None + try: + host = raw.encode('idna').decode('ascii').lower() + except (UnicodeError, ValueError): + return None + if len(host) > HOST_MAX or not all(0 < len(label) <= 63 and label[0] != '-' and label[-1] != '-' and set(label) <= HOST_CHARS for label in host.split('.')): + return None + shown = host if port is None or port == DEFAULT_PORTS.get(scheme) else f'{host}:{port}' + return {'kind': kind, 'host': shown, 'url': urlunsplit((scheme, shown, parts.path, parts.query, parts.fragment))} + + +def outside_list(found: list[tuple[str, str]]) -> tuple[list[dict], int]: + """The outside files of one page in document order, each URL once: at most OUTSIDE_SHOWN, and how many more there are.""" + listed, seen = [], set() + for kind, reference in found: + item = outside_file(kind, reference) + if item and item['url'] not in seen: + seen.add(item['url']) + listed.append(item) + return listed[:OUTSIDE_SHOWN], max(0, len(listed) - OUTSIDE_SHOWN) def _show(name: str) -> str: @@ -383,6 +428,7 @@ def __init__(self, files: dict): self.loops: set = set() self.deep: set = set() self.outside: list[str] = [] + self.listing: list[tuple[str, str]] | None = None self.assets ={path: '/api/assets/' + hashlib.sha256(body).hexdigest() + '.' + STORED.get(_ext(path), _ext(path)) for path, (kind, body) in files.items() if kind == 'asset'} @@ -437,6 +483,8 @@ def css(self, text: str, base: str, missing: set, depth: int = 0, seen: frozense def imported(match): found = self.locate(match.group(1), base) if found is None and not match.group(1).strip().lower().startswith('data:'): + if self.listing is not None: + self.listing.append(('stylesheet', match.group(1))) if match.group(0) not in self.outside: self.outside.append(match.group(0)) return '' @@ -511,7 +559,7 @@ def _page(site: Site, path: str, body: bytes, kit_script) -> dict: missing: set = set() warnings: list[str] = [] outside_scripts, outside_styles = set(), set() - site.used, site.room, site.overflow, site.loops, site.deep, site.outside = set(), CSS_CAP, False, set(), set(), [] + site.used, site.room, site.overflow, site.loops, site.deep, site.outside, site.listing = set(), CSS_CAP, False, set(), set(), [], [] title = TITLE.search(document) title = re.sub(r'\s+', ' ', unescape(title.group(1))).strip()[:200] if title else '' description = '' @@ -539,6 +587,7 @@ def _page(site: Site, path: str, body: bytes, kit_script) -> dict: found = site.locate(source, base) if found is None: outside_scripts.add(source[:120]) + site.listing.append(('script', source)) elif found[0] in site.files and site.files[found[0]][0] == 'script': content = _text(site.files[found[0]][1]) if content.strip(): @@ -554,6 +603,7 @@ def _page(site: Site, path: str, body: bytes, kit_script) -> dict: href = attrs.get('href', '') found = site.locate(href, base) if found is None: + site.listing.append(('stylesheet', href)) if href.strip() and block.start() < body_at: outside_styles.add(href[:120]) elif found[0] in site.files and site.files[found[0]][0] == 'style': @@ -565,6 +615,8 @@ def _page(site: Site, path: str, body: bytes, kit_script) -> dict: styles.append(f'@media {media} {{\n{css}\n}}' if media and media.lower() != 'all' else css) else: missing.add(href) + outside, more = outside_list(site.listing) + site.listing = None script, module = '', False if scripts: if len(scripts) > 1: @@ -598,7 +650,8 @@ def _page(site: Site, path: str, body: bytes, kit_script) -> dict: shown = sorted(missing) warnings.append(f'{len(shown)} reference{"s" if len(shown) != 1 else ""} point{"" if len(shown) != 1 else "s"} at files that were skipped or are not in the archive: {", ".join(item[:80] for item in shown[:5])}{"..." if len(shown) > 5 else ""}.') name = (title or posixpath.basename(path).rsplit('.', 1)[0] or 'Imported page')[:120] - return {'file': path, 'name': name, 'title': title, 'description': description, 'html': markup, 'css': css, 'js': script.strip(), 'module': module and bool(script.strip()), 'warnings': warnings, 'overflow': site.overflow} + return {'file': path, 'name': name, 'title': title, 'description': description, 'html': markup, 'css': css, 'js': script.strip(), 'module': module and bool(script.strip()), 'warnings': warnings, 'overflow': site.overflow, + 'outside': outside, 'outsideMore': more} def _emptiable(site: dict, root: str) -> bool: @@ -681,7 +734,7 @@ def plan(archive: dict, site: dict, kit_script) -> dict: def review(result: dict) -> dict: pages = [{'file': p['file'], 'name': p['name'], 'title': p['title'], 'description': p['description'], 'route': p['route'], 'newRoute': p['newRoute'], - 'replaces': p['replaces'], 'bytes': p['bytes'], 'warnings': p['warnings']} for p in result['pages']] + 'replaces': p['replaces'], 'bytes': p['bytes'], 'warnings': p['warnings'], 'outside': p['outside'], 'outsideMore': p['outsideMore']} for p in result['pages']] matched = [p['replaces'] for p in pages if p['replaces']] blocked = [m['name'] for m in matched if not m['safe']] reason = '' diff --git a/frontend/src/features/library/bring.ts b/frontend/src/features/library/bring.ts index 96e56bad..3bf69ac6 100644 --- a/frontend/src/features/library/bring.ts +++ b/frontend/src/features/library/bring.ts @@ -1,7 +1,10 @@ -import { element } from '../../ui/dom'; +import { element, text as write } from '../../ui/dom'; import { label, labelAttr } from '../../i18n'; export type Bring = 'elements' | 'code'; +/** One sentence per choice, shown under the choice for the one picked; both hold their place so a pick moves nothing. */ +export type BringWhy = Record; +let made = 0; const CHOICES: [Bring, string, string][] = [ ['elements', 'Editable elements (recommended for editing)', 'Each heading, paragraph, picture and box becomes an element you can click, retype, restyle and drag. The look is measured at desktop width; responsive rules are not carried over, and scripts and frames stay as small code sections.'], @@ -9,12 +12,18 @@ const CHOICES: [Bring, string, string][] = [ ]; /** The "Bring pages in as" choice shared by Import HTML and Import site from zip; mounted once, painted by state. */ -export function bringChoice(heading: string): { element: HTMLElement; value(): Bring; disable(on: boolean): void; heading(english: string): void } { +export function bringChoice(heading: string): { element: HTMLElement; value(): Bring; disable(on: boolean): void; heading(english: string): void; choose(value: Bring): void; explain(why: BringWhy | null): void } { const box = element('div', 'fw-lib-bring'); const head = element('h3', 'fw-lib-subhead'); label(head, heading); const group = element('div', 'fw-lib-bring-list'); group.setAttribute('role', 'radiogroup'); + const why = element('div', 'fw-lib-bring-why'); + why.hidden = true; + why.dataset.noI18n = ''; + const lines = { elements: element('p', 'fw-lib-row-meta'), code: element('p', 'fw-lib-row-meta') } as Record; + made += 1; + for (const [id, line] of Object.entries(lines)) { line.id = `fw-bring-why-${made}-${id}`; why.append(line); } let chosen: Bring = 'elements'; const buttons = CHOICES.map(([id, title, note]) => { const button = element('button', 'fw-lib-bring-option'); @@ -36,13 +45,26 @@ export function bringChoice(heading: string): { element: HTMLElement; value(): B button.classList.toggle('is-on', on); button.setAttribute('aria-checked', String(on)); } + for (const [id, line] of Object.entries(lines)) { + line.classList.toggle('is-on', id === chosen); + line.setAttribute('aria-hidden', String(id !== chosen)); + } + if (why.hidden) group.removeAttribute('aria-describedby'); + else group.setAttribute('aria-describedby', lines[chosen].id); }; labelAttr(group, 'aria-label', heading); paint(); - box.append(head, group); + box.append(head, group, why); let named = heading; return { element: box, value: () => chosen, disable: on => buttons.forEach(button => { button.disabled = on; }), + choose: value => { chosen = value; paint(); }, + explain: given => { + for (const [id, line] of Object.entries(lines)) write(line, given?.[id as Bring] || ''); + if (why.hidden === !given) return; + why.hidden = !given; + paint(); + }, heading: english => { if (english === named) return; named = english; diff --git a/frontend/src/features/library/importer.ts b/frontend/src/features/library/importer.ts index e2a1235e..f97ca025 100644 --- a/frontend/src/features/library/importer.ts +++ b/frontend/src/features/library/importer.ts @@ -5,8 +5,24 @@ import { labelAttr, t } from '../../i18n'; import type { LibResult, LibraryHooks } from './types'; import { bringChoice, type Bring } from './bring'; +/** Words joined as a list: "a", "a and b", "a, b and c". */ +export function joined(items: string[]): string { + if (items.length < 2) return items[0] || ''; + return t('{0} and {1}', [items.slice(0, -1).reduce((list, item) => t('{0}, {1}', [list, item])), items[items.length - 1]]); +} + +/** Host names for a sentence: at most three, then how many more. */ +export function hostList(hosts: string[]): string { + if (hosts.length <= 3) return joined(hosts); + const rest = hosts.length - 3; + return rest === 1 ? t('{0} and 1 more host', [hosts.slice(0, 3).join(', ')]) : t('{0} and {1} more hosts', [hosts.slice(0, 3).join(', '), rest]); +} + +/** The result sentence for pages brought in as elements without the files they load from the web. */ +export const missingHosts = (hosts: string[]): string => hosts.length ? t('Files from {0} were not brought along, so part of the look may be missing.', [hostList(hosts)]) : ''; + /** One page into the open page as a code section, converted to elements when asked; answers with the sentence to show. */ -export async function importSection(hooks: LibraryHooks, body: { html: string; css?: string; name?: string }, bring: Bring, progress: (message: string) => void, made?: (ids: string[]) => void): Promise { +export async function importSection(hooks: LibraryHooks, body: { html: string; css?: string; name?: string }, bring: Bring, progress: (message: string) => void, made?: (ids: string[]) => void, hosts: string[] = []): Promise { const where = hooks.placement(); const result = await libraryMutate('/api/library/import-html', { ...body, parent: where.parent, index: where.index, page: where.page }); let message = result.warnings?.[0] || t('HTML section imported.'); @@ -14,7 +30,7 @@ export async function importSection(hooks: LibraryHooks, body: { html: string; c let root = result.root; if (result.root && bring === 'elements') { progress(t('Converting...')); - try { const done = await hooks.convert([result.root]); root = done.root || root; message = note = done.message + ' ' + t('Undo once to get the section back as code, twice to remove it.'); } + try { const done = await hooks.convert([result.root]); root = done.root || root; message = note = [done.message, missingHosts(hosts), t('Undo once to get the section back as code, twice to remove it.')].filter(Boolean).join(' '); } catch (error) { message = note = t('HTML section imported.') + ' ' + t('The pages stayed code sections: {0}', [error instanceof Error ? error.message : String(error)]); } } if (root) hooks.select(root); diff --git a/frontend/src/features/library/site-import.ts b/frontend/src/features/library/site-import.ts index 2535cbde..e886c1f2 100644 --- a/frontend/src/features/library/site-import.ts +++ b/frontend/src/features/library/site-import.ts @@ -1,10 +1,10 @@ import { libraryMutate, request } from '../../api'; import { element, keyed, text } from '../../ui/dom'; import { icon } from '../../ui/icons'; -import { label, t } from '../../i18n'; +import { label, onLanguage, t } from '../../i18n'; import type { LibraryHooks, SitePage, SiteResult, SiteReview, SiteSkip } from './types'; -import { bringChoice } from './bring'; -import { importSection } from './importer'; +import { bringChoice, type BringWhy } from './bring'; +import { hostList, importSection, joined, missingHosts } from './importer'; import { state, subscribe } from '../../api'; type Mode = 'new' | 'replace'; @@ -15,6 +15,27 @@ const size = (bytes: number): string => bytes >= 1048576 ? `${(bytes / 1048576). const HTML_ACCEPT = '.html,.htm,text/html'; const isHtml = (file: File): boolean => /\.html?$/i.test(file.name); const isZip = (file: File): boolean => /\.zip$/i.test(file.name); +const loadsOutside = (page: SitePage): boolean => !!page.outside?.length; +/** The hosts the given pages load files from, each once, in the order they first appear. */ +const hostsOf = (pages: SitePage[]): string[] => [...new Set(pages.flatMap(page => (page.outside || []).map(item => item.host)))]; +/** "1 stylesheet from a and 2 scripts from b": the page's outside files grouped by host and kind, four groups at most. */ +function outsideSentence(page: SitePage): string { + const groups = new Map(); + for (const item of page.outside || []) { + const key = `${item.kind} ${item.host}`; + const group = groups.get(key); + if (group) group.count += 1; + else groups.set(key, { kind: item.kind, host: item.host, count: 1 }); + } + if (!groups.size) return ''; + const all = [...groups.values()]; + const pieces = all.slice(0, 4).map(({ kind, host, count }) => kind === 'stylesheet' + ? count === 1 ? t('1 stylesheet from {0}', [host]) : t('{0} stylesheets from {1}', [count, host]) + : count === 1 ? t('1 script from {0}', [host]) : t('{0} scripts from {1}', [count, host])); + const rest = all.slice(4).reduce((sum, group) => sum + group.count, 0) + (page.outsideMore || 0); + if (rest) pieces.push(rest === 1 ? t('1 more file') : t('{0} more files', [rest])); + return t('This page takes part of its look from the web: {0}. These files are not brought along.', [joined(pieces)]); +} /** Decodes a picked page exactly as the service decodes one inside a zip: UTF-8 (a byte order mark dropped), else Windows-1252 with its five unassigned bytes as U+FFFD. */ function decode(bytes: ArrayBuffer): string { try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } @@ -79,6 +100,7 @@ export class SiteImport { text(this.helpZip, t('Brings a static site made elsewhere into this site: every HTML file in the zip becomes a page, with its stylesheets, pictures and WOFF2 fonts. After the review you choose whether the pages arrive as editable elements or as code sections. Links between the pages follow their new addresses, and outside links stay as they are.')); this.help.append(this.helpHtml, this.helpZip); subscribe(next => { if (this.finished && this.made.length && !this.made.some(id => next.site.nodes[id] || next.site.pages.some(page => page.id === id))) this.reset(); }); + onLanguage(() => this.paint()); this.file.type = 'file'; this.file.multiple = true; this.file.hidden = true; @@ -197,6 +219,7 @@ export class SiteImport { this.mode = 'new'; this.use = 'pages'; this.done = false; + this.bring.choose('elements'); this.say('', false); this.show(); if (zips.length + pages.length !== files.length || (zips.length && files.length > 1)) { @@ -217,6 +240,7 @@ export class SiteImport { if (zips.length) this.current = zips[0]; else this.loose = await Promise.all(pages.map(async file => ({ name: file.name, html: decode(await file.arrayBuffer()) }))); this.plan = await request('/api/library/import-site/review', this.body()); + this.bring.choose(this.plan.pages.some(loadsOutside) ? 'code' : 'elements'); const empty = !this.plan.pages.length; if (empty) this.loose = null; this.say(empty ? (zips.length ? t('The archive has no HTML page that can be imported.') : t('None of the files is an HTML page that can be imported.')) : '', empty); @@ -269,6 +293,7 @@ export class SiteImport { if (this.reviewTail.hidden === showReview) this.reviewTail.hidden = !showReview; const showBring = showReview || section; this.bring.heading(section ? 'Bring it in as' : 'Bring pages in as'); + this.bring.explain(this.why(section)); if (this.bring.element.hidden === showBring) this.bring.element.hidden = !showBring; const count = plan?.pages.length ?? 0; if (section) { @@ -300,14 +325,39 @@ export class SiteImport { if (this.skippedHead.hidden === !!plan.skipped.length) this.skippedHead.hidden = !plan.skipped.length; } + /** Why the choice started on code sections, and what elements would miss; null when no page loads files from the web. */ + private why(section: boolean): BringWhy | null { + const pages = this.plan?.pages || []; + const loading = pages.filter(loadsOutside); + if (!loading.length) return null; + const hosts = hostList(hostsOf(loading)); + if (section || pages.length === 1) return { + code: t('Kept as code, so the page keeps its own scripts and rules, responsive ones included. The files it loads from the web are not brought along either way.'), + elements: t('As elements, the page arrives without the files it loads from {0}, so part of its look will be missing.', [hosts]) + }; + if (loading.length === 1) return { + code: t('Kept as code, because 1 of {0} pages loads files from the web. As code the pages keep their own scripts and rules, responsive ones included; those files are not brought along either way.', [pages.length]), + elements: t('As elements, 1 of {0} pages arrives without the files it loads from {1}, so part of its look will be missing.', [pages.length, hosts]) + }; + return { + code: t('Kept as code, because {0} of {1} pages load files from the web. As code the pages keep their own scripts and rules, responsive ones included; those files are not brought along either way.', [loading.length, pages.length]), + elements: t('As elements, {0} of {1} pages arrive without the files they load from {2}, so part of their look will be missing.', [loading.length, pages.length, hosts]) + }; + } + private row(): HTMLElement { const node = element('div', 'fw-lib-site-item'); - node.append(element('span', 'fw-lib-row-name'), element('span', 'fw-lib-site-route'), element('span', 'fw-lib-row-meta')); + const outside = element('span', 'fw-lib-row-meta fw-lib-site-outside'); + outside.dataset.noI18n = ''; + node.append(element('span', 'fw-lib-row-name'), element('span', 'fw-lib-site-route'), outside, element('span', 'fw-lib-row-meta')); return node; } private fillPage(node: HTMLElement, page: SitePage): void { - const [name, route, meta] = Array.from(node.children) as HTMLElement[]; + const [name, route, outside, meta] = Array.from(node.children) as HTMLElement[]; + const web = outsideSentence(page); + text(outside, web); + if (outside.hidden === !web) outside.hidden = !web; text(name, page.name); const replacing = this.mode === 'replace' && page.replaces; text(route, `${page.file} → ${replacing ? page.route : page.newRoute}`); @@ -317,9 +367,10 @@ export class SiteImport { } private fillSkip(node: HTMLElement, item: SiteSkip): void { - const [name, route, meta] = Array.from(node.children) as HTMLElement[]; + const [name, route, outside, meta] = Array.from(node.children) as HTMLElement[]; text(name, item.file); if (!route.hidden) route.hidden = true; + if (!outside.hidden) outside.hidden = true; text(meta, t(item.reason)); if (meta.hidden) meta.hidden = false; } @@ -330,7 +381,7 @@ export class SiteImport { this.working = t('Importing...'); this.setBusy(true); try { - const message = await importSection(this.hooks, { html: page.html, name: page.name.replace(/\.html?$/i, '') }, this.bring.value(), note => this.progress(note), ids => { this.made = ids; }); + const message = await importSection(this.hooks, { html: page.html, name: page.name.replace(/\.html?$/i, '') }, this.bring.value(), note => this.progress(note), ids => { this.made = ids; }, hostsOf(this.plan?.pages.slice(0, 1) || [])); this.done = true; this.say(message, false); } catch (error) { @@ -359,7 +410,7 @@ export class SiteImport { this.progress(t('Converting...')); const site = state().site; const hosts = result.pages.flatMap(id => site.nodes[site.pages.find(page => page.id === id)?.root || '']?.children || []); - try { message += ' ' + (await this.hooks.convert(hosts)).message + ' ' + t('Undo once to get the pages back as code, twice to remove them.'); } + try { message += ' ' + [(await this.hooks.convert(hosts)).message, missingHosts(hostsOf(plan.pages)), t('Undo once to get the pages back as code, twice to remove them.')].filter(Boolean).join(' '); } catch (error) { message += ' ' + t('The pages stayed code sections: {0}', [error instanceof Error ? error.message : String(error)]); } } this.say(message, false); diff --git a/frontend/src/features/library/types.ts b/frontend/src/features/library/types.ts index c612b354..b41d5eb5 100644 --- a/frontend/src/features/library/types.ts +++ b/frontend/src/features/library/types.ts @@ -22,7 +22,9 @@ export type LibIndex = { categories: string[]; sections: LibSection[]; component export type LibResult = { root?: string; pages?: string[]; warnings?: string[]; changed?: boolean }; /** POST /api/library/import-site/review: what importing a site zip would do, nothing changed yet. */ export type SiteSkip = { file: string; reason: string }; -export type SitePage = { file: string; name: string; title: string; description: string; route: string; newRoute: string; replaces: { id: string; name: string; safe: boolean } | null; bytes: number; warnings: string[] }; +/** A stylesheet or script a page loads from another host: named in the review, never fetched. */ +export type SiteOutside = { kind: 'stylesheet' | 'script'; host: string; url: string }; +export type SitePage = { file: string; name: string; title: string; description: string; route: string; newRoute: string; replaces: { id: string; name: string; safe: boolean } | null; bytes: number; warnings: string[]; outside?: SiteOutside[]; outsideMore?: number }; export type SiteReview = { pages: SitePage[]; assets: { count: number; bytes: number }; supportFiles: number; skipped: SiteSkip[]; ignored: number; canReplace: boolean; replaceNote: string; notes: string[]; revision: number }; /** POST /api/library/import-site: the batch state plus the pages made, assets stored and files skipped. */ export type SiteResult = { pages?: string[]; assets?: number; skipped?: SiteSkip[]; warnings?: string[]; message?: string }; diff --git a/frontend/src/styles/library.css b/frontend/src/styles/library.css index b62554a7..faa81abf 100644 --- a/frontend/src/styles/library.css +++ b/frontend/src/styles/library.css @@ -110,3 +110,8 @@ .fw-lib-bring-option.is-on { border-color: var(--accent-line); background: var(--accent-wash); } .fw-lib-bring-option:disabled { cursor: default; } .fw-lib-bring-option .fw-lib-row-meta { color: var(--text-secondary); } +.fw-lib-bring-why { display: grid; margin: 0 0 var(--space-2); } +.fw-lib-bring-why[hidden] { display: none; } +.fw-lib-bring-why > .fw-lib-row-meta { grid-area: 1 / 1; margin: 0; color: var(--text-secondary); overflow-wrap: anywhere; } +.fw-lib-bring-why > :not(.is-on) { visibility: hidden; } +.fw-lib-site-item > .fw-lib-site-outside { color: var(--text-secondary); } From b15966b0a2c076ae3c3e77e315af8d916298bdda Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:01:42 -0500 Subject: [PATCH 02/38] feat(convert): a page converted to elements with its script kept keeps the style rules the converted elements did not use, scoped so they reach only what the script builds, a page that filled the window fills the canvas and Preview, and the convert dialog keeps the focus while it works --- frontend/src/features/convert/index.ts | 43 ++++- frontend/src/features/convert/measure.ts | 229 ++++++++++++++++++++++- frontend/src/features/convert/rules.ts | 103 +++++++++- frontend/src/styles/convert.css | 1 + 4 files changed, 358 insertions(+), 18 deletions(-) diff --git a/frontend/src/features/convert/index.ts b/frontend/src/features/convert/index.ts index d5e4c070..1886f30f 100644 --- a/frontend/src/features/convert/index.ts +++ b/frontend/src/features/convert/index.ts @@ -89,7 +89,7 @@ function partCommands(site: EditorState['site'], host: SiteNode, record: Section } list.push(...adds(plan, parent => parent || owner.id)); if (root) list.push({ command: 'node.move', params: { id: root.id, parent: owner.id, index: at } }); - if (plan.rest.after || record.js) list.push({ command: 'code.section.set', params: { node: host.id, value: { ...record, enabled: record.enabled !== false, html: plan.rest.after, css: scoped(host.id) } } }); + if (plan.rest.after || record.js) list.push({ command: 'code.section.set', params: { node: host.id, value: { ...record, enabled: record.enabled !== false, html: plan.rest.after, css: scoped(host.id) + (record.js && plan.rest.kept ? `\n${plan.rest.kept}` : '') } } }); else list.push({ command: 'node.remove', params: { id: host.id } }); return list; } @@ -116,6 +116,18 @@ function drop(plans: [Plan, string][], message: string): number { return removed; } +/** Takes the style rules kept for scripts out of the plans when the engine refused the batch for a section's CSS or the site's size. */ +function dropKept(plans: [Plan, string][], message: string): number { + if (!message.includes('invalid css') && !message.includes('site exceeds')) return 0; + let removed = 0; + for (const [plan] of plans) { + for (const item of plan.nodes) if (item.code?.css) { delete item.code.css; removed++; } + if (plan.rest?.kept) { plan.rest.kept = ''; removed++; } + if (plan.outcome.kept) { plan.outcome.keptDropped += plan.outcome.kept; plan.outcome.kept = 0; plan.outcome.keptAll = 0; } + } + return removed; +} + async function apply(build: () => Command[], plans: [Plan, string][]): Promise<{ state: EditorState; left: number }> { let left = 0; for (let attempt = 0; ; attempt++) { @@ -123,6 +135,7 @@ async function apply(build: () => Command[], plans: [Plan, string][]): Promise<{ return { state: await send(build()), left }; } catch (error) { const message = error instanceof Error ? error.message : String(error); + if (attempt < RETRIES && dropKept(plans, message)) continue; const removed = attempt < RETRIES ? drop(plans, message) : 0; if (!removed) throw error; left += removed; @@ -172,6 +185,7 @@ export async function convertSections(ids: string[], keepScript: boolean, part?: const outcome = plans.map(plan => plan.outcome).reduce((all, one) => ({ converted: all.converted + one.converted, responsive: all.responsive + one.responsive, effects: all.effects + one.effects, floats: all.floats + one.floats, pictures: all.pictures + one.pictures, refused: all.refused + one.refused, scripted: all.scripted + one.scripted, left: all.left + one.left, + kept: all.kept + one.kept, keptAll: all.keptAll + one.keptAll, keptOver: all.keptOver + one.keptOver, keptDropped: all.keptDropped + one.keptDropped, parts: Object.fromEntries([...new Set([...Object.keys(all.parts), ...Object.keys(one.parts)])].map(key => [key, (all.parts[key as keyof typeof all.parts] || 0) + (one.parts[key as keyof typeof one.parts] || 0)])) })); outcome.left += left; @@ -189,6 +203,8 @@ export function installConvert(host: ConvertHost): { commands: CommandDef[]; ent box.hidden = true; box.setAttribute('role', 'dialog'); box.setAttribute('aria-modal', 'false'); + box.tabIndex = -1; + box.dataset.ownKeys = ''; const title = element('h2', 'fw-convert-title'); label(title, 'Convert to editable elements'); box.setAttribute('aria-label', t('Convert to editable elements')); @@ -225,9 +241,13 @@ export function installConvert(host: ConvertHost): { commands: CommandDef[]; ent let target = ''; let busy = false; - const close = (): void => { if (!box.hidden) box.hidden = true; }; + const close = (): void => { + if (box.hidden) return; + if (box.contains(document.activeElement)) document.querySelector('.inspector-tabs .active, .inspector-tabs button')?.focus({ preventScroll: true }); + box.hidden = true; + }; const say = (message: string, error = false): void => { text(note, message); note.classList.toggle('is-error', error); }; - const setBusy = (on: boolean): void => { busy = on; go.disabled = on || !parts.hidden; box.setAttribute('aria-busy', String(on)); for (const button of Array.from(parts.querySelectorAll('button'))) (button as HTMLButtonElement).disabled = on || (button as HTMLButtonElement).dataset.big === '1'; }; + const setBusy = (on: boolean): void => { if (on && box.contains(document.activeElement)) box.focus({ preventScroll: true }); busy = on; go.disabled = on || !parts.hidden; box.setAttribute('aria-busy', String(on)); for (const button of Array.from(parts.querySelectorAll('button'))) (button as HTMLButtonElement).disabled = on || (button as HTMLButtonElement).dataset.big === '1'; }; function paintParts(list: Block[]): void { if (partsHead.hidden !== !list.length) { partsHead.hidden = !list.length; parts.hidden = !list.length; } @@ -267,9 +287,10 @@ export function installConvert(host: ConvertHost): { commands: CommandDef[]; ent if (busy || !target) return undefined; setBusy(true); say(t('Converting...')); + const chosen = host.selected(); try { const done = await convertSections([target], scriptBox.checked || scriptRow.hidden === true, part); - finish(done); + finish(done, chosen); if (part !== undefined) { const record = sectionOf(state().site, target); if (record?.html?.trim()) { const next = blocks(sourceOf(record)); paintParts(next.blocks); say(done.message); return done; } @@ -291,9 +312,10 @@ export function installConvert(host: ConvertHost): { commands: CommandDef[]; ent } } - function finish(done: Converted): void { - const after = state().revision; - if (done.root && state().site.nodes[done.root]) host.select(done.root); + /** Selects what the conversion made, unless the person chose another element while it ran. */ + function finish(done: Converted, chosen: string): void { + const after = state().revision, now = host.selected(); + if (done.root && state().site.nodes[done.root] && (now === chosen || !state().site.nodes[now])) host.select(done.root); host.notify(done.message, () => { if (state().revision !== after) { host.status(t('The site changed after the conversion. Use Edit > Undo to step back.'), true); return; } return host.undo(); @@ -313,17 +335,18 @@ export function installConvert(host: ConvertHost): { commands: CommandDef[]; ent params: { node: { type: 'string', description: 'The code section element to convert. Default: the selected element.' }, nodes: { type: 'array', description: 'Several code section elements to convert in one undo step.' }, - keepScript: { type: 'boolean', description: 'Keep the page\'s script as a small code section (default true).' }, + keepScript: { type: 'boolean', description: 'Keep the page\'s script as a small code section, with the style rules the converted elements do not use, for what the script builds (default true).' }, part: { type: 'integer', min: 0, description: 'Convert only this top-level block of the section (0 is the first), for a page too large for one conversion.' } }, enabled: () => host.ready() && anySection(), - description: 'Turn a code section (an imported page or any section of plain HTML and CSS) into ordinary FormWeb elements with their own text, links, pictures and base styles measured at desktop width, in one undo step. Scripts, inline frames and vector graphics stay as small code sections in place; responsive rules are not carried over. Without parameters it opens a short dialog for the selected element; with node or nodes it converts at once and returns the result sentence.', + description: 'Turn a code section (an imported page or any section of plain HTML and CSS) into ordinary FormWeb elements with their own text, links, pictures and base styles measured at desktop width, in one undo step. Scripts, inline frames and vector graphics stay as small code sections in place; responsive rules are not carried over. A kept script keeps the style rules no converted element uses, so what it builds is styled in Preview and the export. Without parameters it opens a short dialog for the selected element; with node or nodes it converts at once and returns the result sentence.', when: 'Use when the person wants to edit an imported page or a code section visually: click a heading, change its text, restyle it or move it.', run: async (params?: Record) => { const list = Array.isArray(params?.nodes) ? (params!.nodes as unknown[]).filter((id): id is string => typeof id === 'string') : typeof params?.node === 'string' ? [params.node] : null; if (!list) { if (convertible(host.selected())) open(host.selected()); else host.status(t('Select a code section that holds HTML to convert.'), true); return undefined; } + const chosen = host.selected(); const done = await convertSections(list, params?.keepScript !== false, typeof params?.part === 'number' ? params.part : undefined); - finish(done); + finish(done, chosen); return { message: done.message, converted: done.converted, root: done.root }; } }]; diff --git a/frontend/src/features/convert/measure.ts b/frontend/src/features/convert/measure.ts index 014f8ccc..73a11220 100644 --- a/frontend/src/features/convert/measure.ts +++ b/frontend/src/features/convert/measure.ts @@ -1,9 +1,9 @@ -import { arrange, backdropLayers, carryAttrs, compact, emptyOutcome, families, layerName, LINK_FORCED, mapTag, pickFonts, READ, reduceStyles, ROOT_FORCED, scopeSelector, VOID_TAGS, type FontFaceRule, type Outcome, type Part, type Run, type SiteFont } from './rules'; +import { arrange, backdropLayers, bodyQualified, carryAttrs, compact, emptyOutcome, families, guardSelector, KEEP_BYTES, KEEP_RULES, layerName, LINK_FORCED, mapTag, pickFonts, READ, reduceStyles, ROOT_FORCED, scopeSelector, scriptWords, selectorList, subjectClasses, VOID_TAGS, type FontFaceRule, type Outcome, type Part, type Run, type SiteFont } from './rules'; import { t } from '../../i18n'; export interface Source { html: string; css: string; js: string; module: boolean } -export interface Planned { id: string; parent: string; tag: string; name: string; text: string; attrs: Record; styles: Record; code?: { enabled: true; html: string; js?: string; module?: boolean } } -export interface Plan { rootStyles: Record; nodes: Planned[]; fonts: Record | null; outcome: Outcome; rest?: { before: string; after: string; css: string } } +export interface Planned { id: string; parent: string; tag: string; name: string; text: string; attrs: Record; styles: Record; code?: { enabled: true; html: string; css?: string; js?: string; module?: boolean } } +export interface Plan { rootStyles: Record; nodes: Planned[]; fonts: Record | null; outcome: Outcome; rest?: { before: string; after: string; css: string; kept?: string } } export interface Options { origin: string; keepScript: boolean; fonts: Record; taken: (id: string) => boolean; limit: number; depth: number; seconds: number; scope?: string } const SKIPPED = new Set(['STYLE', 'LINK', 'META', 'BASE', 'TITLE']); @@ -82,7 +82,7 @@ function frameDocument(origin: string, css: string, body: string, bodyAttrs: str } /** A hidden, sandboxed frame with no scripts and no network beyond the site's own pictures; removed when done. */ -async function openFrame(srcdoc: string, origin: string): Promise<{ doc: Document; close: () => void }> { +async function openFrame(srcdoc: string, origin: string): Promise<{ doc: Document; frame: HTMLIFrameElement; close: () => void }> { const frame = document.createElement('iframe'); frame.setAttribute('sandbox', 'allow-same-origin'); frame.setAttribute('csp', policy(origin)); @@ -96,7 +96,7 @@ async function openFrame(srcdoc: string, origin: string): Promise<{ doc: Documen await loaded; const doc = frame.contentDocument; if (!doc) { frame.remove(); throw new Error(t('The page could not be measured in this browser.')); } - return { doc, close: () => frame.remove() }; + return { doc, frame, close: () => frame.remove() }; } function read(view: Window, el: Element, names: readonly string[]): Record { @@ -156,6 +156,196 @@ export function scopedCss(css: string, prefix: string): string { return out.join('\n'); } +/** The measuring frame's height (`.fw-convert-frame` in convert.css), and the height it is read at a second time. */ +const FRAME_H = 900, TALL = 1300; +const HEIGHTS = ['height', 'min-height', 'max-height']; +const round = (n: number): number => Math.round(n * 100) / 100; + +/** A measured length that followed the frame's height, written in vh again (with a fixed part in calc() if it had one). */ +function inVh(short: string, tall: string): string | null { + const a = parseFloat(short), b = parseFloat(tall); + if (!short.endsWith('px') || !tall.endsWith('px') || !Number.isFinite(a) || !Number.isFinite(b) || Math.abs(b - a) < 0.5) return null; + const per = (b - a) * 100 / (TALL - FRAME_H), rest = a - per * FRAME_H / 100; + if (Math.abs(rest) < 0.5) return `${round(per)}vh`; + return `calc(${round(per)}vh ${rest < 0 ? '-' : '+'} ${round(Math.abs(rest))}px)`; +} + +/** + * Heights the page took from the window. The frame is measured with `html` hidden, so `100vh` reads as the frame's + * 900 px and `height: 100%` stays a percentage that the element's new parent cannot resolve: the page collapsed to + * its content, or kept 900 px on a taller canvas. Every written height that changes when the frame is made taller is + * written in vh again, and a root whose height was a percentage of the window becomes a min-height in vh, with its + * children's percentages of it, so the converted page fills the canvas and the preview as the original filled the + * window. + */ +function fillWindow(view: Window, frame: HTMLIFrameElement, root: Record | null, sized: [{ parent: string; styles: Record }, Element][]): void { + const doc = view.document; + const entries: [Record, Element][] = [...(root ? [[root, doc.body] as [Record, Element]] : []), ...sized.map(([node, el]) => [node.styles, el] as [Record, Element])] + .filter(([styles]) => HEIGHTS.some(name => /px$|%$/.test(styles[name] || ''))); + if (!entries.length) return; + const page = read(view, doc.documentElement, ['height']).height; + const short = entries.map(([, el]) => read(view, el, HEIGHTS)); + frame.style.height = `${TALL}px`; + void frame.offsetHeight; + const tall = entries.map(([, el]) => read(view, el, HEIGHTS)); + const pageTall = read(view, doc.documentElement, ['height']).height; + frame.style.height = ''; + entries.forEach(([styles], index) => { + for (const name of HEIGHTS) { + if (styles[name] !== short[index][name]) continue; + const value = inVh(short[index][name], tall[index][name]); + if (value) styles[name] = value; + } + }); + if (!root) return; + const vhOf = (value: string | null | undefined): number => value && value.endsWith('vh') && !value.startsWith('calc') ? parseFloat(value) : NaN; + const pageVh = page.endsWith('%') ? parseFloat(page) : vhOf(inVh(page, pageTall)); + if (!Number.isFinite(pageVh)) return; + const share = (value: string | undefined, of: number): number => value?.endsWith('%') ? round(parseFloat(value) * of / 100) : NaN; + const own = share(root.height, pageVh), least = share(root['min-height'], pageVh); + const fill = Math.max(Number.isFinite(own) ? own : 0, Number.isFinite(least) ? least : 0); + if (!fill) return; + if (root.height?.endsWith('%')) delete root.height; + if (!(vhOf(root['min-height']) >= fill)) root['min-height'] = `${fill}vh`; + if (!Number.isFinite(own)) return; + for (const [node] of sized) { + if (node.parent !== '') continue; + const child = Math.max(share(node.styles.height, own) || 0, share(node.styles['min-height'], own) || 0); + if (!child) continue; + if (node.styles.height?.endsWith('%')) delete node.styles.height; + node.styles['min-height'] = `${child}vh`; + } +} + +export interface Kept { css: string; rules: number; all: boolean; over: number } + +/** How long checking which rules the converted elements use may take before every rule is kept unchecked. */ +const MATCH_MS = 2000; +/** Added to a kept selector's subject so it cannot match a converted element (every element carries this attribute). */ +const GUARD = ':where(:not([data-fw-node]))'; +const GROUPS = new Set(['CSSMediaRule', 'CSSSupportsRule', 'CSSContainerRule', 'CSSLayerBlockRule']); +const kindOf = (rule: CSSRule): string => rule.constructor.name; + +function groupHead(rule: CSSRule): string { + const kind = kindOf(rule); + if (kind === 'CSSMediaRule') return `@media ${(rule as CSSMediaRule).media.mediaText}`; + if (kind === 'CSSSupportsRule') return `@supports ${(rule as CSSSupportsRule).conditionText}`; + if (kind === 'CSSLayerBlockRule') return `@layer ${(rule as CSSLayerBlockRule).name}`.trim(); + const text = rule.cssText, at = text.indexOf('{'); + return at > 0 ? text.slice(0, at).trim() : ''; +} + +/** + * The page's style rules kept for what its script builds. A selector is kept when it matched no converted element in + * the measuring frame (the page as written, scripts not run), or when it did but its subject requires classes the + * script names (the script may build more of them); the other selectors of a list are left out. Custom properties + * of every rule stay, so kept rules still find their var() values. Each kept selector looks only inside `prefix` + * (the converted root) and is guarded so it cannot restyle a converted element. `@keyframes` and `@font-face` stay + * when a kept rule names them, `@media`, `@supports`, `@container` and `@layer` blocks keep only their kept rules, + * `@import` never stays (the browser's parse of a constructed sheet drops it). Parsing and serialising are the + * browser's, in the measuring frame's realm; nothing is applied or fetched there. + */ +async function keepRules(view: Window, doc: Document, css: string, converted: Set, words: Set, prefix: string): Promise { + const Sheet = (view as unknown as { CSSStyleSheet: typeof CSSStyleSheet }).CSSStyleSheet; + const sheet = new Sheet(), scratch = new Sheet(); + const none: Kept = { css: '', rules: 0, all: false, over: 0 }; + let slice = performance.now(); + const breathe = async (): Promise => { if (performance.now() - slice > 40) { await new Promise(resolve => setTimeout(resolve, 0)); slice = performance.now(); } }; + try { sheet.replaceSync(css); } catch { return none; } + const styleRules: CSSStyleRule[] = []; + const collect = (list: CSSRuleList): void => { + for (let i = 0; i < list.length; i++) { + const rule = list[i]; + if (isStyle(rule)) styleRules.push(rule); + else if (GROUPS.has(kindOf(rule))) collect((rule as CSSGroupingRule).cssRules); + } + }; + collect(sheet.cssRules); + if (!styleRules.length) return none; + const used = (selector: string): boolean => { + let found: NodeListOf; + try { found = doc.querySelectorAll(selector); } catch { return false; } + for (let i = 0; i < found.length; i++) if (converted.has(found[i])) return true; + return false; + }; + const lists = new Map(); + const keeps = new Map(); + const deadline = performance.now() + MATCH_MS; + let all = false; + for (const rule of styleRules) { + const list = selectorList(rule.selectorText); + lists.set(rule, list); + if (all) continue; + await breathe(); + if (performance.now() > deadline) { all = true; continue; } + keeps.set(rule, list.map(selector => !used(selector) || (() => { const classes = subjectClasses(selector); return !!classes.length && classes.every(name => words.has(name)); })())); + } + if (all) keeps.clear(); + + const encoder = new TextEncoder(); + let bytes = 0, rules = 0, over = 0; + const valid = (text: string): boolean => { try { scratch.insertRule(text, 0); scratch.deleteRule(0); return true; } catch { return false; } }; + let full = false; + const room = (text: string): boolean => { + const size = encoder.encode(text).length + 1; + if (rules >= KEEP_RULES || bytes + size > KEEP_BYTES) { full ||= rules >= KEEP_RULES || bytes > KEEP_BYTES - 256; return false; } + bytes += size; + return true; + }; + const customsOf = (style: CSSStyleDeclaration): string[] => { + const customs: string[] = []; + for (let i = 0; i < style.length; i++) { + const name = style.item(i); + if (name.startsWith('--')) customs.push(`${name}:${style.getPropertyValue(name)}${style.getPropertyPriority(name) ? ' !important' : ''}`); + } + return customs; + }; + const styleTexts = (rule: CSSStyleRule): string[] => { + const list = lists.get(rule)!, keep = keeps.get(rule) || list.map(() => true); + const style = rule.style, scope = (selector: string): string => scopeSelector(selector, prefix); + const customs = customsOf(style); + const texts: string[] = []; + if (customs.length) { const text = `${list.map(scope).join(', ')}{${customs.join(';')}}`; if (valid(text)) texts.push(text); } + let kept = list.filter((selector, index) => keep[index] && !bodyQualified(selector)).map(scope).filter(selector => selector !== prefix).map(selector => guardSelector(selector, GUARD)); + const nested = (rule as CSSStyleRule & { cssRules?: CSSRuleList }).cssRules; + const body = `{${style.cssText}${nested ? Array.from(nested).map(inner => inner.cssText).join('') : ''}}`; + if (kept.length && !valid(kept.join(', ') + body)) kept = kept.filter(selector => valid(selector + body)); + if (kept.length && style.length) texts.push(kept.join(', ') + body); + return texts; + }; + const emit = async (list: CSSRuleList): Promise => { + const out: string[] = []; + for (let i = 0; i < list.length; i++) { + const rule = list[i]; + if (isStyle(rule)) { + if (full) { if ((keeps.get(rule) || [true]).some(Boolean) || customsOf(rule.style).length) over++; continue; } + await breathe(); + const texts = styleTexts(rule); + if (!texts.length) continue; + if (room(texts.join(''))) { out.push(...texts); rules++; } else over++; + } else if (GROUPS.has(kindOf(rule))) { + const inner = await emit((rule as CSSGroupingRule).cssRules), head = groupHead(rule); + if (inner.length && head) { out.push(`${head}{${inner.join('\n')}}`); bytes += head.length + 2; } + } + } + return out; + }; + const body = await emit(sheet.cssRules); + if (!body.length) return { ...none, over, all }; + const names = new Set(); + scriptWords(body.join('\n').toLowerCase(), names, 200000); + const head: string[] = []; + for (let i = 0; i < sheet.cssRules.length; i++) { + const rule = sheet.cssRules[i], kind = kindOf(rule); + const wanted = kind === 'CSSLayerStatementRule' || kind === 'CSSPropertyRule' + || (kind === 'CSSKeyframesRule' && names.has((rule as CSSKeyframesRule).name.toLowerCase())) + || (kind === 'CSSFontFaceRule' && families((rule as CSSFontFaceRule).style.getPropertyValue('font-family')).some(family => family.split(' ').every(word => names.has(word)))); + if (!wanted) continue; + if (room(rule.cssText)) head.push(rule.cssText); else over++; + } + return { css: [...head, ...body].join('\n'), rules, all, over }; +} + /** The blocks a page too large for one conversion can be converted by, one at a time: its top-level elements. */ export function blocks(source: Source): { blocks: Block[]; total: number } { const { doc } = sanitize(source); @@ -207,6 +397,8 @@ export async function measure(source: Source, options: Options, only?: number): doc.querySelectorAll('[data-fwk-i]').forEach(el => sources.set(el.getAttribute('data-fwk-i')!, el)); const nodes: Planned[] = []; const used = new Set(); + const converted = new Set(), words = new Set(); + let script: Planned | undefined; let serial = 0; const stem = `cv${Math.random().toString(36).slice(2, 7)}`; const fresh = (): string => { let id = `${stem}-${++serial}`; while (options.taken(id)) id = `${stem}-${++serial}`; return id; }; @@ -255,9 +447,12 @@ export async function measure(source: Source, options: Options, only?: number): rootMeasured['background-color'] = page['background-color']; } const rootStyles = settle(rootMeasured, bare.doc.body, ROOT_FORCED); + const sized: [{ parent: string; styles: Record }, Element][] = []; const keptHtml = (from: Element, frameEl: Element, bareParent: Element): string => { const copy = from.cloneNode(true) as Element; + converted.add(frameEl); + frameEl.querySelectorAll('*').forEach(el => converted.add(el)); const pairs: [Element, Element, Element][] = []; const twin = bare.doc.importNode(frameEl, true) as Element; twin.removeAttribute('style'); @@ -289,6 +484,7 @@ export async function measure(source: Source, options: Options, only?: number): const html = part === 'script' ? (() => { const copy = from.cloneNode(true) as Element; copy.removeAttribute('data-fwk-i'); return copy.outerHTML; })() : keptHtml(from, frameEl, bareParent); outcome.parts[part] = (outcome.parts[part] || 0) + 1; nodes.push({ id: fresh(), parent, tag: PHRASING.has(parentTag) ? 'span' : 'div', name: part === 'script' ? 'Script' : `Code ${from.tagName.toLowerCase()}`, text: '', attrs: {}, styles: { display: 'contents' }, code: { enabled: true, html } }); + if (part === 'script') { script ??= nodes[nodes.length - 1]; scriptWords(from.textContent || '', words); } }; const gather = (frameParent: Element, runs: Run[]): void => { @@ -331,7 +527,9 @@ export async function measure(source: Source, options: Options, only?: number): const measured = read(view, el, READ); const styles = settle(measured, twin, rule.tag === 'a' ? LINK_FORCED : []); const id = fresh(); + converted.add(el); nodes.push({ id, parent, tag: rule.tag, name: layerName(rule.tag, { id: from.id, className: from.getAttribute('class') || '' }), text: '', attrs: carried.attrs, styles }); + sized.push([nodes[nodes.length - 1], el]); if (!VOID_TAGS.has(rule.tag)) backdrop(measured, id, styles); children(el, twin, id, rule.tag, depth + 1); } @@ -340,7 +538,7 @@ export async function measure(source: Source, options: Options, only?: number): const ROOT = ''; const top = only === undefined ? original.doc.body : original.doc.body.children[only]; if (!top) throw new Error(t('That part of the page is no longer there.')); - if (only === undefined) { backdrop(rootMeasured, ROOT, rootStyles); children(original.doc.body, bare.doc.body, ROOT, 'body', 1); } + if (only === undefined) { converted.add(top); backdrop(rootMeasured, ROOT, rootStyles); children(original.doc.body, bare.doc.body, ROOT, 'body', 1); } else { const from = sources.get(top.getAttribute('data-fwk-i') || '') || top; const rule = mapTag(from.tagName); @@ -351,19 +549,36 @@ export async function measure(source: Source, options: Options, only?: number): const measured = read(view, top, READ); const styles = settle(measured, twin, rule.tag === 'a' ? LINK_FORCED : []); const id = fresh(); + converted.add(top); nodes.push({ id, parent: ROOT, tag: rule.tag, name: layerName(rule.tag, { id: from.id, className: from.getAttribute('class') || '' }), text: '', attrs: carried.attrs, styles }); + sized.push([nodes[nodes.length - 1], top]); if (!VOID_TAGS.has(rule.tag)) backdrop(measured, id, styles); children(top, twin, id, rule.tag, 2); } if (only === undefined && options.keepScript && source.js.trim()) { outcome.parts.script = (outcome.parts.script || 0) + 1; nodes.push({ id: fresh(), parent: ROOT, tag: 'div', name: 'Page script', text: '', attrs: {}, styles: { display: 'contents' }, code: { enabled: true, html: '', js: source.js, ...(source.module ? { module: true } : {}) } }); + script = nodes[nodes.length - 1]; + scriptWords(source.js, words); + } + fillWindow(view, original.frame, only === undefined ? rootStyles : null, sized); + const scope = only === undefined ? options.scope : nodes.find(node => node.parent === ROOT)?.id; + const hostScript = only !== undefined && options.keepScript && !!source.js.trim(); + if (hostScript) scriptWords(source.js, words); + let keptCss = ''; + if ((script?.code || hostScript) && scope) { + const kept = await keepRules(view, original.doc, css, converted, words, `[data-fw-node="${scope}"]`); + if (kept.css && script?.code) script.code.css = kept.css; + else keptCss = kept.css; + outcome.kept = kept.rules; + outcome.keptAll = kept.all ? kept.rules : 0; + outcome.keptOver = kept.over; } outcome.converted = nodes.filter(node => !node.code).length; if (rootStyles['font-family']) families(rootStyles['font-family']).forEach(name => used.add(name)); const fonts = pickFonts(rules.faces, used, options.fonts); const changed = JSON.stringify(fonts) !== JSON.stringify(options.fonts); - const rest = only === undefined ? undefined : { ...split(source.html, only), css: scopedCss(css, `[data-fw-node="${SCOPE}"]`) }; + const rest = only === undefined ? undefined : { ...split(source.html, only), css: scopedCss(css, `[data-fw-node="${SCOPE}"]`), kept: keptCss }; return { rootStyles, nodes, fonts: changed ? fonts : null, outcome, rest }; } finally { original.close(); diff --git a/frontend/src/features/convert/rules.ts b/frontend/src/features/convert/rules.ts index 3b9849ce..163869cc 100644 --- a/frontend/src/features/convert/rules.ts +++ b/frontend/src/features/convert/rules.ts @@ -281,10 +281,16 @@ export interface Outcome { refused: number; scripted: number; left: number; + /** Style rules kept for the page's script, those of them kept without checking (time bound), those past the + * bounds, and those dropped because the engine did not take them. */ + kept: number; + keptAll: number; + keptOver: number; + keptDropped: number; } export function emptyOutcome(): Outcome { - return { converted: 0, parts: {}, responsive: 0, effects: 0, floats: 0, pictures: 0, refused: 0, scripted: 0, left: 0 }; + return { converted: 0, parts: {}, responsive: 0, effects: 0, floats: 0, pictures: 0, refused: 0, scripted: 0, left: 0, kept: 0, keptAll: 0, keptOver: 0, keptDropped: 0 }; } type Say = (english: string, values?: readonly (string | number)[]) => string; @@ -311,6 +317,11 @@ export function summary(outcome: Outcome, say: Say, count: SayCount): string { if (outcome.floats) lines.push(count(outcome.floats, '1 float was left out: FormWeb has no float property.', '{0} floats were left out: FormWeb has no float property.', [outcome.floats])); if (outcome.scripted) lines.push(count(outcome.scripted, '1 event handler or script link was left out.', '{0} event handlers and script links were left out.', [outcome.scripted])); if (outcome.refused + outcome.left) lines.push(count(outcome.refused + outcome.left, '1 value the engine does not take was left out.', '{0} values the engine does not take were left out.', [outcome.refused + outcome.left])); + const checked = outcome.kept - outcome.keptAll; + if (checked > 0) lines.push(count(checked, 'Kept 1 style rule for what the page\'s script builds.', 'Kept {0} style rules for what the page\'s script builds.', [checked])); + if (outcome.keptAll) lines.push(count(outcome.keptAll, 'Kept 1 style rule for what the page\'s script builds without checking whether the converted elements use it: checking took too long, so every rule was kept.', 'Kept {0} style rules for what the page\'s script builds without checking which ones the converted elements use: checking took too long, so every rule was kept.', [outcome.keptAll])); + if (outcome.keptOver) lines.push(count(outcome.keptOver, '1 more style rule was left out: at most {1} rules and {2} KB are kept for a script.', '{0} more style rules were left out: at most {1} rules and {2} KB are kept for a script.', [outcome.keptOver, KEEP_RULES, KEEP_BYTES / 1024])); + if (outcome.keptDropped) lines.push(count(outcome.keptDropped, 'The style rule kept for the page\'s script was left out: the engine did not take it.', 'The {0} style rules kept for the page\'s script were left out: the engine did not take them.', [outcome.keptDropped])); return lines.join(' '); } @@ -339,6 +350,96 @@ export function scopeSelector(list: string, prefix: string): string { }).filter(Boolean).join(', '); } +/** The most style rules and bytes kept for a page's script, under the engine's 256 KiB for a code section's CSS. */ +export const KEEP_RULES = 3000; +export const KEEP_BYTES = 192 * 1024; + +/** The selectors of one list, split at commas outside parentheses, brackets and strings, in one pass. */ +export function selectorList(list: string): string[] { + const parts: string[] = []; + let depth = 0, start = 0, quote = ''; + for (let i = 0; i < list.length; i++) { + const c = list[i]; + if (c === '\\') { i++; continue; } + if (quote) { if (c === quote) quote = ''; continue; } + if (c === '"' || c === '\'') quote = c; + else if (c === '(' || c === '[') depth++; + else if (c === ')' || c === ']') depth = Math.max(0, depth - 1); + else if (c === ',' && !depth) { parts.push(list.slice(start, i).trim()); start = i + 1; } + } + parts.push(list.slice(start).trim()); + return parts.filter(Boolean); +} + +const IDENT = (c: string): boolean => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c === '-' || c === '_' || c > '\u007f'; + +/** The subject of one selector (the compound after its last combinator): where it starts, where a pseudo-element + * begins (or the end), and the class names it requires. One pass, no backtracking. */ +function subjectOf(selector: string): { start: number; end: number; classes: string[] } { + let depth = 0, start = 0, end = -1, quote = ''; + for (let i = 0; i < selector.length; i++) { + const c = selector[i]; + if (c === '\\') { i++; continue; } + if (quote) { if (c === quote) quote = ''; continue; } + if (c === '"' || c === '\'') quote = c; + else if (c === '(' || c === '[') depth++; + else if (c === ')' || c === ']') depth = Math.max(0, depth - 1); + else if (depth) continue; + else if (c === ' ' || c === '>' || c === '+' || c === '~' || c === '\n' || c === '\t') { start = i + 1; end = -1; } + else if (c === ':' && selector[i + 1] === ':' && end < 0) { end = i; i++; } + } + if (end < 0) end = selector.length; + const classes: string[] = []; + depth = 0; quote = ''; + for (let i = start; i < end; i++) { + const c = selector[i]; + if (c === '\\') { i++; continue; } + if (quote) { if (c === quote) quote = ''; continue; } + if (c === '"' || c === '\'') quote = c; + else if (c === '(' || c === '[') depth++; + else if (c === ')' || c === ']') depth = Math.max(0, depth - 1); + else if (c === '.' && !depth) { + let name = ''; + for (i++; i < end && (IDENT(selector[i]) || selector[i] === '\\'); i++) name += selector[i] === '\\' ? selector[++i] || '' : selector[i]; + i--; + if (name) classes.push(name); + } + } + return { start, end, classes }; +} + +/** Whether a selector asks more of the page's body than being the body (`body.dark`, `body:has(...)`): the converted + * root that stands for the body carries none of that, and `scopeSelector` would drop the condition. */ +export function bodyQualified(selector: string): boolean { + const part = selector.trim().replace(/^(?:html|:root)(?:\s*>\s*|\s+)/i, ''); + return part.slice(0, 4).toLowerCase() === 'body' && '.#:['.includes(part[4] || ' '); +} + +/** The class names the subject of one selector requires. */ +export const subjectClasses = (selector: string): string[] => subjectOf(selector).classes; + +/** + * One kept selector made unable to match a converted element: `guard` goes on its subject, before any + * pseudo-element. A subject that requires a class is left as it is, since converted elements carry no class; it + * still matches an element the page's script gives that class. + */ +export function guardSelector(selector: string, guard: string): string { + const subject = subjectOf(selector); + if (subject.classes.length) return selector; + return selector.slice(0, subject.end) + guard + selector.slice(subject.end); +} + +/** The words a script is written with (names, strings split at anything but letters, digits, - and _), at most `limit`. */ +export function scriptWords(code: string, into: Set, limit = 50000): void { + let word = ''; + for (let i = 0; i <= code.length && into.size < limit; i++) { + const c = code[i]; + if (c !== undefined && IDENT(c)) { word += c; continue; } + if (word && word.length <= 120) into.add(word); + word = ''; + } +} + export type Layer = { kind: 'picture'; src: string; fit: string; position: string } | { kind: 'paint'; image: string }; function layersOf(value: string): string[] { diff --git a/frontend/src/styles/convert.css b/frontend/src/styles/convert.css index 2032b6cb..254d2f5c 100644 --- a/frontend/src/styles/convert.css +++ b/frontend/src/styles/convert.css @@ -2,6 +2,7 @@ .fw-convert { position: fixed; top: 50%; left: 50%; z-index: var(--z-popover); display: flex; flex-direction: column; gap: var(--space-3); width: min(440px, calc(100vw - 2 * var(--space-6))); max-height: min(560px, calc(100vh - 2 * var(--space-6))); padding: var(--space-4); overflow-y: auto; scrollbar-width: none; transform: translate(-50%, -50%); border: 1px solid var(--border-light); border-radius: var(--radius-xl); background: var(--bg-secondary); box-shadow: var(--shadow-window); color: var(--text-primary); font-size: var(--fs-12); line-height: 1.45; pointer-events: auto; } .fw-convert::-webkit-scrollbar { display: none; } .fw-convert[hidden], .fw-convert [hidden] { display: none; } +.fw-convert:focus { outline: none; } .fw-convert-title { margin: 0; font-size: var(--fs-14); font-weight: 600; } .fw-convert-text { margin: 0; color: var(--text-secondary); } .fw-convert .checkbox-field { margin-top: 0; } From 1c868a5028e7c4826252ff17e89256a2018f259c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:01:44 -0500 Subject: [PATCH 03/38] feat(audit): a module that draws one marker per element with an audit issue over the canvas, asks the audit again after the site changes, and a View command for it that does not end a trial --- frontend/src/commands/catalogue.ts | 1 + frontend/src/features/audit-markers.ts | 393 +++++++++++++++++++++++++ frontend/src/features/try/index.ts | 2 +- frontend/src/styles/audit-markers.css | 14 + 4 files changed, 409 insertions(+), 1 deletion(-) create mode 100644 frontend/src/features/audit-markers.ts create mode 100644 frontend/src/styles/audit-markers.css diff --git a/frontend/src/commands/catalogue.ts b/frontend/src/commands/catalogue.ts index 8d5cf0b5..6ef5719f 100644 --- a/frontend/src/commands/catalogue.ts +++ b/frontend/src/commands/catalogue.ts @@ -84,6 +84,7 @@ const META: Record = { 'view.try-choices': { description: 'Turn trying on or off for the Design inspector\'s choices (the segment buttons and the lists). With it on, a clicked choice shows on the canvas only and a small bar offers Keep and Revert; nothing is written until Keep, which is one undo step. With it off, a clicked choice is written at once. It only changes the editor, is remembered in this browser (Preferences > Interface > Design fields), and is never saved with the site.', when: 'Use when the person wants choices written at once, or wants to see a choice on the page before it is kept.' }, 'view.design-controls': { description: 'Show or hide the controls (sliders, color swatches, choosers) beside the Design inspector\'s CSS fields for every field that has no choice of its own; with them off the fields are plain CSS text. The typed value stays the stored value either way. It only changes the editor, is remembered in this browser (Preferences > Interface > Design fields), and is never saved with the site.', when: 'Use when the person prefers typing CSS values, or wants the sliders and pickers back.' }, 'view.layout-outlines': { description: 'Show or hide layout outlines on the design canvas: the container of the selected element and the containers around it are outlined, and a CSS grid container shows its tracks. It only changes the view, is remembered in this browser, is never saved with the site or exported, and is hidden in Preview.', when: 'Use when the person wants to see how the page is structured before moving elements.' }, + 'view.audit-markers': { description: 'Turn audit markers on or off (off by default): each element of the open page that has an issue in the SEO and accessibility audit gets one small marker on the canvas with its issue count, and a click on a marker selects the element and shows its issues. With markers on the audit is asked again after the site changes (at most once every 600 ms). Issues without an element get no marker. It only changes the view, is remembered in this browser (also in the Audit dialog), is never saved with the site or exported, and is hidden in Preview, during drags, trials, text editing and dialogs.', when: 'Use when the person wants to see on the page where the audit found issues, or no longer wants the markers.' }, 'view.hover-outline': { description: 'Turn hover outlines on or off (on by default): while the mouse rests on a row in Layers, its element gets a light outline on the canvas, and while it rests on an element on the canvas, that element is outlined and its layer row is tinted. Nothing scrolls or is selected. It only changes the view, is remembered in this browser, is never saved with the site, and shows nothing during drags, text editing, menus or Preview.', when: 'Use when the person wants, or no longer wants, a quick preview of where an element is without selecting it.' }, 'vector.rulers': { description: 'Show or hide the rulers along the vector editing area, in the SVG user units (Illustrator View > Rulers). Outside vector editing the key reloads the page.', when: 'Use to measure or to drag out guides while vector editing.' }, 'vector.guides.toggle': { description: 'Show or hide the guides of the edited SVG. The guides themselves are saved with the SVG (data-fw-guides) and are left out of exports; this toggle only changes the view.' }, diff --git a/frontend/src/features/audit-markers.ts b/frontend/src/features/audit-markers.ts new file mode 100644 index 00000000..f49ca504 --- /dev/null +++ b/frontend/src/features/audit-markers.ts @@ -0,0 +1,393 @@ +import { request } from '../api'; +import { labelAttr } from '../i18n'; +import { element, keyed, labelPieces, text, type Piece } from '../ui/dom'; +import { FrameMap, bounds, type Box } from './canvas-drag'; +import type { AuditIssue, EditorState } from '../types'; +import '../styles/audit-markers.css'; + +export interface AuditMarkersHost { + frame: HTMLIFrameElement; + stage: HTMLElement; + overlay: HTMLElement; + dialog: HTMLElement; + loaded: () => Promise; + page: () => string; + editing: () => boolean; + busy: () => boolean; + pick: (id: string, message: string, again: () => void) => void; + rescue: () => HTMLElement | null | undefined; + status: (message: string, error?: boolean) => void; +} + +export interface AuditMarkers { + row: HTMLElement; + enabled: () => boolean; + set: (on: boolean) => void; + sync: (next: EditorState) => void; + fresh: (answer: { issues: AuditIssue[] }) => void; +} + +interface Answer { site: string; revision: number; issues: AuditIssue[] } +interface Dot { id: string; name: string; rank: number; messages: string[] } + +const KEY = 'formweb.audit-markers'; +const GAP_MS = 600; +const SETTLE_MS = 150; +const CAP = 200; +const MAX_ISSUES = 5000; +const MAX_TEXT = 300; +const MAX_LINES = 20; +const MAX_NAME = 80; +const SIZE = 20; +const INSET = 2; +const RANK: Record = { error: 3, warning: 2, info: 1 }; +const SHAPE = ['info', 'info', 'warning', 'error']; + +function remembered(): boolean { + try { return localStorage.getItem(KEY) === '1'; } catch { return false; } +} + +function remember(on: boolean): void { + try { localStorage.setItem(KEY, on ? '1' : '0'); } catch { } +} + +const cut = (value: string, max: number): string => value.length > max ? value.slice(0, max - 1) + '…' : value; + +export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { + let on = remembered(); + let current: EditorState | null = null; + let answer: Answer | null = null; + let failed = false; + let said = false; + let out = false; + let due = false; + let timer = 0; + let last = -GAP_MS; + let frame = 0; + let doc: Document | null = null; + let shown: Dot[] = []; + let total = 0; + let open = ''; + const found = new Map(); + const placed = new Map(); + const map = new FrameMap(host.frame, host.stage); + + const layer = element('div', 'fw-audit-marks'); + layer.hidden = true; + const pop = element('div', 'fw-audit-pop'); + pop.hidden = true; + pop.setAttribute('role', 'group'); + const popList = element('ul', 'fw-audit-pop-list'); + pop.append(popList); + host.overlay.append(layer, pop); + + const box = element('input'); + box.type = 'checkbox'; + box.checked = on; + box.dataset.ownKeys = ''; + const boxLabel = element('label', 'checkbox-field'); + boxLabel.append(box, element('span', '', 'Show audit markers on the page')); + const about = element('p', 'micro', 'Puts a small marker on each element of this page that has an issue. Click a marker to select the element.'); + const note = element('p', 'micro fw-audit-note'); + const row = element('div', 'fw-audit-switch'); + row.append(boxLabel, about, note); + box.addEventListener('change', () => set(box.checked)); + + const valid = (): boolean => !!answer && !!current && answer.site === current.site.id && answer.revision === current.revision; + + function pageNodes(): Map { + const order = new Map(); + const site = current?.site; + const page = site?.pages.find(item => item.id === host.page()); + if (!site || !page) return order; + const stack = [page.root]; + while (stack.length) { + const id = stack.pop()!; + if (order.has(id) || !site.nodes[id]) continue; + order.set(id, order.size); + const kids = site.nodes[id].children; + for (let index = kids.length - 1; index >= 0; index--) stack.push(kids[index]); + } + return order; + } + + function collect(): void { + if (!answer || !current) { shown = []; total = 0; return; } + const order = pageNodes(); + const dots = new Map(); + for (const issue of answer.issues) { + const id = typeof issue.node === 'string' ? issue.node : ''; + if (!id || !order.has(id)) continue; + let dot = dots.get(id); + if (!dot) { dot = { id, name: cut(current.site.nodes[id].name || current.site.nodes[id].tag, MAX_NAME), rank: 0, messages: [] }; dots.set(id, dot); } + dot.rank = Math.max(dot.rank, RANK[issue.severity] ?? 1); + dot.messages.push(cut(String(issue.message ?? ''), MAX_TEXT)); + } + const all = [...dots.values()].sort((a, b) => order.get(a.id)! - order.get(b.id)!); + total = all.length; + shown = all.slice(0, CAP); + } + + function describe(): void { + if (!answer) { labelPieces(note, []); return; } + const loose = answer.issues.filter(issue => !issue.node).length; + const parts: Piece[] = []; + if (loose === 1) parts.push({ en: '1 issue has no element, so it has no marker.' }); + else if (loose) parts.push({ en: '{0} issues have no element, so they have no marker.', values: [loose] }); + if (total > CAP) { if (parts.length) parts.push(' '); parts.push({ en: 'Markers are drawn on the first {0} of {1} elements with issues on this page.', values: [CAP, total] }); } + labelPieces(note, parts); + } + + const focused = (): HTMLElement | null => { + const at = document.activeElement; + return at instanceof HTMLElement && layer.contains(at) ? at : null; + }; + + function rescue(): void { + if (!focused()) return; + const target = host.rescue(); + if (target?.isConnected) target.focus({ preventScroll: true }); + } + + function close(): void { + open = ''; + if (!pop.hidden) pop.hidden = true; + } + + function fill(): void { + const keep = focused(); + const next = new Set(shown.map(dot => dot.id)); + if (keep && !next.has(keep.dataset.key || '')) rescue(); + keyed(layer, shown, dot => dot.id, () => { + const node = element('button', 'fw-audit-dot'); + node.type = 'button'; + node.hidden = true; + node.dataset.ownKeys = ''; + node.append(element('span', 'fw-audit-count')); + node.addEventListener('click', () => activate(node.dataset.key || '')); + node.addEventListener('keydown', event => { if (event.key === 'Escape' && open) { event.preventDefault(); close(); } }); + return node; + }, (node, dot) => { + const shape = SHAPE[dot.rank] || 'info'; + if (node.dataset.severity !== shape) node.dataset.severity = shape; + text(node.firstElementChild as HTMLElement, String(dot.messages.length)); + if (dot.messages.length === 1) labelAttr(node, 'aria-label', '1 issue on {0}', [dot.name]); + else labelAttr(node, 'aria-label', '{0} issues on {1}', [dot.messages.length, dot.name]); + const tip = dot.messages.slice(0, MAX_LINES).join('\n'); + if (node.title !== tip) node.title = tip; + }); + for (const id of [...placed.keys()]) if (!next.has(id)) placed.delete(id); + if (keep?.isConnected && document.activeElement !== keep) keep.focus({ preventScroll: true }); + if (open) { + const dot = shown.find(item => item.id === open); + if (!dot || dot.messages.length < 2) close(); else list(dot); + } + } + + function list(dot: Dot): void { + labelAttr(pop, 'aria-label', 'Issues on {0}', [dot.name]); + keyed(popList, dot.messages.slice(0, MAX_LINES).map((message, index) => ({ message, key: String(index) })), item => item.key, () => element('li'), (node, item) => text(node, item.message)); + } + + function activate(id: string): void { + const dot = shown.find(item => item.id === id); + if (!dot || blocked()) return; + host.pick(id, dot.messages[0] || '', () => activate(id)); + const after = shown.find(item => item.id === id); + if (after && after.messages.length > 1) { + open = id; + list(after); + if (pop.hidden) pop.hidden = false; + } else close(); + place(); + } + + function blocked(): boolean { + if (!on || !answer || failed || !doc || answer.site !== current?.site.id) return true; + if (!host.editing() || host.busy() || !host.dialog.hidden) return true; + const html = doc.documentElement; + if (html.hasAttribute('data-fw-dragging') || html.hasAttribute('data-fw-holding') || document.body.classList.contains('fw-canvas-dragging')) return true; + return !!doc.querySelector('[contenteditable="true"]'); + } + + function resolve(id: string): HTMLElement | null { + const cached = found.get(id); + if (cached?.isConnected) return cached; + found.delete(id); + if (!doc) return null; + for (const node of doc.querySelectorAll(`[data-fw-id="${CSS.escape(id)}"]`)) { + if (node.dataset.fwKey?.endsWith(':list')) continue; + if (node.getClientRects().length || node.style.display === 'contents') { found.set(id, node); return node; } + const poster = node.querySelector(':scope>[data-fw-poster=script]'); + if (poster?.getClientRects().length) { found.set(id, poster); return poster; } + } + return null; + } + + function place(): void { + if (blocked()) { + rescue(); + close(); + if (!layer.hidden) layer.hidden = true; + return; + } + const still = map.still(); + const seen = map.visible(); + const active = focused(); + const nodes = [...layer.children] as HTMLElement[]; + const spots = nodes.map(node => { + const at = resolve(node.dataset.key || ''); + const rect: Box | null = at ? bounds(at) : null; + if (!rect) return ''; + const corner = still.toParent(rect.left + rect.width, rect.top); + const left = Math.round(corner.x - SIZE - INSET), top = Math.round(corner.y + INSET); + return left >= seen.left && top >= seen.top && left + SIZE <= seen.left + seen.width && top + SIZE <= seen.top + seen.height ? `${left},${top}` : ''; + }); + for (let index = 0; index < nodes.length; index++) { + const node = nodes[index], id = node.dataset.key || '', spot = spots[index]; + if (!spot) { + if (node === active) rescue(); + if (id === open) close(); + if (!node.hidden) node.hidden = true; + continue; + } + if (placed.get(id) !== spot) { + placed.set(id, spot); + const [left, top] = spot.split(','); + node.style.transform = `translate(${left}px, ${top}px)`; + } + if (node.hidden) node.hidden = false; + } + if (layer.hidden) layer.hidden = false; + if (open) aim(); + } + + function aim(): void { + const anchor = [...layer.children].find(node => (node as HTMLElement).dataset.key === open) as HTMLElement | undefined; + if (!anchor || anchor.hidden) { close(); return; } + const spot = anchor.getBoundingClientRect(); + const own = pop.getBoundingClientRect(); + const margin = 8; + let left = spot.right - own.width; + let top = spot.bottom + 4; + if (top + own.height > window.innerHeight - margin && spot.top - 4 - own.height >= margin) top = spot.top - 4 - own.height; + left = Math.max(margin, Math.min(left, window.innerWidth - margin - own.width)); + top = Math.max(margin, Math.min(top, window.innerHeight - margin - own.height)); + const next = `translate(${Math.round(left)}px, ${Math.round(top)}px)`; + if (pop.style.transform !== next) pop.style.transform = next; + } + + function poke(): void { + if (!on || frame) return; + frame = requestAnimationFrame(() => { frame = 0; place(); }); + } + + function paint(): void { + collect(); + describe(); + found.clear(); + fill(); + if (frame) { cancelAnimationFrame(frame); frame = 0; } + place(); + } + + function want(): void { + if (!on) return; + due = true; + if (timer || out) return; + timer = window.setTimeout(ask, Math.max(SETTLE_MS, last + GAP_MS - performance.now())); + } + + async function ask(): Promise { + timer = 0; + if (!on || !due || out || !current) return; + due = false; + out = true; + last = performance.now(); + const site = current.site.id, revision = current.revision, page = host.page(); + let result: { issues?: AuditIssue[] }; + try { + result = await request<{ issues: AuditIssue[] }>('/api/audit'); + } catch { + out = false; + if (!on) return; + failed = true; + paint(); + if (!said) { said = true; host.status('The audit could not be run, so the audit markers are hidden.', true); } + return; + } + out = false; + if (!on) return; + if (!current || current.site.id !== site || current.revision !== revision || host.page() !== page) { want(); return; } + take(result, site, revision); + if (due) want(); + } + + function take(result: { issues?: AuditIssue[] }, site: string, revision: number): void { + const issues = Array.isArray(result?.issues) ? result.issues.slice(0, MAX_ISSUES) : []; + answer = { site, revision, issues }; + failed = false; + said = false; + paint(); + } + + function set(next: boolean): void { + if (next === on) { box.checked = on; return; } + on = next; + box.checked = on; + remember(on); + if (on) { + if (valid()) paint(); else { answer = null; failed = false; paint(); want(); } + } else { + if (timer) { clearTimeout(timer); timer = 0; } + due = false; + rescue(); + close(); + if (frame) { cancelAnimationFrame(frame); frame = 0; } + if (!layer.hidden) layer.hidden = true; + } + host.status(on ? 'Audit markers are on: each element of this page with an issue shows a marker.' : 'Audit markers are off.'); + } + + function sync(next: EditorState): void { + current = next; + if (!on) return; + if (!valid()) want(); + if (answer) paint(); else poke(); + } + + function fresh(result: { issues: AuditIssue[] }): void { + if (!current) return; + take(result, current.site.id, current.revision); + } + + const watch = (event: Event): void => { + if (!on) return; + if (event.type === 'pointermove' && !(event as PointerEvent).buttons) return; + if (open && event.type === 'pointerdown') { + const target = event.target as Node | null; + if (!target || !(pop.contains(target) || layer.contains(target))) close(); + } + if (open && event.type === 'focusin' && (event.target as HTMLElement | null)?.dataset?.key !== open) close(); + poke(); + }; + for (const type of ['pointerdown', 'pointerup', 'pointercancel', 'pointermove', 'keydown', 'keyup', 'click', 'focusin', 'input', 'change', 'scroll', 'transitionend']) window.addEventListener(type, watch, { capture: true, passive: true }); + window.addEventListener('resize', poke); + const sized = new ResizeObserver(poke); + sized.observe(host.stage); + sized.observe(host.frame); + new MutationObserver(poke).observe(host.dialog, { attributes: true, attributeFilter: ['hidden'] }); + new MutationObserver(poke).observe(document.body, { attributes: true, attributeFilter: ['class'] }); + void host.loaded().then(() => { + const at = host.frame.contentDocument; + const view = host.frame.contentWindow as (Window & typeof globalThis) | null; + if (!at || !view) return; + doc = at; + for (const type of ['pointerdown', 'pointerup', 'pointercancel', 'pointermove', 'dblclick', 'focusout', 'keyup', 'scroll', 'load']) at.addEventListener(type, watch, { capture: true, passive: true }); + new view.ResizeObserver(poke).observe(at.documentElement); + new view.MutationObserver(poke).observe(at.documentElement, { attributes: true, attributeFilter: ['data-fw-dragging', 'data-fw-holding'] }); + poke(); + }); + + return { row, enabled: () => on, set, sync, fresh }; +} diff --git a/frontend/src/features/try/index.ts b/frontend/src/features/try/index.ts index 23d8d911..393f2f25 100644 --- a/frontend/src/features/try/index.ts +++ b/frontend/src/features/try/index.ts @@ -5,7 +5,7 @@ import { installChoiceLists } from './choice-list'; import type { LayerFrame, Trial, TrialEnd, TrialOwner, TryKit, TryOptions } from './types'; const STORE = 'formweb.try-choices'; -const PASS = new Set(['edit.copy', 'file.save', 'view.search', 'view.try-choices']); +const PASS = new Set(['edit.copy', 'file.save', 'view.search', 'view.try-choices', 'view.audit-markers']); const SURFACE = '.fw-menubar, .fw-menu, .fw-search-pop, [data-cmd]'; const MENU = '.fw-menubar, .fw-menu, .fw-search-pop'; const LANDING_MS = 30000; diff --git a/frontend/src/styles/audit-markers.css b/frontend/src/styles/audit-markers.css new file mode 100644 index 00000000..cb84af22 --- /dev/null +++ b/frontend/src/styles/audit-markers.css @@ -0,0 +1,14 @@ +.fw-audit-switch { display: grid; gap: var(--space-1); margin: 0 0 var(--space-3); } +.fw-audit-switch .micro { margin: 0; } +.fw-audit-switch .fw-audit-note { min-block-size: calc(2 * 1.6em); } +.fw-audit-marks[hidden], .fw-audit-dot[hidden], .fw-audit-pop[hidden] { display: none; } +.fw-audit-dot { position: fixed; left: 0; top: 0; z-index: var(--z-raised); box-sizing: border-box; display: grid; place-items: center; width: var(--space-5); height: var(--space-5); min-height: 0; margin: 0; padding: 0; border: 0; background: transparent; color: var(--text-primary); font-size: var(--fs-10); font-weight: 700; line-height: 1; font-variant-numeric: tabular-nums; pointer-events: auto; cursor: pointer; } +.fw-audit-dot::before { content: ''; position: absolute; inset: 0; box-sizing: border-box; border: 2px solid var(--cv-action-blue); border-radius: var(--radius-pill); background: var(--surface-2); box-shadow: var(--shadow-sm); } +.fw-audit-dot[data-severity='warning']::before { inset: 2px; border-color: var(--warn); border-radius: var(--radius-xs); transform: rotate(45deg); } +.fw-audit-dot[data-severity='error']::before { inset: 1px; border-color: var(--danger); border-radius: var(--radius-xs); } +.fw-audit-dot:hover { background: transparent; } +.fw-audit-dot:hover::before { background: var(--surface-raised); } +.fw-audit-dot:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 2px; } +.fw-audit-count { position: relative; } +.fw-audit-pop { position: fixed; left: 0; top: 0; z-index: var(--z-popover); box-sizing: border-box; max-width: min(320px, calc(100vw - var(--space-4))); padding: var(--space-2) var(--space-3); pointer-events: auto; border: 1px solid var(--line-2); border-radius: var(--radius-lg); background: color-mix(in srgb, var(--surface-2) 94%, transparent); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); box-shadow: var(--shadow-lg); color: var(--text-primary); font-size: var(--fs-12); } +.fw-audit-pop-list { display: grid; gap: var(--space-1); margin: 0; padding: 0 0 0 var(--space-4); } From 45ad36106c6defd0808cb67da4b19a09cda55f8d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:01:47 -0500 Subject: [PATCH 04/38] feat(desktop): Preferences chooses where exports are saved (Downloads, a folder you choose, or ask each time), the shell places every download there with a safe name and says when the folder could not be used, the audit dialog and the View menu switch the audit markers, and toolbar buttons keep Delete and Backspace to themselves --- frontend/src/features/export-folder.ts | 158 +++++++++++++++++ frontend/src/features/studio.ts | 5 +- frontend/src/main.ts | 38 +++- frontend/src/styles/export-folder.css | 12 ++ frontend/src/ui/downloads.ts | 60 ++++++- frontend/src/vector/exportscreens.ts | 17 +- frontend/src/vector/panel.ts | 9 +- src-tauri/build.rs | 3 + src-tauri/capabilities/default.json | 4 +- src-tauri/src/downloads.rs | 230 +++++++++++++++++++++++-- src-tauri/src/main.rs | 2 +- 11 files changed, 482 insertions(+), 56 deletions(-) create mode 100644 frontend/src/features/export-folder.ts create mode 100644 frontend/src/styles/export-folder.css diff --git a/frontend/src/features/export-folder.ts b/frontend/src/features/export-folder.ts new file mode 100644 index 00000000..d4ae799b --- /dev/null +++ b/frontend/src/features/export-folder.ts @@ -0,0 +1,158 @@ +import { labelAttr } from '../i18n'; +import { element } from '../ui/dom'; +import '../styles/export-folder.css'; + +export type ExportMode = 'downloads' | 'folder' | 'ask'; +export type ExportChoice = { mode: ExportMode; path: string }; + +type Core = { invoke(command: string, args?: Record): Promise }; + +const KEY = 'formweb.export-folder'; +const PATH_MAX = 4096; +const NAME_MAX = 1024; +const MODES: readonly ExportMode[] = ['downloads', 'folder', 'ask']; +const DEFAULT: ExportChoice = { mode: 'downloads', path: '' }; + +const core = (): Core | undefined => (window as unknown as { __TAURI__?: { core?: Core } }).__TAURI__?.core; + +function parse(raw: string | null): ExportChoice { + if (!raw || raw.length > PATH_MAX + 64) return DEFAULT; + try { + const value: unknown = JSON.parse(raw); + if (!value || typeof value !== 'object') return DEFAULT; + const { mode, path } = value as { mode?: unknown; path?: unknown }; + const kept = typeof path === 'string' && path.length <= PATH_MAX ? path : ''; + if (!MODES.includes(mode as ExportMode)) return DEFAULT; + if (mode === 'folder' && !kept) return DEFAULT; + return { mode: mode as ExportMode, path: kept }; + } catch { + return DEFAULT; + } +} + +function read(): ExportChoice { + try { return parse(localStorage.getItem(KEY)); } catch { return DEFAULT; } +} + +let current = read(); + +function hand(choice: ExportChoice): void { + const bridge = core(); + if (!bridge) return; + try { + void bridge.invoke('set_export_place', { mode: choice.mode, path: choice.path }).catch(() => undefined); + } catch { + return; + } +} + +const listeners = new Set<() => void>(); + +function keep(choice: ExportChoice): void { + current = choice; + try { + if (choice.mode === 'downloads' && !choice.path) localStorage.removeItem(KEY); + else localStorage.setItem(KEY, JSON.stringify(choice)); + } catch { } + hand(choice); + listeners.forEach(listener => listener()); +} + +hand(current); + +export const desktopShell = (): boolean => !!core(); + +export const exportChoice = (): ExportChoice => current; + +export function resetExportFolder(): void { + try { localStorage.removeItem(KEY); } catch { } + current = DEFAULT; + hand(DEFAULT); +} + +export function forgetAnswer(): void { + hand(current); +} + +export async function beforeDownload(name: string): Promise { + const bridge = core(); + if (!bridge || current.mode !== 'ask') return true; + try { + return (await bridge.invoke('ask_export_place', { name: name.slice(0, NAME_MAX) })) === true; + } catch { + return true; + } +} + +let mounted: HTMLElement | null = null; + +export function exportFolderRow(): HTMLElement { + if (mounted) return mounted; + const row = element('div', 'fw-export-folder'); + mounted = row; + if (!core()) { + row.append(element('p', 'micro', 'In a browser, the browser decides where downloads go.')); + return row; + } + row.dataset.ownKeys = ''; + row.setAttribute('role', 'radiogroup'); + const radios = new Map(); + const option = (mode: ExportMode, words: string): HTMLLabelElement => { + const radio = element('input'); + radio.type = 'radio'; + radio.name = 'fw-export-folder'; + radio.value = mode; + radios.set(mode, radio); + const wrap = element('label', 'checkbox-field'); + wrap.append(radio, element('span', '', words)); + return wrap; + }; + const pick = element('div', 'fw-export-pick'); + const choose = element('button', 'fw-export-choose'); + choose.type = 'button'; + choose.append(element('span', '', 'Choose folder...')); + const shown = element('span', 'fw-export-path'); + shown.dataset.noI18n = ''; + const none = element('span', 'fw-export-path is-empty', 'No folder chosen yet.'); + pick.append(choose, shown, none); + const note = element('p', 'micro', 'Export static site, Download project and the other downloads follow this choice. If the chosen folder cannot be used when a file is saved, the file goes to Downloads and the notice says so.'); + row.append(option('downloads', 'The Downloads folder'), option('folder', 'A folder you choose'), pick, option('ask', 'Ask each time'), note); + const paint = (): void => { + for (const [mode, radio] of radios) if (radio.checked !== (current.mode === mode)) radio.checked = current.mode === mode; + const path = current.path; + if (shown.textContent !== path) shown.textContent = path; + if (path) { if (shown.title !== path) shown.title = path; } else if (shown.hasAttribute('title')) shown.removeAttribute('title'); + if (shown.hidden !== !path) shown.hidden = !path; + if (none.hidden !== !!path) none.hidden = !!path; + labelAttr(choose, 'title', path ? 'Choose another folder' : 'Choose the folder exports are saved to'); + }; + let choosing = false; + const chooseFolder = async (): Promise => { + const bridge = core(); + if (!bridge || choosing) return false; + choosing = true; + choose.setAttribute('aria-busy', 'true'); + try { + const folder = await bridge.invoke('choose_export_folder', { start: current.path }); + if (typeof folder !== 'string' || !folder || folder.length > PATH_MAX) return false; + keep({ mode: 'folder', path: folder }); + return true; + } catch { + return false; + } finally { + choosing = false; + choose.removeAttribute('aria-busy'); + } + }; + choose.addEventListener('click', () => { void chooseFolder().then(paint); }); + for (const [mode, radio] of radios) { + radio.addEventListener('change', () => { + if (!radio.checked) return; + if (mode === 'folder' && !current.path) { void chooseFolder().then(paint); return; } + keep({ mode, path: current.path }); + }); + } + listeners.add(paint); + paint(); + return row; +} diff --git a/frontend/src/features/studio.ts b/frontend/src/features/studio.ts index 9b7bf87e..741eaf0f 100644 --- a/frontend/src/features/studio.ts +++ b/frontend/src/features/studio.ts @@ -2,6 +2,7 @@ import { accept, command, download, request, state, subscribe } from '../api'; import type { EditorState } from '../types'; import { element, keyed, labelPieces, options, text } from '../ui/dom'; import { icon } from '../ui/icons'; +import { deliverFile } from '../ui/downloads'; import { label, t } from '../i18n'; import { authoringActions } from './authoring'; import { serviceActions } from './services'; @@ -216,8 +217,8 @@ export class FeatureStudio { else { const path = typeof view.spec.path === 'function' ? view.spec.path(params) : view.spec.path!; if (view.spec.download) { - await download(path, view.spec.download); - response = { downloaded: view.spec.download }; + const file = view.spec.download; + response = { downloaded: await deliverFile(file, started => download(path, file, started)) ? file : null }; } else { const body = { ...params }; if (typeof view.spec.path === 'function') { delete body.id; delete body.source; delete body.email; } diff --git a/frontend/src/main.ts b/frontend/src/main.ts index a5b15372..c36017b0 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -18,7 +18,8 @@ import { DemoPreview } from './ui/demo-preview'; import { unsavedWork } from './ui/unsaved'; import { watchOpenedFiles } from './ui/opened-file'; import { Notice } from './ui/notice'; -import { deliver, isBusy } from './ui/downloads'; +import { deliver, isBusy, useNotice } from './ui/downloads'; +import { exportFolderRow, resetExportFolder } from './features/export-folder'; import { flash, issueField, rowOf, scrollNearest } from './ui/reveal'; import { FeatureStudio } from './features/studio'; import { RuntimePreview } from './features/runtime-preview'; @@ -53,6 +54,7 @@ import { canvasClick, installSelection, isMulti, isSelected, layerClick, topMost import { anyCopyable, anyRemovable, canStep, copySelected, countLabel, cutSelected, deletePagesNote, deleteSelectedPages, duplicateSelected, holdsMany, installSelectionActions, pasteMany, removeSelected, selectionNote, selectionTitle, stepSelected } from './features/selection-actions'; import { installCanvasDrag } from './features/canvas-drag'; import { installHoverOutline } from './features/hover-outline'; +import { installAuditMarkers } from './features/audit-markers'; import { installSelectMode, paintSelectMode } from './features/select-mode'; import { sectionToggle } from './features/panel/fold'; import { watchHelp } from './ui/help-fit'; @@ -244,6 +246,7 @@ brand.title = 'formweb by nodemode.ai'; const menus = menuModel(commandRegistry); const menubar = new Menubar(menus, overlay); const titleTools = element('div', 'fw-title-tools'); +titleTools.dataset.ownKeys = ''; const topActions = element('div', 'top-actions'); async function toggleAgents(): Promise { const result = await request<{ enabled?: boolean; agentsEnabled?: boolean }>('/api/agents', { enabled: !agentsEnabled }); @@ -269,6 +272,7 @@ if (document.documentElement.classList.contains('has-overlay-titlebar')) { } const toolbar = element('div', 'toolbar'); +toolbar.dataset.ownKeys = ''; const projectIdentity = element('div', 'project-identity'); const projectName = element('span', 'project-name', 'Connecting to site engine'); projectIdentity.append(icon('globe'), projectName); @@ -1070,7 +1074,24 @@ publishPane.append(field('Publication slug', publishSlug), publishOutput, publis const auditPane = dialogPane('audit'); const auditSummary = element('p', 'empty-note', 'Run the Rust engine audit to review this site.'); const auditList = element('div'); -auditPane.append(auditSummary, auditList); +const auditMarkers = installAuditMarkers({ + frame: canvas.frame, stage, overlay, dialog: scrim, loaded: () => canvas.loaded(), page: () => currentPage().id, + editing: () => !preview && !fullPreview.isOpen && !demoPreview.isOpen && !featureStudio.opened && !!home.root.hidden, busy: () => tryKit.busy(), + pick: (id, message, again) => { + const page = state().site.pages.find(item => descendants(item.root).has(id)); + if (!page || !state().site.nodes[id]) return; + pageId = page.id; + selectedId = id; + update(state()); + canvas.reveal(selectedId); + scrollNearest(layersList, rowOf(layersList, selectedId)); + const line = t('Selected {0}: {1}', [currentNode().name, message]); + status(line); + notice.show(line, { error: true, action: { label: 'Show again', run: again } }); + }, + rescue: () => inspectorTabButtons.get(activeInspector), status +}); +auditPane.append(auditSummary, auditMarkers.row, auditList); const cmsPane = dialogPane('cms'); const cmsLayout = element('div', 'dialog-pane'); @@ -1455,6 +1476,7 @@ const resetPrefs = button('Reset All Preferences...', 'trash', undefined, 'fw-pr const resetNote = element('p', 'micro', 'Every FormWeb preference on this device goes back to its default and the editor reloads. Your sites and projects are kept.'); const resetConfirm = button('Reset', undefined, () => { try { for (const key of Object.keys(localStorage)) if (key.startsWith('formweb.') || ['nodemode_ui_settings', 'formweb_theme', 'formweb_language', 'formweb_shortcuts', 'formweb_workspace', 'formweb_terminal', 'fw.vector.pathfinder'].includes(key)) localStorage.removeItem(key); } catch { } + resetExportFolder(); location.reload(); }, 'fw-prefs-danger'); const resetCancel = button('Cancel', undefined, () => { resetRow.hidden = true; resetPrefs.hidden = false; }); @@ -1464,7 +1486,8 @@ resetRow.append(resetNote, resetConfirm, resetCancel); resetPrefs.addEventListener('click', () => { resetPrefs.hidden = true; resetRow.hidden = false; }); const tokenNote = element('p', 'micro', 'For a server launched with FORMWEB_AUTH_TOKEN, enter its token below. It is stored only for this browser tab.'); const endpointNote = element('p', 'micro', `API endpoint: ${apiBase || 'same origin'} /api. The API and MCP use the same authoritative Rust document.`); -prefsAdd('General', prefsGroup('Startup', autoShowHomeLabel), prefsGroup('Reset', resetPrefs, resetRow)); +prefsAdd('General', prefsGroup('Startup', autoShowHomeLabel), prefsGroup('Where exports are saved', exportFolderRow()), prefsGroup('Reset', resetPrefs, resetRow)); +useNotice(notice); prefsAdd('Interface', prefsGroup('Theme', field('Editor theme', themeSelect)), prefsGroup('Language', field('Editor language', languageSelect)), prefsGroup('Design fields', field('Show in Design fields', designFieldsSelect), designFieldsNote, designFieldsAll, tryChoicesLabel, tryChoicesNote)); prefsAdd('Plugins', prefsGroup('Server access', tokenNote, field('Server access token', authToken), endpointNote)); settingsPane.append(prefsPages); @@ -1675,6 +1698,7 @@ function update(next: EditorState): void { if (passwordGatesFor !== site.id) void loadPasswordGates().catch(() => undefined); canvas.mark(selectedIds()); canvas.render(site, page, selectedId, widths[breakpoint], locale, breakpoint); + auditMarkers.sync(next); runtimePreview.update(preview, next, page.id, locale, widths[breakpoint]); if (refreshPreviewButton.classList.contains('active') !== preview) refreshPreviewButton.classList.toggle('active', preview); if (refreshPreviewButton.getAttribute('aria-pressed') !== String(preview)) refreshPreviewButton.setAttribute('aria-pressed', String(preview)); @@ -1696,7 +1720,7 @@ async function saveProject(): Promise { } async function downloadProject(): Promise { const file = state().site.name.toLowerCase().replace(/[^a-z0-9-]+/g, '-') + '.fweb'; - await deliver(file, { desktop: 'Saved {0} to your Downloads folder.', placed: 'Saved {0} to {1}.', browser: 'Downloaded {0}. Your browser lists it with its downloads.' }, notice, started => download('/api/project-file', file, started)); + if (!await deliver(file, { desktop: 'Saved {0} to your Downloads folder.', placed: 'Saved {0} to {1}.', browser: 'Downloaded {0}. Your browser lists it with its downloads.' }, notice, started => download('/api/project-file', file, started))) { status('Nothing was saved.'); return; } status('Editable .fweb project downloaded.'); } const NOT_FOUND_BASE_KEY = "The 404 page links its styles and pages from / because the base URL is still example.com. Set the base URL to the site's public address before you deploy it under a path."; @@ -1725,6 +1749,7 @@ function baseUrlAction(warning: string): { label: string; run: () => unknown } | async function exportSite(): Promise { const file = state().site.name.toLowerCase().replace(/[^a-z0-9-]+/g, '-') + '-site.zip'; const headers = await deliver(file, { desktop: 'Exported {0} to your Downloads folder.', placed: 'Exported {0} to {1}.', browser: 'Downloaded {0}. Your browser lists it with its downloads.' }, notice, started => download(`/api/export?locale=${encodeURIComponent(locale)}`, file, started), exportButton); + if (!headers) { status('Nothing was saved.'); return; } const warning = notFoundBaseWarning(); status([t('Static site exported for {0}.', [{ lang: locale }]), warning, localFormWarning(localFormHeader(headers))], false, baseUrlAction(warning)); } @@ -1789,7 +1814,8 @@ async function downloadQr(): Promise { const url = qrUrl.value.trim() || pageAddress(); const format = qrFormat.value || 'png'; const name = currentPage().slug.replace(/[^a-z0-9-]+/gi, '-').replace(/^-|-$/g, '') || 'home'; - await download(`/api/qr?format=${format}&scale=10&dark=${encodeURIComponent(qrDark.value)}&light=${encodeURIComponent(qrLight.value)}&url=${encodeURIComponent(url)}`, `qr-${name}.${format}`); + const file = `qr-${name}.${format}`; + if (!await deliver(file, { desktop: 'Saved {0} to your Downloads folder.', placed: 'Saved {0} to {1}.', browser: 'Downloaded {0}. Your browser lists it with its downloads.' }, notice, started => download(`/api/qr?format=${format}&scale=10&dark=${encodeURIComponent(qrDark.value)}&light=${encodeURIComponent(qrLight.value)}&url=${encodeURIComponent(url)}`, file, started))) { status('Nothing was saved.'); return; } status(`QR code downloaded for ${url}.`); } async function moveLayer(direction: number): Promise { @@ -1988,6 +2014,7 @@ function showIssue(row: HTMLElement): void { } async function auditSite(): Promise { const result = await request<{ issues: AuditIssue[]; counts: Record }>('/api/audit'); + auditMarkers.fresh(result); openDialog('audit'); text(auditSummary, result.issues.length === 1 ? '1 issue found. Select an element to resolve it in the inspector.' : result.issues.length ? t('{0} issues found. Select an element to resolve it in the inspector.', [result.issues.length]) : 'No issues found by the built-in audit. Review content and exported pages before release.'); keyed(auditList, result.issues.map((issue, index) => ({ ...issue, key: `${issue.code}-${issue.page || ''}-${issue.node || ''}-${index}` })), issue => issue.key, () => { @@ -2342,6 +2369,7 @@ registerCommands([ { id: 'view.theme', label: 'Light theme', menu: 'View', group: 2, run: () => setTheme(readChoice().theme === 'light' ? 'studio' : 'light'), checked: () => readChoice().theme === 'light' }, { id: 'view.design-controls', label: 'Show controls in Design fields', menu: 'View', group: 2, run: () => { controlKit.setDefaultRaw(!controlKit.defaultRaw()); status(controlKit.defaultRaw() ? 'Design fields show the CSS text only.' : 'Design fields show their controls.'); }, checked: () => !controlKit.defaultRaw() }, { id: 'view.try-choices', label: 'Try choices before keeping them', menu: 'View', group: 2, run: () => { tryKit.setEnabled(!tryKit.enabled()); tryChoices.checked = tryKit.enabled(); status(tryKit.enabled() ? 'A clicked choice now shows on the page until you press Keep.' : 'Clicked choices are now written at once.'); }, checked: () => tryKit.enabled() }, + { id: 'view.audit-markers', label: 'Show audit markers', menu: 'View', group: 2, run: () => auditMarkers.set(!auditMarkers.enabled()), checked: () => auditMarkers.enabled(), enabled: ready }, { id: 'view.search', label: 'Search commands', menu: 'View', keys: ['Mod+K'], global: true, group: 2, run: () => commandSearch.show() }, { id: 'view.menus-in-window', label: 'Menus in Window', menu: 'View', group: 2, enabled: desktopMac, checked: menusInWindow, run: () => { const on = !menusInWindow(); setMenusInWindow(on); status(on ? 'The menus stay in the window from the next start.' : 'The menus go to the menu bar from the next start.'); } }, { id: 'window.layers', label: 'Pages and layers', menu: 'Window', run: () => toggleLeft('pages'), checked: () => activeSidebar === 'pages' && layout.state.left === 'open' }, diff --git a/frontend/src/styles/export-folder.css b/frontend/src/styles/export-folder.css new file mode 100644 index 00000000..5bf60fc7 --- /dev/null +++ b/frontend/src/styles/export-folder.css @@ -0,0 +1,12 @@ +.fw-export-folder { display: flex; flex-direction: column; gap: var(--space-3); min-width: 0; } +.fw-export-folder .checkbox-field { margin-top: 0; } +.fw-export-folder .micro { margin: 0; padding: 0; } +.fw-export-folder input[type='radio'] { -webkit-appearance: none; appearance: none; flex: none; width: var(--check-size); min-width: var(--check-size); height: var(--check-size); min-height: var(--check-size); margin: 0; padding: 0; border-color: var(--check-edge); border-radius: 50%; cursor: pointer; } +.fw-export-folder input[type='radio']:hover { border-color: var(--text-muted); } +.fw-export-folder input[type='radio']:checked { border-color: var(--accent-color); background: radial-gradient(circle, var(--accent-color) 0 3.5px, transparent 4px); } +.fw-export-pick { display: flex; align-items: center; gap: var(--space-2); min-width: 0; min-height: var(--control-height); padding-left: calc(var(--check-size) + var(--space-2)); } +.fw-export-choose { flex: none; } +.fw-export-path { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-secondary); font-family: var(--font-mono); font-size: var(--fs-11); } +.fw-export-path.is-empty { color: var(--text-muted); font-family: inherit; } +.fw-export-path[hidden] { display: none; } +button[aria-busy='true'][aria-disabled='true'] { cursor: progress; } diff --git a/frontend/src/ui/downloads.ts b/frontend/src/ui/downloads.ts index dfad1b9b..16a7aaa3 100644 --- a/frontend/src/ui/downloads.ts +++ b/frontend/src/ui/downloads.ts @@ -1,8 +1,9 @@ import { t } from '../i18n'; import type { Notice } from './notice'; +import { beforeDownload, exportChoice, forgetAnswer } from '../features/export-folder'; type Core = { invoke(command: string): Promise }; -type Saved = { ok: boolean; file: string; folder: string }; +type Saved = { ok: boolean; file: string; folder: string; unusable: string }; export type Words = { desktop: string; placed: string; browser: string }; const core = (): Core | undefined => (window as unknown as { __TAURI__?: { core?: Core } }).__TAURI__?.core; @@ -10,13 +11,13 @@ const waiting = new Map void>(); const LISTEN_MS = 10 * 60 * 1000; window.addEventListener('formweb-download', event => { - const detail = (event as CustomEvent).detail as { url?: unknown; ok?: unknown; file?: unknown; folder?: unknown } | null; + const detail = (event as CustomEvent).detail as { url?: unknown; ok?: unknown; file?: unknown; folder?: unknown; unusable?: unknown } | null; if (!detail) return; const key = typeof detail.url === 'string' && waiting.has(detail.url) ? detail.url : waiting.size === 1 ? [...waiting.keys()][0] : ''; const done = waiting.get(key); if (!done) return; waiting.delete(key); - done({ ok: detail.ok === true, file: typeof detail.file === 'string' ? detail.file : '', folder: typeof detail.folder === 'string' ? detail.folder : '' }); + done({ ok: detail.ok === true, file: typeof detail.file === 'string' ? detail.file : '', folder: typeof detail.folder === 'string' ? detail.folder : '', unusable: typeof detail.unusable === 'string' ? detail.unusable.slice(0, 4096) : '' }); }); function whenSaved(url: string): Promise { @@ -47,24 +48,65 @@ async function showInFolder(notice: Notice): Promise { export const isBusy = (button: HTMLButtonElement): boolean => button.getAttribute('aria-busy') === 'true'; -export async function deliver(file: string, words: Words, notice: Notice, fetch: (started: (url: string) => void) => Promise, button?: HTMLButtonElement): Promise { +let shared: Notice | null = null; +const SAVED: Words = { desktop: 'Saved {0} to your Downloads folder.', placed: 'Saved {0} to {1}.', browser: 'Downloaded {0}. Your browser lists it with its downloads.' }; + +export const useNotice = (notice: Notice): void => { shared = notice; }; + +export async function deliverFile(file: string, fetch: (started: (url: string) => void) => Promise): Promise { + if (!shared) { await fetch(() => undefined); return true; } + const done = await deliver(file, SAVED, shared, fetch); + if (!done) shared.show(t('Nothing was saved.')); + return !!done; +} + +export function saveBlob(blob: Blob, name: string, started: (url: string) => void): Promise { + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = name; + link.rel = 'noopener'; + link.hidden = true; + document.body.append(link); + started(url); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(url), 60000); + return Promise.resolve(new Headers()); +} + +let turns: Promise = Promise.resolve(); + +export function deliver(file: string, words: Words, notice: Notice, fetch: (started: (url: string) => void) => Promise, button?: HTMLButtonElement): Promise { + if (!core() || exportChoice().mode !== 'ask') return send(file, words, notice, fetch, button, false); + const turn = turns.then(() => send(file, words, notice, fetch, button, true)); + turns = turn.catch(() => undefined); + return turn; +} + +async function send(file: string, words: Words, notice: Notice, fetch: (started: (url: string) => void) => Promise, button: HTMLButtonElement | undefined, asking: boolean): Promise { let pending: Promise | null = null; const desktop = !!core(); - if (button) { button.disabled = true; button.setAttribute('aria-busy', 'true'); } + if (button) { button.setAttribute('aria-disabled', 'true'); button.setAttribute('aria-busy', 'true'); } let headers: Headers; try { + if (asking && !(await beforeDownload(file))) return null; headers = await fetch(url => { if (desktop) pending = whenSaved(url); }); } catch (error) { + if (asking) forgetAnswer(); notice.show(error instanceof Error ? error.message : String(error), { error: true }); throw error; } finally { - if (button) { button.disabled = false; button.removeAttribute('aria-busy'); } + if (button) { button.removeAttribute('aria-disabled'); button.removeAttribute('aria-busy'); } } - notice.show(t(desktop ? words.desktop : words.browser, [file])); + const usual = !desktop || exportChoice().mode === 'downloads'; + notice.show(usual ? t(desktop ? words.desktop : words.browser, [file]) : t('Saving {0}...', [file])); void (pending as Promise | null)?.then(saved => { if (!saved) return; - if (!saved.ok) notice.show(t('{0} could not be saved to your Downloads folder. Check that the folder exists and has free space, then try again.', [file]), { error: true }); - else if (saved.folder) notice.show(t(words.placed, [saved.file || file, saved.folder]), { action: { label: 'Show in folder', run: () => showInFolder(notice) } }); + const reveal = { label: 'Show in folder', run: () => showInFolder(notice) }; + if (!saved.ok) notice.show(saved.folder && !usual ? t('{0} could not be saved to {1}. Check that the folder exists and has free space, then try again.', [file, saved.folder]) : t('{0} could not be saved to your Downloads folder. Check that the folder exists and has free space, then try again.', [file]), { error: true }); + else if (saved.unusable && saved.folder) notice.show(t('The chosen folder {0} could not be used, so {1} was saved to {2}.', [saved.unusable, saved.file || file, saved.folder]), { error: true, action: reveal }); + else if (saved.folder) notice.show(t(words.placed, [saved.file || file, saved.folder]), { action: reveal }); else notice.show(t(words.desktop, [saved.file || file])); }); return headers; diff --git a/frontend/src/vector/exportscreens.ts b/frontend/src/vector/exportscreens.ts index 2860728a..1100383a 100644 --- a/frontend/src/vector/exportscreens.ts +++ b/frontend/src/vector/exportscreens.ts @@ -1,5 +1,6 @@ import { label, labelAttr, t } from '../i18n'; import { element } from '../ui/dom'; +import { deliverFile, saveBlob } from '../ui/downloads'; import type { Host } from './host'; import { svgOf } from './store'; import { boards } from './artboards'; @@ -154,17 +155,7 @@ async function rasterize(source: Source, scale: number, format: Exclude URL.revokeObjectURL(url), 10000); -} +const download = (blob: Blob, name: string): Promise => deliverFile(name, started => saveBlob(blob, name, started)); const pause = (ms: number): Promise => new Promise(resolve => setTimeout(resolve, ms)); export const safeName = (value: string): string => value.replace(/[^\w.@+-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80); @@ -191,7 +182,7 @@ export async function exportScreens(host: Host, svgId: string, options: ExportOp const written: string[] = []; const queue: { blob: Blob; name: string }[] = []; await queueFiles(source, base, options, queue); - for (const item of queue) { download(item.blob, item.name); written.push(item.name); await pause(200); } + for (const item of queue) { if (await download(item.blob, item.name)) written.push(item.name); await pause(200); } return written; } @@ -215,7 +206,7 @@ export async function exportArtboards(host: Host, items: { id: string; name: str } if (!queue.length) throw new Error(t('No artboards on this page to export.')); const written: string[] = []; - for (const file of queue) { download(file.blob, file.name); written.push(file.name); await pause(200); } + for (const file of queue) { if (await download(file.blob, file.name)) written.push(file.name); await pause(200); } return written; } diff --git a/frontend/src/vector/panel.ts b/frontend/src/vector/panel.ts index 1d2836a5..ea6973c0 100644 --- a/frontend/src/vector/panel.ts +++ b/frontend/src/vector/panel.ts @@ -1,4 +1,5 @@ import { element, value } from '../ui/dom'; +import { deliverFile, saveBlob } from '../ui/downloads'; import { label, labelAttr, tn, type Value } from '../i18n'; import { openAverage } from './averagedialog'; import { openPathfinderOptions } from './pfdialog'; @@ -309,12 +310,8 @@ export class VectorPanel { download(): void { const markup = this.editor.exportText(); if (!markup) { this.editor.notify('Select a vector shape to export.'); return; } - const url = URL.createObjectURL(new Blob([markup], { type: 'image/svg+xml' })); - const link = document.createElement('a'); - link.href = url; - link.download = 'vector.svg'; - link.click(); - setTimeout(() => URL.revokeObjectURL(url), 1000); + const blob = new Blob([markup], { type: 'image/svg+xml' }); + void deliverFile('vector.svg', started => saveBlob(blob, 'vector.svg', started)).catch(() => undefined); } update(): void { diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 4a5717fd..b30eb2bd 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -9,6 +9,9 @@ const APP_COMMANDS: &[&str] = &[ "text_edit", "take_opened_file", "reveal_download", + "set_export_place", + "choose_export_folder", + "ask_export_place", ]; fn main() { diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 04ab3cff..447ffaaa 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -1,8 +1,8 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", - "description": "The editor talks HTTP to its local FormWeb service; through Tauri it asks the shell for the GPU renderer (probe, thumbnail, diff), to show the window, for the files the system asked it to open, for text edits and to show the last downloaded file in its folder. The window shows the page the service serves on 127.0.0.1 (8240 to 8279), a remote origin to Tauri, so the capability lists those addresses and every app command has an allow permission (build.rs).", + "description": "The editor talks HTTP to its local FormWeb service; through Tauri it asks the shell for the GPU renderer (probe, thumbnail, diff), to show the window, for the files the system asked it to open, for text edits, to show the last downloaded file in its folder, and where downloads are saved (the place chosen in Preferences, the system folder dialog, and the save dialog of ask each time, all opened by the shell). The window shows the page the service serves on 127.0.0.1 (8240 to 8279), a remote origin to Tauri, so the capability lists those addresses and every app command has an allow permission (build.rs).", "windows": ["main"], "remote": { "urls": ["http://127.0.0.1:(82[4-7][0-9])/*"] }, - "permissions": ["core:default", "core:window:allow-start-dragging", "core:window:allow-toggle-maximize", "allow-render-probe", "allow-render-thumbnail", "allow-render-diff", "allow-app-ready", "allow-set-window-title", "allow-text-edit", "allow-take-opened-file", "allow-reveal-download"] + "permissions": ["core:default", "core:window:allow-start-dragging", "core:window:allow-toggle-maximize", "allow-render-probe", "allow-render-thumbnail", "allow-render-diff", "allow-app-ready", "allow-set-window-title", "allow-text-edit", "allow-take-opened-file", "allow-reveal-download", "allow-set-export-place", "allow-choose-export-folder", "allow-ask-export-place"] } diff --git a/src-tauri/src/downloads.rs b/src-tauri/src/downloads.rs index 7b720ae8..8440376c 100644 --- a/src-tauri/src/downloads.rs +++ b/src-tauri/src/downloads.rs @@ -1,20 +1,50 @@ -//! Downloads from the page (Export static site, Download project). Every platform's web view saves them straight to the -//! Downloads folder with no prompt and no download bar, so the shell tells the page where each file went (a -//! `formweb-download` event) and keeps the last saved path for the page's Show in folder button. +//! Downloads from the page (Export static site, Download project). Every platform's web view saves them without a prompt +//! or a download bar, so the shell decides the place in `Requested` (the Downloads folder, the folder the person chose, +//! or the place the save dialog gave just before), tells the page where each file went (a `formweb-download` event) and +//! keeps the last saved path for the page's Show in folder button. use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::atomic::Ordering; use std::sync::Mutex; +use std::time::{Duration, Instant}; use tauri::webview::DownloadEvent; -#[cfg(target_os = "linux")] -use tauri::Manager; -use tauri::{Runtime, Webview}; +use tauri::{AppHandle, Manager, Runtime, Webview}; +use tauri_plugin_dialog::DialogExt; + +struct Request { + url: String, + destination: PathBuf, + placed: bool, + unusable: Option, +} + +#[derive(Clone, Debug, PartialEq)] +enum Place { + Downloads, + Folder(PathBuf), + Ask, +} + +/// A place the save dialog gave for the file the page is about to download, used once by the next download of that name. +struct Answer { + name: String, + path: PathBuf, + at: Instant, +} -static REQUESTED: Mutex> = Mutex::new(Vec::new()); +static REQUESTED: Mutex> = Mutex::new(Vec::new()); static LAST: Mutex> = Mutex::new(None); +static PLACE: Mutex = Mutex::new(Place::Downloads); +static ANSWERS: Mutex> = Mutex::new(Vec::new()); const KEPT: usize = 16; +const ANSWERS_KEPT: usize = 4; +const ANSWER_LIFE: Duration = Duration::from_secs(120); +const PATH_MAX: usize = 4096; +const NAME_MAX: usize = 200; +const NUMBER_MAX: u32 = 9999; +const FALLBACK_NAME: &str = "download"; pub fn on_download(webview: Webview, event: DownloadEvent<'_>) -> bool { match event { @@ -23,17 +53,53 @@ pub fn on_download(webview: Webview, event: DownloadEvent<'_>) -> if requested.len() >= KEPT { requested.remove(0); } - requested.push((url.to_string(), destination.clone())); + let raw = destination.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(); + let name = clean(&unnumbered(&raw)); + let reserved: Vec = requested.iter().map(|request| request.destination.clone()).collect(); + let taken = |path: &Path| path.exists() || reserved.iter().any(|other| other == path); + let place = PLACE.lock().unwrap().clone(); + let mut unusable = None; + let mut chosen = None; + match place { + Place::Folder(folder) => match usable(&folder) { + true => chosen = Some(free(&folder, &name, taken)), + false => unusable = Some(folder), + }, + Place::Ask => { + if let Some(path) = take_answer(&name) { + match path.parent().filter(|folder| usable(folder)) { + Some(_) => chosen = Some(path), + None => unusable = path.parent().map(Path::to_path_buf), + } + } + } + Place::Downloads => {} + } + let placed = chosen.is_some() || clean(&raw) != raw; + match chosen { + Some(path) => *destination = path, + None if placed => { + if let Some(folder) = destination.parent().map(Path::to_path_buf) { + *destination = free(&folder, &name, taken); + } + } + None => {} + } + requested.push(Request { url: url.to_string(), destination: destination.clone(), placed, unusable }); } DownloadEvent::Finished { url, path, success } => { let url = url.to_string(); let asked = { let mut requested = REQUESTED.lock().unwrap(); - requested.iter().position(|(seen, _)| *seen == url).map(|at| requested.remove(at).1) + requested.iter().position(|request| request.url == url).map(|at| requested.remove(at)) }; - let saved = path.filter(|path| path.is_file()).or(asked); + let placed = asked.as_ref().is_some_and(|request| request.placed); + let unusable = asked.as_ref().and_then(|request| request.unusable.as_ref()).map(|folder| folder.to_string_lossy().into_owned()).unwrap_or_default(); + let saved = path.filter(|path| path.is_file()).or(asked.map(|request| request.destination)); #[cfg(target_os = "linux")] - let saved = saved.map(|path| settle(&webview, path)); + let saved = saved.map(|path| if placed { path } else { settle(&webview, path) }); + #[cfg(not(target_os = "linux"))] + let _ = placed; if success { if let Some(path) = &saved { *LAST.lock().unwrap() = Some(path.clone()); @@ -48,6 +114,7 @@ pub fn on_download(webview: Webview, event: DownloadEvent<'_>) -> "ok": success, "file": saved.as_deref().and_then(Path::file_name).map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(), "folder": saved.as_deref().and_then(Path::parent).map(|folder| folder.to_string_lossy().into_owned()).unwrap_or_default(), + "unusable": unusable, }); let _ = webview.eval(format!("window.dispatchEvent(new CustomEvent('formweb-download', {{ detail: {detail} }}))")); } @@ -65,7 +132,7 @@ fn settle(webview: &Webview, path: PathBuf) -> PathBuf { if !path.is_file() || path.parent() == Some(folder.as_path()) || std::fs::create_dir_all(&folder).is_err() { return path; } - let target = free(&folder, &unnumbered(name)); + let target = free(&folder, &unnumbered(name), Path::exists); if std::fs::rename(&path, &target).is_ok() || (std::fs::copy(&path, &target).is_ok() && std::fs::remove_file(&path).is_ok()) { target } else { @@ -74,32 +141,159 @@ fn settle(webview: &Webview, path: PathBuf) -> PathBuf { } /// The base name and extension, split at the first dot as the web view does. -#[cfg(target_os = "linux")] fn split(name: &str) -> (&str, &str) { name.find('.').map_or((name, ""), |at| name.split_at(at)) } /// The name without the " (2)" the web view added for a file of that name in the folder it used. -#[cfg(target_os = "linux")] fn unnumbered(name: &str) -> String { let (base, ext) = split(name); - let kept = base.rsplit_once(" (").filter(|(_, n)| n.strip_suffix(')').is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))).map_or(base, |(kept, _)| kept); + let kept = base.rsplit_once(" (").filter(|(_, n)| n.strip_suffix(')').is_some_and(|n| !n.is_empty() && n.len() <= 6 && n.bytes().all(|b| b.is_ascii_digit()))).map_or(base, |(kept, _)| kept); format!("{kept}{ext}") } /// `name` in `folder`, or "base (1).ext", "base (2).ext" and so on when that is taken, as the web views do. -#[cfg(target_os = "linux")] -fn free(folder: &Path, name: &str) -> PathBuf { +fn free(folder: &Path, name: &str, taken: impl Fn(&Path) -> bool) -> PathBuf { let (base, ext) = split(name); let mut path = folder.join(name); let mut count = 1; - while path.exists() { + while taken(&path) && count <= NUMBER_MAX { path = folder.join(format!("{base} ({count}){ext}")); count += 1; } + if taken(&path) { + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|time| time.as_millis()).unwrap_or_default(); + path = folder.join(format!("{base} ({stamp}){ext}")); + } path } +const RESERVED: &[&str] = &["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"]; + +/// A device name Windows reserves in every folder, whatever follows its first dot. +fn reserved(name: &str) -> bool { + let stem = name.split('.').next().unwrap_or("").trim_end_matches(' ').to_ascii_uppercase(); + if RESERVED.contains(&stem.as_str()) { + return true; + } + let digit = stem.get(3..).unwrap_or(""); + (stem.starts_with("COM") || stem.starts_with("LPT")) && matches!(digit, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "0" | "\u{b9}" | "\u{b2}" | "\u{b3}") +} + +/// The file name a download may use: the last part of what the page or the web view suggested, without separators, +/// drive letters, characters Windows refuses, control and direction characters, leading dots, trailing dots and +/// spaces, or a device name, and at most `NAME_MAX` bytes with its short extension kept. Anything left empty is +/// `FALLBACK_NAME`. +fn clean(suggested: &str) -> String { + let last = suggested.rsplit(['/', '\\']).next().unwrap_or(""); + let mut name: String = last + .chars() + .filter(|c| !c.is_control() && !matches!(c, '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{feff}')) + .map(|c| if matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*') { '_' } else { c }) + .collect(); + name = name.trim_start_matches(['.', ' ']).trim_end_matches(['.', ' ']).to_string(); + if name.len() > NAME_MAX { + let ext = name.rfind('.').map(|at| &name[at..]).filter(|ext| ext.len() <= 16).unwrap_or("").to_string(); + let mut end = NAME_MAX - ext.len(); + while !name.is_char_boundary(end) { + end -= 1; + } + name = format!("{}{ext}", name[..end].trim_end_matches(['.', ' '])); + } + if name.is_empty() || name.starts_with('.') { + return FALLBACK_NAME.to_string(); + } + if reserved(&name) { + name.insert(0, '_'); + } + name +} + +/// A folder the shell may save into now: absolute, an existing directory, and one where a new file can be created. +fn usable(folder: &Path) -> bool { + if !folder.is_absolute() || !folder.is_dir() { + return false; + } + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|time| time.as_nanos()).unwrap_or_default(); + let probe = folder.join(format!(".formweb-write-check-{}-{stamp}", std::process::id())); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) { + Ok(file) => { + drop(file); + let _ = std::fs::remove_file(&probe); + true + } + Err(_) => false, + } +} + +/// The dialog's answer for a file of this name, if one is waiting and fresh; it is used once. +fn take_answer(name: &str) -> Option { + let mut answers = ANSWERS.lock().unwrap(); + answers.retain(|answer| answer.at.elapsed() < ANSWER_LIFE); + let at = answers.iter().position(|answer| answer.name == name)?; + Some(answers.remove(at).path) +} + +fn place_of(mode: &str, path: &str) -> Place { + match mode { + "folder" if !path.is_empty() && path.len() <= PATH_MAX => Place::Folder(PathBuf::from(path)), + "ask" => Place::Ask, + _ => Place::Downloads, + } +} + +/// Where the page's downloads go, as the person chose in Preferences. The folder is checked when a file is saved, not here. +#[tauri::command] +pub fn set_export_place(mode: String, path: String) { + *PLACE.lock().unwrap() = place_of(&mode, &path); + ANSWERS.lock().unwrap().clear(); +} + +fn start_folder(app: &AppHandle, wanted: &str) -> Option { + let wanted = (!wanted.is_empty() && wanted.len() <= PATH_MAX).then(|| PathBuf::from(wanted)).filter(|path| path.is_absolute() && path.is_dir()); + wanted.or_else(|| app.path().download_dir().ok().filter(|path| path.is_dir())) +} + +/// The system folder dialog, opened on `start` when it is a folder; the chosen folder, or nothing after Cancel. +#[tauri::command] +pub async fn choose_export_folder(app: AppHandle, start: String) -> Option { + let mut dialog = app.dialog().file().set_can_create_directories(true); + if let Some(folder) = start_folder(&app, &start) { + dialog = dialog.set_directory(folder); + } + if let Some(window) = app.get_webview_window("main") { + dialog = dialog.set_parent(&window); + } + let folder = dialog.blocking_pick_folder()?.into_path().ok()?; + let text = folder.to_string_lossy().into_owned(); + (text.len() <= PATH_MAX).then_some(text) +} + +/// The system save dialog for the file the page is about to download, before the download starts. The place is kept +/// for the next download of that name within `ANSWER_LIFE`; false after Cancel, and then nothing is kept. +#[tauri::command] +pub async fn ask_export_place(app: AppHandle, name: String) -> bool { + let suggested = clean(&name); + let name = clean(&unnumbered(&name)); + let mut dialog = app.dialog().file().set_file_name(suggested.clone()).set_can_create_directories(true); + if let Some(folder) = start_folder(&app, "") { + dialog = dialog.set_directory(folder); + } + if let Some(window) = app.get_webview_window("main") { + dialog = dialog.set_parent(&window); + } + let Some(path) = dialog.blocking_save_file().and_then(|path| path.into_path().ok()) else { return false }; + let Some(folder) = path.parent().filter(|folder| folder.is_absolute()).map(Path::to_path_buf) else { return false }; + let file = path.file_name().map(|file| clean(&file.to_string_lossy())).unwrap_or(suggested); + let mut answers = ANSWERS.lock().unwrap(); + answers.retain(|answer| answer.at.elapsed() < ANSWER_LIFE && answer.name != name); + if answers.len() >= ANSWERS_KEPT { + answers.remove(0); + } + answers.push(Answer { name, path: folder.join(file), at: Instant::now() }); + true +} + /// What went wrong, as a stable code the page turns into a sentence in the person's language, with the file's name and /// folder and, for a file manager that did not start, the system's own reason. #[derive(serde::Serialize, Debug, PartialEq)] diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 34cf0d2c..4696e60c 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -383,7 +383,7 @@ fn main() { traffic_lights::place(window); } }) - .invoke_handler(tauri::generate_handler![render::render_probe, render::render_thumbnail, render::render_diff, reveal::app_ready, traffic_lights::set_window_title, text_edit::text_edit, take_opened_file, downloads::reveal_download]) + .invoke_handler(tauri::generate_handler![render::render_probe, render::render_thumbnail, render::render_diff, reveal::app_ready, traffic_lights::set_window_title, text_edit::text_edit, take_opened_file, downloads::reveal_download, downloads::set_export_place, downloads::choose_export_folder, downloads::ask_export_place]) .setup(|app| { reveal::round_splash(app.handle()); let handle = app.handle().clone(); From bcffcd30b43e2b4859652f643e4764843412cac3 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:43:14 -0500 Subject: [PATCH 05/38] fix(wave): the import review reads a link the way a browser does, so a backslash can no longer make it name the wrong host, and its stylesheet scan no longer stalls on an unterminated import; the shell alone records the folder a person chose and refuses an ask-mode download nobody was asked about; a held or failed audit no longer leaves stale markers or asks again on every click; kept style rules cannot redefine a name the site already uses --- backend/app/library_routes.py | 4 +- backend/app/site_import.py | 96 +++++++--- frontend/src/features/audit-markers.ts | 24 ++- frontend/src/features/convert/index.ts | 26 ++- frontend/src/features/convert/measure.ts | 83 ++++++--- frontend/src/features/convert/rules.ts | 18 +- frontend/src/features/export-folder.ts | 40 +++-- frontend/src/features/library/importer.ts | 8 +- frontend/src/features/library/site-import.ts | 16 +- frontend/src/features/library/types.ts | 2 +- frontend/src/main.ts | 5 +- frontend/src/styles/export-folder.css | 1 + frontend/src/ui/downloads.ts | 11 +- frontend/src/vector/exportscreens.ts | 17 +- src-tauri/src/downloads.rs | 174 +++++++++++++++---- 15 files changed, 382 insertions(+), 143 deletions(-) diff --git a/backend/app/library_routes.py b/backend/app/library_routes.py index 10b92705..a0cb2aa9 100644 --- a/backend/app/library_routes.py +++ b/backend/app/library_routes.py @@ -319,7 +319,9 @@ async def library_import_html(request: Request): result = await studio.mutate('batch', {'commands': commands, 'expectedRevision': revision}) studio.access.record('library.import-html', {'node': host, 'bytes': len(document)}) warnings = [] if shim or not module else ['The script ran as a module with no kit helpers.'] - return {**(result if isinstance(result, dict) else {}), 'root': host, 'warnings': warnings + ([site_import.left_out_scripts(foreign)] if foreign else [])} + outside, more = await asyncio.to_thread(site_import.outside_of, document) + return {**(result if isinstance(result, dict) else {}), 'root': host, 'warnings': warnings + ([site_import.left_out_scripts(foreign)] if foreign else []), + 'outside': outside, 'outsideMore': more} async def _archive(request: Request) -> bytes | dict | list: diff --git a/backend/app/site_import.py b/backend/app/site_import.py index 3649140f..51544deb 100644 --- a/backend/app/site_import.py +++ b/backend/app/site_import.py @@ -13,7 +13,7 @@ import zipfile import zlib from html import escape, unescape -from urllib.parse import unquote, urlsplit, urlunsplit +from urllib.parse import unquote, urlsplit from .assets import SIZE_LIMITS, check_upload_svg, ingest, own_asset, sniff_extension from .config import MAX_IMAGE_BYTES, MAX_SITE_ARCHIVE_BYTES @@ -61,41 +61,83 @@ TITLE = re.compile(r']*(?:>|\Z)(.*?)(?:|\Z)', re.I | re.S) PAIR = re.compile(r'''([A-Za-z_:][-A-Za-z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>=`]+)))?''') CSS_URL = re.compile(r'''url\(\s*(?:"([^"]*)"|'([^']*)'|([^()'"\s]*))\s*\)''', re.I) -CSS_IMPORT = re.compile(r'''@import\s+(?:url\(\s*)?["']?([^"')\s;]+)["']?\s*\)?([^;{}@]*);''', re.I) +CSS_IMPORT = re.compile(r'''@import\s++(?:url\(\s*+)?["']?([^"')\s;]++)["']?\s*+\)?([^;{}@]*+);''', re.I) OUTSIDE_SHOWN = 20 URL_MAX = 2048 HOST_MAX = 253 HOST_CHARS = frozenset('abcdefghijklmnopqrstuvwxyz0123456789-') +SCHEME_CHARS = frozenset('abcdefghijklmnopqrstuvwxyz0123456789+-.') +C0_SPACE = ''.join(chr(code) for code in range(0x21)) +DEVIATIONS = frozenset('ßς‌‍ẞ') DEFAULT_PORTS = {'http': 80, 'https': 443} +def _number(part: str) -> int | None: + """One part of a host that ends in a number, read as browsers read it: 0x hex, a leading 0 octal, else decimal.""" + if not part: + return None + digits, base = (part[2:], 16) if part[:2].lower() == '0x' else (part[1:], 8) if len(part) > 1 and part[0] == '0' else (part, 10) + if not digits: + return 0 + return int(digits, base) if all(c in '0123456789abcdef'[:base] for c in digits.lower()) else None + + +def _ipv4(host: str) -> str | None: + """The dotted form browsers give a host whose last label is a number; None when they would refuse the URL.""" + parts = host.split('.') + numbers = [_number(part) for part in parts] if len(parts) <= 4 else [None] + if None in numbers or any(n > 255 for n in numbers[:-1]) or numbers[-1] >= 256 ** (5 - len(numbers)): + return None + value = numbers[-1] + sum(n * 256 ** (3 - i) for i, n in enumerate(numbers[:-1])) + return '.'.join(str(value >> shift & 255) for shift in (24, 16, 8, 0)) + + def outside_file(kind: str, reference: str) -> dict | None: - """A file a page loads from another host, as the review names it: its kind, the lower-cased ASCII host (with the port - only when it is not the scheme's default; any port of a protocol-relative URL) and the URL without credentials. None - for anything that is not plainly an http, https or protocol-relative URL with a host of letters, digits and hyphens.""" - value = reference.strip(' \t\n\r\f').replace('\t', '').replace('\n', '').replace('\r', '') + """A file a page loads from another host, as the review names it: its kind, the host a browser would ask (lower-cased + ASCII, IPv4 in dotted form, the port only when it is not the scheme's default) and the URL without credentials. Read + the way browsers read http and https references: C0 controls and spaces trimmed, tabs and line breaks removed, a + backslash before the host taken as a slash, the last @ ending the credentials. None for anything else, and for every + form whose host depends on the page's own scheme or that browsers might read another way.""" + value = reference.strip(C0_SPACE).replace('\t', '').replace('\n', '').replace('\r', '') if not value or len(value) > URL_MAX or not value.isprintable(): return None - try: - parts = urlsplit(value) - port = parts.port - raw = parts.hostname or '' - except ValueError: + colon = value.find(':') + scheme = value[:colon].lower() if colon > 0 and value[0].isascii() and value[0].isalpha() and set(value[:colon].lower()) <= SCHEME_CHARS else '' + if scheme and scheme not in DEFAULT_PORTS: + return None + lead = value[colon + 1:] if scheme else value + if len(lead) < 2 or lead[0] not in '/\\' or lead[1] not in '/\\': return None - scheme = parts.scheme.lower() - if not (scheme in DEFAULT_PORTS or (not scheme and value.startswith('//'))) or not parts.netloc: + tail = lead.lstrip('/\\') + end = next((i for i, c in enumerate(tail) if c in '/\\?#'), len(tail)) + authority, after = tail[:end].rsplit('@', 1)[-1], tail[end:] + raw, _, port_text = authority.partition(':') + if not raw or raw.startswith('[') or len(raw) > HOST_MAX or not (port_text == '' or (port_text.isascii() and port_text.isdigit() and int(port_text) <= 65535)): return None - raw = raw[:-1] if raw.endswith('.') else raw - if not raw or len(raw) > HOST_MAX: + if any(c in '%\\@' or c.isspace() for c in raw) or any(c in DEVIATIONS or unicodedata.ucd_3_2_0.category(c) == 'Cn' for c in raw if not c.isascii()): return None try: - host = raw.encode('idna').decode('ascii').lower() + host = (raw if raw.isascii() else raw.encode('idna').decode('ascii')).lower() + for label in host.split('.'): + if label.startswith('xn--'): + label.encode('ascii').decode('idna') except (UnicodeError, ValueError): return None - if len(host) > HOST_MAX or not all(0 < len(label) <= 63 and label[0] != '-' and label[-1] != '-' and set(label) <= HOST_CHARS for label in host.split('.')): + labels = host.split('.') + if host.endswith('.') or len(host) > HOST_MAX: + return None + if labels[-1].isdigit() or _number(labels[-1]) is not None and labels[-1][:2] == '0x': + host = _ipv4(host) + if host is None: + return None + elif not all(0 < len(label) <= 63 and label[0] != '-' and label[-1] != '-' and set(label) <= HOST_CHARS for label in labels): + return None + port = int(port_text) if port_text else None + if not scheme and port in (80, 443): return None shown = host if port is None or port == DEFAULT_PORTS.get(scheme) else f'{host}:{port}' - return {'kind': kind, 'host': shown, 'url': urlunsplit((scheme, shown, parts.path, parts.query, parts.fragment))} + cut = next((i for i, c in enumerate(after) if c in '?#'), len(after)) + return {'kind': kind, 'host': shown, 'url': f'{scheme + ":" if scheme else ""}//{shown}{after[:cut].replace(chr(92), "/")}{after[cut:]}'} def outside_list(found: list[tuple[str, str]]) -> tuple[list[dict], int]: @@ -482,9 +524,9 @@ def take(self, path: str) -> bool: def css(self, text: str, base: str, missing: set, depth: int = 0, seen: frozenset = frozenset(), source: str = '') -> str: def imported(match): found = self.locate(match.group(1), base) + if self.listing is not None and (found is None or found[0] not in self.files): + self.listing.append(('stylesheet', match.group(1))) if found is None and not match.group(1).strip().lower().startswith('data:'): - if self.listing is not None: - self.listing.append(('stylesheet', match.group(1))) if match.group(0) not in self.outside: self.outside.append(match.group(0)) return '' @@ -585,9 +627,10 @@ def _page(site: Site, path: str, body: bytes, kit_script) -> dict: continue if source is not None: found = site.locate(source, base) + if found is None or found[0] not in site.files: + site.listing.append(('script', source)) if found is None: outside_scripts.add(source[:120]) - site.listing.append(('script', source)) elif found[0] in site.files and site.files[found[0]][0] == 'script': content = _text(site.files[found[0]][1]) if content.strip(): @@ -602,8 +645,9 @@ def _page(site: Site, path: str, body: bytes, kit_script) -> dict: continue href = attrs.get('href', '') found = site.locate(href, base) - if found is None: + if found is None or found[0] not in site.files: site.listing.append(('stylesheet', href)) + if found is None: if href.strip() and block.start() < body_at: outside_styles.add(href[:120]) elif found[0] in site.files and site.files[found[0]][0] == 'style': @@ -747,6 +791,14 @@ def review(result: dict) -> dict: 'notes': ['Each page arrives as one code section: its HTML, CSS and first script, editable as code. Code sections run in Preview and in exports, not on the canvas.']} +def outside_of(document: str) -> tuple[list[dict], int]: + """The outside files of one page given as text (Import HTML as a section), listed as the review lists them.""" + if len(document) > FILE_CAPS['page']: + return [], 0 + page = _page(Site({}), 'page.html', document.encode('utf-8', 'replace'), lambda script: (script, False)) + return page['outside'], page['outsideMore'] + + def summary(pages: int, assets: int, skipped: int) -> str: made = f'Imported {pages} page{"" if pages == 1 else "s"} and {assets} asset{"" if assets == 1 else "s"}.' if skipped: diff --git a/frontend/src/features/audit-markers.ts b/frontend/src/features/audit-markers.ts index f49ca504..757d7b7f 100644 --- a/frontend/src/features/audit-markers.ts +++ b/frontend/src/features/audit-markers.ts @@ -15,7 +15,7 @@ export interface AuditMarkersHost { editing: () => boolean; busy: () => boolean; pick: (id: string, message: string, again: () => void) => void; - rescue: () => HTMLElement | null | undefined; + rescue: () => (HTMLElement | null | undefined)[]; status: (message: string, error?: boolean) => void; } @@ -24,7 +24,7 @@ export interface AuditMarkers { enabled: () => boolean; set: (on: boolean) => void; sync: (next: EditorState) => void; - fresh: (answer: { issues: AuditIssue[] }) => void; + fresh: (answer: { issues: AuditIssue[] }, site: string, revision: number) => void; } interface Answer { site: string; revision: number; issues: AuditIssue[] } @@ -58,6 +58,7 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { let current: EditorState | null = null; let answer: Answer | null = null; let failed = false; + let failedAt = ''; let said = false; let out = false; let due = false; @@ -145,8 +146,11 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { function rescue(): void { if (!focused()) return; - const target = host.rescue(); - if (target?.isConnected) target.focus({ preventScroll: true }); + for (const target of host.rescue()) { + if (!target?.isConnected || !target.getClientRects().length || (target as HTMLButtonElement).disabled) continue; + target.focus({ preventScroll: true }); + if (document.activeElement === target) return; + } } function close(): void { @@ -312,6 +316,7 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { out = false; if (!on) return; failed = true; + failedAt = `${site}:${revision}`; paint(); if (!said) { said = true; host.status('The audit could not be run, so the audit markers are hidden.', true); } return; @@ -327,6 +332,7 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { const issues = Array.isArray(result?.issues) ? result.issues.slice(0, MAX_ISSUES) : []; answer = { site, revision, issues }; failed = false; + failedAt = ''; said = false; paint(); } @@ -337,7 +343,7 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { box.checked = on; remember(on); if (on) { - if (valid()) paint(); else { answer = null; failed = false; paint(); want(); } + if (valid()) paint(); else { answer = null; failed = false; failedAt = ''; paint(); want(); } } else { if (timer) { clearTimeout(timer); timer = 0; } due = false; @@ -352,13 +358,15 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { function sync(next: EditorState): void { current = next; if (!on) return; - if (!valid()) want(); + if (!valid() && failedAt !== `${next.site.id}:${next.revision}`) want(); if (answer) paint(); else poke(); } - function fresh(result: { issues: AuditIssue[] }): void { + function fresh(result: { issues: AuditIssue[] }, site: string, revision: number): void { if (!current) return; - take(result, current.site.id, current.revision); + if (current.site.id === site && current.revision === revision) { take(result, site, revision); return; } + failedAt = ''; + want(); } const watch = (event: Event): void => { diff --git a/frontend/src/features/convert/index.ts b/frontend/src/features/convert/index.ts index 1886f30f..65875a51 100644 --- a/frontend/src/features/convert/index.ts +++ b/frontend/src/features/convert/index.ts @@ -7,7 +7,7 @@ import type { CommandDef } from '../../ui/shell'; import type { MenuEntry } from '../../ui/context-menu'; import type { Command, EditorState, SiteNode } from '../../types'; import { blocks, measure, SCOPE, TooLarge, type Block, type Plan, type Planned, type Source } from './measure'; -import { refusal, ROOT_FORCED, summary, type SiteFont } from './rules'; +import { refusal, ROOT_FORCED, scriptWords, summary, type SiteFont } from './rules'; import '../../styles/convert.css'; export const CONVERT_ID = 'library.convert-section'; @@ -94,6 +94,17 @@ function partCommands(site: EditorState['site'], host: SiteNode, record: Section return list; } +/** The words the site's own styles, tokens, fonts and code use, lower case, leaving out the sections being converted: + * page-wide names (keyframes, font faces, registered properties) a kept stylesheet must not take. */ +function siteNames(site: EditorState['site'], skip: Set): Set { + const code = site.extensions?.code as { sections?: Record } | undefined; + const sections = Object.fromEntries(Object.entries(code?.sections || {}).filter(([id]) => !skip.has(id))); + const text = JSON.stringify([Object.values(site.nodes).map(node => [node.styles, node.breakpoints]), site.tokens, site.extensions?.design, { ...code, sections }]); + const names = new Set(); + scriptWords(text.toLowerCase(), names, 500000); + return names; +} + function fontsCommand(site: EditorState['site'], fonts: Record | null): Command[] { if (!fonts) return []; const before = ((site.extensions?.design as { fonts?: Record } | undefined)?.fonts) || {}; @@ -149,6 +160,7 @@ export async function convertSections(ids: string[], keepScript: boolean, part?: const hosts = ids.map(id => site.nodes[id]).filter((node): node is SiteNode => !!node && !!sectionOf(site, node.id)?.html?.trim()); if (!hosts.length) throw new Error(t('Select a code section that holds HTML to convert.')); const taken = new Set(Object.keys(site.nodes)); + const names = keepScript ? siteNames(site, new Set(hosts.map(host => host.id))) : undefined; let fonts = { ...(((site.extensions?.design as { fonts?: Record } | undefined)?.fonts) || {}) }; const plans: Plan[] = []; const done: SiteNode[] = []; @@ -157,7 +169,7 @@ export async function convertSections(ids: string[], keepScript: boolean, part?: let plan: Plan; try { plan = await measure(sourceOf(sectionOf(site, host.id)!), { - origin: location.origin, keepScript, fonts, taken: id => taken.has(id), limit: LIMIT, depth: DEPTH, seconds: SECONDS, scope: host.id + origin: location.origin, keepScript, fonts, taken: id => taken.has(id), limit: LIMIT, depth: DEPTH, seconds: SECONDS, scope: host.id, siteNames: names }, part); } catch (error) { if (!(error instanceof TooLarge) || hosts.length === 1) throw error; @@ -185,7 +197,7 @@ export async function convertSections(ids: string[], keepScript: boolean, part?: const outcome = plans.map(plan => plan.outcome).reduce((all, one) => ({ converted: all.converted + one.converted, responsive: all.responsive + one.responsive, effects: all.effects + one.effects, floats: all.floats + one.floats, pictures: all.pictures + one.pictures, refused: all.refused + one.refused, scripted: all.scripted + one.scripted, left: all.left + one.left, - kept: all.kept + one.kept, keptAll: all.keptAll + one.keptAll, keptOver: all.keptOver + one.keptOver, keptDropped: all.keptDropped + one.keptDropped, + kept: all.kept + one.kept, keptAll: all.keptAll + one.keptAll, keptOver: all.keptOver + one.keptOver, keptClash: all.keptClash + one.keptClash, keptDropped: all.keptDropped + one.keptDropped, parts: Object.fromEntries([...new Set([...Object.keys(all.parts), ...Object.keys(one.parts)])].map(key => [key, (all.parts[key as keyof typeof all.parts] || 0) + (one.parts[key as keyof typeof one.parts] || 0)])) })); outcome.left += left; @@ -243,7 +255,11 @@ export function installConvert(host: ConvertHost): { commands: CommandDef[]; ent const close = (): void => { if (box.hidden) return; - if (box.contains(document.activeElement)) document.querySelector('.inspector-tabs .active, .inspector-tabs button')?.focus({ preventScroll: true }); + if (box.contains(document.activeElement)) { + const shown = (node: HTMLElement | null): node is HTMLElement => !!node && node.getClientRects().length > 0; + const tab = document.querySelector('.inspector-tabs button.active'), audit = document.querySelector('[data-cmd="page.audit"]'); + (shown(tab) ? tab : shown(audit) ? audit : null)?.focus({ preventScroll: true }); + } box.hidden = true; }; const say = (message: string, error = false): void => { text(note, message); note.classList.toggle('is-error', error); }; @@ -339,7 +355,7 @@ export function installConvert(host: ConvertHost): { commands: CommandDef[]; ent part: { type: 'integer', min: 0, description: 'Convert only this top-level block of the section (0 is the first), for a page too large for one conversion.' } }, enabled: () => host.ready() && anySection(), - description: 'Turn a code section (an imported page or any section of plain HTML and CSS) into ordinary FormWeb elements with their own text, links, pictures and base styles measured at desktop width, in one undo step. Scripts, inline frames and vector graphics stay as small code sections in place; responsive rules are not carried over. A kept script keeps the style rules no converted element uses, so what it builds is styled in Preview and the export. Without parameters it opens a short dialog for the selected element; with node or nodes it converts at once and returns the result sentence.', + description: 'Turn a code section (an imported page or any section of plain HTML and CSS) into ordinary FormWeb elements with their own text, links, pictures and base styles measured at desktop width, in one undo step. Scripts, inline frames and vector graphics stay as small code sections in place; responsive rules are not carried over. A kept script keeps the style rules no converted element uses, and the class rules the script names, so what it builds is styled in Preview and the export. Without parameters it opens a short dialog for the selected element; with node or nodes it converts at once and returns the result sentence.', when: 'Use when the person wants to edit an imported page or a code section visually: click a heading, change its text, restyle it or move it.', run: async (params?: Record) => { const list = Array.isArray(params?.nodes) ? (params!.nodes as unknown[]).filter((id): id is string => typeof id === 'string') : typeof params?.node === 'string' ? [params.node] : null; diff --git a/frontend/src/features/convert/measure.ts b/frontend/src/features/convert/measure.ts index 73a11220..f3715a75 100644 --- a/frontend/src/features/convert/measure.ts +++ b/frontend/src/features/convert/measure.ts @@ -4,7 +4,7 @@ import { t } from '../../i18n'; export interface Source { html: string; css: string; js: string; module: boolean } export interface Planned { id: string; parent: string; tag: string; name: string; text: string; attrs: Record; styles: Record; code?: { enabled: true; html: string; css?: string; js?: string; module?: boolean } } export interface Plan { rootStyles: Record; nodes: Planned[]; fonts: Record | null; outcome: Outcome; rest?: { before: string; after: string; css: string; kept?: string } } -export interface Options { origin: string; keepScript: boolean; fonts: Record; taken: (id: string) => boolean; limit: number; depth: number; seconds: number; scope?: string } +export interface Options { origin: string; keepScript: boolean; fonts: Record; taken: (id: string) => boolean; limit: number; depth: number; seconds: number; scope?: string; siteNames?: Set } const SKIPPED = new Set(['STYLE', 'LINK', 'META', 'BASE', 'TITLE']); @@ -217,7 +217,7 @@ function fillWindow(view: Window, frame: HTMLIFrameElement, root: Record, words: Set, prefix: string): Promise { +async function keepRules(view: Window, doc: Document, css: string, converted: Set, words: Set, tag: string, site: Set): Promise { const Sheet = (view as unknown as { CSSStyleSheet: typeof CSSStyleSheet }).CSSStyleSheet; const sheet = new Sheet(), scratch = new Sheet(); - const none: Kept = { css: '', rules: 0, all: false, over: 0 }; + const prefix = `[data-fw-node="${tag}"]`; + const none: Kept = { css: '', rules: 0, all: false, over: 0, clash: 0 }; let slice = performance.now(); const breathe = async (): Promise => { if (performance.now() - slice > 40) { await new Promise(resolve => setTimeout(resolve, 0)); slice = performance.now(); } }; try { sheet.replaceSync(css); } catch { return none; } @@ -275,12 +279,31 @@ async function keepRules(view: Window, doc: Document, css: string, converted: Se for (const rule of styleRules) { const list = selectorList(rule.selectorText); lists.set(rule, list); - if (all) continue; - await breathe(); - if (performance.now() > deadline) { all = true; continue; } - keeps.set(rule, list.map(selector => !used(selector) || (() => { const classes = subjectClasses(selector); return !!classes.length && classes.every(name => words.has(name)); })())); + const keep: boolean[] = []; + for (const selector of list) { + if (all) break; + await breathe(); + if (performance.now() > deadline) { all = true; break; } + const classes = subjectClasses(selector); + keep.push(!used(selector) || (!!classes.length && classes.every(name => words.has(name)))); + } + if (!all) keeps.set(rule, keep); } if (all) keeps.clear(); + const renamed = new Map(); + for (let i = 0; i < sheet.cssRules.length; i++) { + const rule = sheet.cssRules[i]; + if (kindOf(rule) !== 'CSSKeyframesRule' || !site.has((rule as CSSKeyframesRule).name.toLowerCase())) continue; + const name = (rule as CSSKeyframesRule).name, fresh = `${name}-${tag}`; + (rule as CSSKeyframesRule).name = fresh; + renamed.set(name, fresh); + } + if (renamed.size) for (const rule of styleRules) { + const names = rule.style.getPropertyValue('animation-name'); + if (!names) continue; + const list = names.split(',').map(name => name.trim()); + if (list.some(name => renamed.has(name))) rule.style.setProperty('animation-name', list.map(name => renamed.get(name) || name).join(', '), rule.style.getPropertyPriority('animation-name')); + } const encoder = new TextEncoder(); let bytes = 0, rules = 0, over = 0; @@ -310,7 +333,7 @@ async function keepRules(view: Window, doc: Document, css: string, converted: Se const nested = (rule as CSSStyleRule & { cssRules?: CSSRuleList }).cssRules; const body = `{${style.cssText}${nested ? Array.from(nested).map(inner => inner.cssText).join('') : ''}}`; if (kept.length && !valid(kept.join(', ') + body)) kept = kept.filter(selector => valid(selector + body)); - if (kept.length && style.length) texts.push(kept.join(', ') + body); + if (kept.length && (style.length || nested?.length)) texts.push(kept.join(', ') + body); return texts; }; const emit = async (list: CSSRuleList): Promise => { @@ -325,25 +348,40 @@ async function keepRules(view: Window, doc: Document, css: string, converted: Se if (room(texts.join(''))) { out.push(...texts); rules++; } else over++; } else if (GROUPS.has(kindOf(rule))) { const inner = await emit((rule as CSSGroupingRule).cssRules), head = groupHead(rule); - if (inner.length && head) { out.push(`${head}{${inner.join('\n')}}`); bytes += head.length + 2; } + if (inner.length && head) { out.push(`${head}{${inner.join('\n')}}`); bytes += head.length + 2; if (kindOf(rule) === 'CSSLayerBlockRule') layers.add((rule as CSSLayerBlockRule).name); } } } return out; }; + const layers = new Set(); const body = await emit(sheet.cssRules); if (!body.length) return { ...none, over, all }; const names = new Set(); scriptWords(body.join('\n').toLowerCase(), names, 200000); + const named = (family: string, set: Set): boolean => family.split(' ').every(word => set.has(word)); const head: string[] = []; + let clash = 0; for (let i = 0; i < sheet.cssRules.length; i++) { const rule = sheet.cssRules[i], kind = kindOf(rule); - const wanted = kind === 'CSSLayerStatementRule' || kind === 'CSSPropertyRule' - || (kind === 'CSSKeyframesRule' && names.has((rule as CSSKeyframesRule).name.toLowerCase())) - || (kind === 'CSSFontFaceRule' && families((rule as CSSFontFaceRule).style.getPropertyValue('font-family')).some(family => family.split(' ').every(word => names.has(word)))); - if (!wanted) continue; - if (room(rule.cssText)) head.push(rule.cssText); else over++; + let text = rule.cssText; + if (kind === 'CSSLayerStatementRule') { + const list = Array.from((rule as CSSLayerStatementRule).nameList).filter(name => layers.has(name)); + if (!list.length) continue; + text = `@layer ${list.join(', ')};`; + } else if (kind === 'CSSPropertyRule') { + const name = (rule as CSSPropertyRule).name.toLowerCase(); + if (!names.has(name)) continue; + if (site.has(name)) { clash++; continue; } + } else if (kind === 'CSSKeyframesRule') { + if (!names.has((rule as CSSKeyframesRule).name.toLowerCase())) continue; + } else if (kind === 'CSSFontFaceRule') { + const list = families((rule as CSSFontFaceRule).style.getPropertyValue('font-family')); + if (!list.some(family => named(family, names))) continue; + if (list.some(family => named(family, site))) { clash++; continue; } + } else continue; + if (room(text)) head.push(text); else over++; } - return { css: [...head, ...body].join('\n'), rules, all, over }; + return { css: [...head, ...body].join('\n'), rules, all, over, clash }; } /** The blocks a page too large for one conversion can be converted by, one at a time: its top-level elements. */ @@ -567,12 +605,13 @@ export async function measure(source: Source, options: Options, only?: number): if (hostScript) scriptWords(source.js, words); let keptCss = ''; if ((script?.code || hostScript) && scope) { - const kept = await keepRules(view, original.doc, css, converted, words, `[data-fw-node="${scope}"]`); + const kept = await keepRules(view, original.doc, css, converted, words, scope, options.siteNames || new Set()); if (kept.css && script?.code) script.code.css = kept.css; else keptCss = kept.css; outcome.kept = kept.rules; outcome.keptAll = kept.all ? kept.rules : 0; outcome.keptOver = kept.over; + outcome.keptClash = kept.clash; } outcome.converted = nodes.filter(node => !node.code).length; if (rootStyles['font-family']) families(rootStyles['font-family']).forEach(name => used.add(name)); diff --git a/frontend/src/features/convert/rules.ts b/frontend/src/features/convert/rules.ts index 163869cc..74c4277c 100644 --- a/frontend/src/features/convert/rules.ts +++ b/frontend/src/features/convert/rules.ts @@ -282,15 +282,17 @@ export interface Outcome { scripted: number; left: number; /** Style rules kept for the page's script, those of them kept without checking (time bound), those past the - * bounds, and those dropped because the engine did not take them. */ + * bounds, fonts and registered properties left out because the site uses their names, and rules dropped because + * the section or the site would have been too large. */ kept: number; keptAll: number; keptOver: number; + keptClash: number; keptDropped: number; } export function emptyOutcome(): Outcome { - return { converted: 0, parts: {}, responsive: 0, effects: 0, floats: 0, pictures: 0, refused: 0, scripted: 0, left: 0, kept: 0, keptAll: 0, keptOver: 0, keptDropped: 0 }; + return { converted: 0, parts: {}, responsive: 0, effects: 0, floats: 0, pictures: 0, refused: 0, scripted: 0, left: 0, kept: 0, keptAll: 0, keptOver: 0, keptClash: 0, keptDropped: 0 }; } type Say = (english: string, values?: readonly (string | number)[]) => string; @@ -318,10 +320,11 @@ export function summary(outcome: Outcome, say: Say, count: SayCount): string { if (outcome.scripted) lines.push(count(outcome.scripted, '1 event handler or script link was left out.', '{0} event handlers and script links were left out.', [outcome.scripted])); if (outcome.refused + outcome.left) lines.push(count(outcome.refused + outcome.left, '1 value the engine does not take was left out.', '{0} values the engine does not take were left out.', [outcome.refused + outcome.left])); const checked = outcome.kept - outcome.keptAll; - if (checked > 0) lines.push(count(checked, 'Kept 1 style rule for what the page\'s script builds.', 'Kept {0} style rules for what the page\'s script builds.', [checked])); - if (outcome.keptAll) lines.push(count(outcome.keptAll, 'Kept 1 style rule for what the page\'s script builds without checking whether the converted elements use it: checking took too long, so every rule was kept.', 'Kept {0} style rules for what the page\'s script builds without checking which ones the converted elements use: checking took too long, so every rule was kept.', [outcome.keptAll])); - if (outcome.keptOver) lines.push(count(outcome.keptOver, '1 more style rule was left out: at most {1} rules and {2} KB are kept for a script.', '{0} more style rules were left out: at most {1} rules and {2} KB are kept for a script.', [outcome.keptOver, KEEP_RULES, KEEP_BYTES / 1024])); - if (outcome.keptDropped) lines.push(count(outcome.keptDropped, 'The style rule kept for the page\'s script was left out: the engine did not take it.', 'The {0} style rules kept for the page\'s script were left out: the engine did not take them.', [outcome.keptDropped])); + if (checked > 0) lines.push(count(checked, 'Kept 1 style rule for the content the page\'s script builds.', 'Kept {0} style rules for the content the page\'s script builds.', [checked])); + if (outcome.keptAll) lines.push(count(outcome.keptAll, 'Kept 1 style rule for the content the page\'s script builds without checking whether the converted elements use it: checking took too long, so every rule was kept.', 'Kept {0} style rules for the content the page\'s script builds without checking which ones the converted elements use: checking took too long, so every rule was kept.', [outcome.keptAll])); + if (outcome.keptOver) lines.push(count(outcome.keptOver, '1 more style rule was left out: at most {1} rules and {2} KiB are kept for a script.', '{0} more style rules were left out: at most {1} rules and {2} KiB are kept for a script.', [outcome.keptOver, KEEP_RULES, KEEP_BYTES / 1024])); + if (outcome.keptClash) lines.push(count(outcome.keptClash, '1 font or registered property from the page\'s stylesheet was left out because the site already uses its name.', '{0} fonts or registered properties from the page\'s stylesheet were left out because the site already uses their names.', [outcome.keptClash])); + if (outcome.keptDropped) lines.push(count(outcome.keptDropped, 'The style rule kept for the content the page\'s script builds was left out because the page\'s code would be too large.', 'The {0} style rules kept for the content the page\'s script builds were left out because the page\'s code would be too large.', [outcome.keptDropped])); return lines.join(' '); } @@ -371,6 +374,8 @@ export function selectorList(list: string): string[] { return parts.filter(Boolean); } +/** Pseudo-elements a stylesheet may still write with one colon. */ +const LEGACY = ['before', 'after', 'first-line', 'first-letter']; const IDENT = (c: string): boolean => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c === '-' || c === '_' || c > '\u007f'; /** The subject of one selector (the compound after its last combinator): where it starts, where a pseudo-element @@ -387,6 +392,7 @@ function subjectOf(selector: string): { start: number; end: number; classes: str else if (depth) continue; else if (c === ' ' || c === '>' || c === '+' || c === '~' || c === '\n' || c === '\t') { start = i + 1; end = -1; } else if (c === ':' && selector[i + 1] === ':' && end < 0) { end = i; i++; } + else if (c === ':' && end < 0 && LEGACY.some(name => selector.slice(i + 1, i + 1 + name.length).toLowerCase() === name && !IDENT(selector[i + 1 + name.length] || ' '))) end = i; } if (end < 0) end = selector.length; const classes: string[] = []; diff --git a/frontend/src/features/export-folder.ts b/frontend/src/features/export-folder.ts index d4ae799b..a42ff556 100644 --- a/frontend/src/features/export-folder.ts +++ b/frontend/src/features/export-folder.ts @@ -36,26 +36,38 @@ function read(): ExportChoice { let current = read(); -function hand(choice: ExportChoice): void { +const listeners = new Set<() => void>(); + +function store(choice: ExportChoice): void { + current = choice; + try { + if (choice.mode === 'downloads' && !choice.path) localStorage.removeItem(KEY); + else localStorage.setItem(KEY, JSON.stringify(choice)); + } catch { } + listeners.forEach(listener => listener()); +} + +function settle(sent: ExportChoice, answer: unknown): void { + if (sent !== current || !answer || typeof answer !== 'object') return; + const { mode, folder } = answer as { mode?: unknown; folder?: unknown }; + const shown = typeof folder === 'string' && folder.length <= PATH_MAX ? folder : ''; + if (current.mode === 'folder' && mode !== 'folder') store({ mode: 'downloads', path: '' }); + else if (current.path !== shown) store({ mode: current.mode, path: shown }); +} + +function hand(choice: ExportChoice, forget = false): void { const bridge = core(); if (!bridge) return; try { - void bridge.invoke('set_export_place', { mode: choice.mode, path: choice.path }).catch(() => undefined); + void bridge.invoke('set_export_place', { mode: choice.mode, path: choice.path, forget }).then(answer => settle(choice, answer), () => undefined); } catch { return; } } -const listeners = new Set<() => void>(); - function keep(choice: ExportChoice): void { - current = choice; - try { - if (choice.mode === 'downloads' && !choice.path) localStorage.removeItem(KEY); - else localStorage.setItem(KEY, JSON.stringify(choice)); - } catch { } + store(choice); hand(choice); - listeners.forEach(listener => listener()); } hand(current); @@ -67,7 +79,7 @@ export const exportChoice = (): ExportChoice => current; export function resetExportFolder(): void { try { localStorage.removeItem(KEY); } catch { } current = DEFAULT; - hand(DEFAULT); + hand(DEFAULT, true); } export function forgetAnswer(): void { @@ -80,7 +92,7 @@ export async function beforeDownload(name: string): Promise { try { return (await bridge.invoke('ask_export_place', { name: name.slice(0, NAME_MAX) })) === true; } catch { - return true; + return false; } } @@ -115,7 +127,7 @@ export function exportFolderRow(): HTMLElement { shown.dataset.noI18n = ''; const none = element('span', 'fw-export-path is-empty', 'No folder chosen yet.'); pick.append(choose, shown, none); - const note = element('p', 'micro', 'Export static site, Download project and the other downloads follow this choice. If the chosen folder cannot be used when a file is saved, the file goes to Downloads and the notice says so.'); + const note = element('p', 'micro', 'Every download from the editor follows this choice: Export static site, Download .fweb project, QR codes and picture exports. With Ask each time, each file asks where it goes. If the chosen folder cannot be used when a file is saved, the file goes to Downloads and the notice says so.'); row.append(option('downloads', 'The Downloads folder'), option('folder', 'A folder you choose'), pick, option('ask', 'Ask each time'), note); const paint = (): void => { for (const [mode, radio] of radios) if (radio.checked !== (current.mode === mode)) radio.checked = current.mode === mode; @@ -133,7 +145,7 @@ export function exportFolderRow(): HTMLElement { choosing = true; choose.setAttribute('aria-busy', 'true'); try { - const folder = await bridge.invoke('choose_export_folder', { start: current.path }); + const folder = await bridge.invoke('choose_export_folder'); if (typeof folder !== 'string' || !folder || folder.length > PATH_MAX) return false; keep({ mode: 'folder', path: folder }); return true; diff --git a/frontend/src/features/library/importer.ts b/frontend/src/features/library/importer.ts index f97ca025..ff99f46f 100644 --- a/frontend/src/features/library/importer.ts +++ b/frontend/src/features/library/importer.ts @@ -15,19 +15,21 @@ export function joined(items: string[]): string { export function hostList(hosts: string[]): string { if (hosts.length <= 3) return joined(hosts); const rest = hosts.length - 3; - return rest === 1 ? t('{0} and 1 more host', [hosts.slice(0, 3).join(', ')]) : t('{0} and {1} more hosts', [hosts.slice(0, 3).join(', '), rest]); + const first = hosts.slice(0, 3).reduce((list, host) => t('{0}, {1}', [list, host])); + return rest === 1 ? t('{0} and 1 more host', [first]) : t('{0} and {1} more hosts', [first, rest]); } /** The result sentence for pages brought in as elements without the files they load from the web. */ -export const missingHosts = (hosts: string[]): string => hosts.length ? t('Files from {0} were not brought along, so part of the look may be missing.', [hostList(hosts)]) : ''; +export const missingHosts = (hosts: string[]): string => hosts.length ? t('Files from {0} were not brought along, so part of the look or behaviour may be missing.', [hostList(hosts)]) : ''; /** One page into the open page as a code section, converted to elements when asked; answers with the sentence to show. */ -export async function importSection(hooks: LibraryHooks, body: { html: string; css?: string; name?: string }, bring: Bring, progress: (message: string) => void, made?: (ids: string[]) => void, hosts: string[] = []): Promise { +export async function importSection(hooks: LibraryHooks, body: { html: string; css?: string; name?: string }, bring: Bring, progress: (message: string) => void, made?: (ids: string[]) => void): Promise { const where = hooks.placement(); const result = await libraryMutate('/api/library/import-html', { ...body, parent: where.parent, index: where.index, page: where.page }); let message = result.warnings?.[0] || t('HTML section imported.'); let note = t('HTML section imported.'); let root = result.root; + const hosts = [...new Set((result.outside || []).map(item => item.host))]; if (result.root && bring === 'elements') { progress(t('Converting...')); try { const done = await hooks.convert([result.root]); root = done.root || root; message = note = [done.message, missingHosts(hosts), t('Undo once to get the section back as code, twice to remove it.')].filter(Boolean).join(' '); } diff --git a/frontend/src/features/library/site-import.ts b/frontend/src/features/library/site-import.ts index e886c1f2..f6b8b848 100644 --- a/frontend/src/features/library/site-import.ts +++ b/frontend/src/features/library/site-import.ts @@ -34,7 +34,7 @@ function outsideSentence(page: SitePage): string { : count === 1 ? t('1 script from {0}', [host]) : t('{0} scripts from {1}', [count, host])); const rest = all.slice(4).reduce((sum, group) => sum + group.count, 0) + (page.outsideMore || 0); if (rest) pieces.push(rest === 1 ? t('1 more file') : t('{0} more files', [rest])); - return t('This page takes part of its look from the web: {0}. These files are not brought along.', [joined(pieces)]); + return t('This page loads files from the web: {0}. These files are not brought along.', [joined(pieces)]); } /** Decodes a picked page exactly as the service decodes one inside a zip: UTF-8 (a byte order mark dropped), else Windows-1252 with its five unassigned bytes as U+FFFD. */ function decode(bytes: ArrayBuffer): string { @@ -332,16 +332,16 @@ export class SiteImport { if (!loading.length) return null; const hosts = hostList(hostsOf(loading)); if (section || pages.length === 1) return { - code: t('Kept as code, so the page keeps its own scripts and rules, responsive ones included. The files it loads from the web are not brought along either way.'), - elements: t('As elements, the page arrives without the files it loads from {0}, so part of its look will be missing.', [hosts]) + code: t('Kept as code, so the page keeps its own scripts and style rules, responsive ones included. The files it loads from the web are not brought along either way.'), + elements: t('As elements, the page arrives without the files it loads from {0}, so part of its look or behaviour may be missing.', [hosts]) }; if (loading.length === 1) return { - code: t('Kept as code, because 1 of {0} pages loads files from the web. As code the pages keep their own scripts and rules, responsive ones included; those files are not brought along either way.', [pages.length]), - elements: t('As elements, 1 of {0} pages arrives without the files it loads from {1}, so part of its look will be missing.', [pages.length, hosts]) + code: t('Kept as code, because 1 of {0} pages loads files from the web. As code the pages keep their own scripts and style rules, responsive ones included; those files are not brought along either way.', [pages.length]), + elements: t('As elements, 1 of {0} pages arrives without the files it loads from {1}, so part of its look or behaviour may be missing.', [pages.length, hosts]) }; return { - code: t('Kept as code, because {0} of {1} pages load files from the web. As code the pages keep their own scripts and rules, responsive ones included; those files are not brought along either way.', [loading.length, pages.length]), - elements: t('As elements, {0} of {1} pages arrive without the files they load from {2}, so part of their look will be missing.', [loading.length, pages.length, hosts]) + code: t('Kept as code, because {0} of {1} pages load files from the web. As code the pages keep their own scripts and style rules, responsive ones included; those files are not brought along either way.', [loading.length, pages.length]), + elements: t('As elements, {0} of {1} pages arrive without the files they load from {2}, so part of their look or behaviour may be missing.', [loading.length, pages.length, hosts]) }; } @@ -381,7 +381,7 @@ export class SiteImport { this.working = t('Importing...'); this.setBusy(true); try { - const message = await importSection(this.hooks, { html: page.html, name: page.name.replace(/\.html?$/i, '') }, this.bring.value(), note => this.progress(note), ids => { this.made = ids; }, hostsOf(this.plan?.pages.slice(0, 1) || [])); + const message = await importSection(this.hooks, { html: page.html, name: page.name.replace(/\.html?$/i, '') }, this.bring.value(), note => this.progress(note), ids => { this.made = ids; }); this.done = true; this.say(message, false); } catch (error) { diff --git a/frontend/src/features/library/types.ts b/frontend/src/features/library/types.ts index b41d5eb5..0ee5e6f9 100644 --- a/frontend/src/features/library/types.ts +++ b/frontend/src/features/library/types.ts @@ -19,7 +19,7 @@ export type LibPreset = { id: string; name?: string; description?: string }; export type LibStarter = { id: string; name?: string; description?: string; preset?: string; pages?: { name?: string; slug?: string; sections?: string[] }[] }; export type LibIndex = { categories: string[]; sections: LibSection[]; components: LibComponent[]; presets: LibPreset[]; starters: LibStarter[] }; /** What a mutating library route adds to the batch state. */ -export type LibResult = { root?: string; pages?: string[]; warnings?: string[]; changed?: boolean }; +export type LibResult = { root?: string; pages?: string[]; warnings?: string[]; changed?: boolean; outside?: SiteOutside[]; outsideMore?: number }; /** POST /api/library/import-site/review: what importing a site zip would do, nothing changed yet. */ export type SiteSkip = { file: string; reason: string }; /** A stylesheet or script a page loads from another host: named in the review, never fetched. */ diff --git a/frontend/src/main.ts b/frontend/src/main.ts index c36017b0..50cce785 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -1089,7 +1089,7 @@ const auditMarkers = installAuditMarkers({ status(line); notice.show(line, { error: true, action: { label: 'Show again', run: again } }); }, - rescue: () => inspectorTabButtons.get(activeInspector), status + rescue: () => [inspectorTabButtons.get(activeInspector), auditButton], status }); auditPane.append(auditSummary, auditMarkers.row, auditList); @@ -2013,8 +2013,9 @@ function showIssue(row: HTMLElement): void { notice.show(line, { error: true, action: { label: 'Show again', run: () => { if (row.isConnected && row.dataset.key === key) (row.children[2] as HTMLButtonElement).click(); } } }); } async function auditSite(): Promise { + const asked = state(); const result = await request<{ issues: AuditIssue[]; counts: Record }>('/api/audit'); - auditMarkers.fresh(result); + auditMarkers.fresh(result, asked.site.id, asked.revision); openDialog('audit'); text(auditSummary, result.issues.length === 1 ? '1 issue found. Select an element to resolve it in the inspector.' : result.issues.length ? t('{0} issues found. Select an element to resolve it in the inspector.', [result.issues.length]) : 'No issues found by the built-in audit. Review content and exported pages before release.'); keyed(auditList, result.issues.map((issue, index) => ({ ...issue, key: `${issue.code}-${issue.page || ''}-${issue.node || ''}-${index}` })), issue => issue.key, () => { diff --git a/frontend/src/styles/export-folder.css b/frontend/src/styles/export-folder.css index 5bf60fc7..f8c320f2 100644 --- a/frontend/src/styles/export-folder.css +++ b/frontend/src/styles/export-folder.css @@ -10,3 +10,4 @@ .fw-export-path.is-empty { color: var(--text-muted); font-family: inherit; } .fw-export-path[hidden] { display: none; } button[aria-busy='true'][aria-disabled='true'] { cursor: progress; } +.fw-v-btn[aria-disabled='true'] { opacity: .35; cursor: progress; } diff --git a/frontend/src/ui/downloads.ts b/frontend/src/ui/downloads.ts index 16a7aaa3..9133e0fc 100644 --- a/frontend/src/ui/downloads.ts +++ b/frontend/src/ui/downloads.ts @@ -3,7 +3,7 @@ import type { Notice } from './notice'; import { beforeDownload, exportChoice, forgetAnswer } from '../features/export-folder'; type Core = { invoke(command: string): Promise }; -type Saved = { ok: boolean; file: string; folder: string; unusable: string }; +type Saved = { ok: boolean; file: string; folder: string; unusable: string; reason: string }; export type Words = { desktop: string; placed: string; browser: string }; const core = (): Core | undefined => (window as unknown as { __TAURI__?: { core?: Core } }).__TAURI__?.core; @@ -11,13 +11,13 @@ const waiting = new Map void>(); const LISTEN_MS = 10 * 60 * 1000; window.addEventListener('formweb-download', event => { - const detail = (event as CustomEvent).detail as { url?: unknown; ok?: unknown; file?: unknown; folder?: unknown; unusable?: unknown } | null; + const detail = (event as CustomEvent).detail as { url?: unknown; ok?: unknown; file?: unknown; folder?: unknown; unusable?: unknown; reason?: unknown } | null; if (!detail) return; const key = typeof detail.url === 'string' && waiting.has(detail.url) ? detail.url : waiting.size === 1 ? [...waiting.keys()][0] : ''; const done = waiting.get(key); if (!done) return; waiting.delete(key); - done({ ok: detail.ok === true, file: typeof detail.file === 'string' ? detail.file : '', folder: typeof detail.folder === 'string' ? detail.folder : '', unusable: typeof detail.unusable === 'string' ? detail.unusable.slice(0, 4096) : '' }); + done({ ok: detail.ok === true, file: typeof detail.file === 'string' ? detail.file : '', folder: typeof detail.folder === 'string' ? detail.folder : '', unusable: typeof detail.unusable === 'string' ? detail.unusable.slice(0, 4096) : '', reason: typeof detail.reason === 'string' ? detail.reason.slice(0, 64) : '' }); }); function whenSaved(url: string): Promise { @@ -104,8 +104,9 @@ async function send(file: string, words: Words, notice: Notice, fetch: (started: void (pending as Promise | null)?.then(saved => { if (!saved) return; const reveal = { label: 'Show in folder', run: () => showInFolder(notice) }; - if (!saved.ok) notice.show(saved.folder && !usual ? t('{0} could not be saved to {1}. Check that the folder exists and has free space, then try again.', [file, saved.folder]) : t('{0} could not be saved to your Downloads folder. Check that the folder exists and has free space, then try again.', [file]), { error: true }); - else if (saved.unusable && saved.folder) notice.show(t('The chosen folder {0} could not be used, so {1} was saved to {2}.', [saved.unusable, saved.file || file, saved.folder]), { error: true, action: reveal }); + if (!saved.ok && saved.reason === 'not-asked') notice.show(t('Nothing was saved.')); + else if (!saved.ok) notice.show(saved.folder && !usual ? t('{0} could not be saved to {1}. Check that the folder exists and has free space, then try again.', [file, saved.folder]) : t('{0} could not be saved to your Downloads folder. Check that the folder exists and has free space, then try again.', [file]), { error: true }); + else if (saved.unusable && saved.folder) notice.show(t('The chosen folder {0} is missing or cannot be written, so {1} was saved to {2}.', [saved.unusable, saved.file || file, saved.folder]), { error: true, action: reveal }); else if (saved.folder) notice.show(t(words.placed, [saved.file || file, saved.folder]), { action: reveal }); else notice.show(t(words.desktop, [saved.file || file])); }); diff --git a/frontend/src/vector/exportscreens.ts b/frontend/src/vector/exportscreens.ts index 1100383a..7dd9b011 100644 --- a/frontend/src/vector/exportscreens.ts +++ b/frontend/src/vector/exportscreens.ts @@ -1,4 +1,4 @@ -import { label, labelAttr, t } from '../i18n'; +import { label, labelAttr, t, tn } from '../i18n'; import { element } from '../ui/dom'; import { deliverFile, saveBlob } from '../ui/downloads'; import type { Host } from './host'; @@ -182,7 +182,7 @@ export async function exportScreens(host: Host, svgId: string, options: ExportOp const written: string[] = []; const queue: { blob: Blob; name: string }[] = []; await queueFiles(source, base, options, queue); - for (const item of queue) { if (await download(item.blob, item.name)) written.push(item.name); await pause(200); } + for (const item of queue) { if (!await download(item.blob, item.name)) break; written.push(item.name); await pause(200); } return written; } @@ -206,7 +206,7 @@ export async function exportArtboards(host: Host, items: { id: string; name: str } if (!queue.length) throw new Error(t('No artboards on this page to export.')); const written: string[] = []; - for (const file of queue) { if (await download(file.blob, file.name)) written.push(file.name); await pause(200); } + for (const file of queue) { if (!await download(file.blob, file.name)) break; written.push(file.name); await pause(200); } return written; } @@ -342,14 +342,14 @@ class ExportDialog { private async run(): Promise { const host = this.host; - if (!host || (!this.svg && !this.scope.all.checked)) return; + if (!host || (!this.svg && !this.scope.all.checked) || this.go.getAttribute('aria-disabled') === 'true') return; const formats = FORMATS.map(f => f.id).filter(id => this.formats.get(id)?.checked); const scales = this.scales.filter(s => s.on.checked).map(s => ({ scale: s.scale, suffix: s.suffix.value.trim() })); const raster = formats.some(f => !VECTOR.has(f)); if (!formats.length) { label(this.status, 'Choose at least one format.'); return; } if (raster && !scales.length) { label(this.status, 'Choose at least one scale.'); return; } if (new Set(scales.map(s => safeName(s.suffix))).size !== scales.length) { label(this.status, 'Each scale needs a different suffix.'); return; } - this.go.disabled = true; + this.go.setAttribute('aria-disabled', 'true'); label(this.status, 'Exporting...'); try { const options: ExportOptions = { @@ -357,12 +357,13 @@ class ExportDialog { quality: Number(this.quality.value) || 90, background: this.transparent.checked ? null : this.bg.value, jpgBackground: this.jpgBg.value }; const files = this.scope.all.checked ? await exportArtboards(host, pageArtboards(host), options) : await exportScreens(host, this.svg, options); - label(this.status, 'Exported {0} files.', [files.length]); - host.notify(t('Exported {0} files.', [files.length])); + const said = files.length ? tn(files.length, 'Exported {0} file.', 'Exported {0} files.') : t('Nothing was saved.'); + this.status.textContent = said; + host.notify(said); } catch (error) { if (error instanceof Error) this.status.textContent = error.message; else label(this.status, 'Export failed.'); - } finally { this.go.disabled = false; } + } finally { this.go.removeAttribute('aria-disabled'); } } open(host: Host, svg: string): void { diff --git a/src-tauri/src/downloads.rs b/src-tauri/src/downloads.rs index 8440376c..d49a1079 100644 --- a/src-tauri/src/downloads.rs +++ b/src-tauri/src/downloads.rs @@ -18,6 +18,7 @@ struct Request { destination: PathBuf, placed: bool, unusable: Option, + refused: bool, } #[derive(Clone, Debug, PartialEq)] @@ -38,9 +39,12 @@ static REQUESTED: Mutex> = Mutex::new(Vec::new()); static LAST: Mutex> = Mutex::new(None); static PLACE: Mutex = Mutex::new(Place::Downloads); static ANSWERS: Mutex> = Mutex::new(Vec::new()); +/// The folder the person picked in the shell's folder dialog: `None` until the record file has been read. +static CHOSEN: Mutex>> = Mutex::new(None); +const RECORD: &str = "export-folder.json"; const KEPT: usize = 16; const ANSWERS_KEPT: usize = 4; -const ANSWER_LIFE: Duration = Duration::from_secs(120); +const ANSWER_LIFE: Duration = Duration::from_secs(30 * 60); const PATH_MAX: usize = 4096; const NAME_MAX: usize = 200; const NUMBER_MAX: u32 = 9999; @@ -54,9 +58,9 @@ pub fn on_download(webview: Webview, event: DownloadEvent<'_>) -> requested.remove(0); } let raw = destination.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(); - let name = clean(&unnumbered(&raw)); - let reserved: Vec = requested.iter().map(|request| request.destination.clone()).collect(); - let taken = |path: &Path| path.exists() || reserved.iter().any(|other| other == path); + let name = clean(&web_name(&raw, destination.parent())); + let reserved: Vec = requested.iter().map(|request| folded(&request.destination)).collect(); + let taken = |path: &Path| occupied(path) || reserved.contains(&folded(path)); let place = PLACE.lock().unwrap().clone(); let mut unusable = None; let mut chosen = None; @@ -65,14 +69,18 @@ pub fn on_download(webview: Webview, event: DownloadEvent<'_>) -> true => chosen = Some(free(&folder, &name, taken)), false => unusable = Some(folder), }, - Place::Ask => { - if let Some(path) = take_answer(&name) { - match path.parent().filter(|folder| usable(folder)) { - Some(_) => chosen = Some(path), - None => unusable = path.parent().map(Path::to_path_buf), - } + Place::Ask => match take_answer(&name).or_else(|| take_answer(&clean(&raw))) { + Some(path) => match path.parent().filter(|folder| usable(folder)) { + Some(_) => chosen = Some(path), + None => unusable = path.parent().map(Path::to_path_buf), + }, + None => { + requested.push(Request { url: url.to_string(), destination: destination.clone(), placed: true, unusable: None, refused: true }); + drop(requested); + tell(&webview, serde_json::json!({ "url": url.to_string(), "ok": false, "reason": "not-asked", "file": name, "folder": "", "unusable": "" })); + return false; } - } + }, Place::Downloads => {} } let placed = chosen.is_some() || clean(&raw) != raw; @@ -85,7 +93,7 @@ pub fn on_download(webview: Webview, event: DownloadEvent<'_>) -> } None => {} } - requested.push(Request { url: url.to_string(), destination: destination.clone(), placed, unusable }); + requested.push(Request { url: url.to_string(), destination: destination.clone(), placed, unusable, refused: false }); } DownloadEvent::Finished { url, path, success } => { let url = url.to_string(); @@ -93,6 +101,9 @@ pub fn on_download(webview: Webview, event: DownloadEvent<'_>) -> let mut requested = REQUESTED.lock().unwrap(); requested.iter().position(|request| request.url == url).map(|at| requested.remove(at)) }; + if asked.as_ref().is_some_and(|request| request.refused) { + return true; + } let placed = asked.as_ref().is_some_and(|request| request.placed); let unusable = asked.as_ref().and_then(|request| request.unusable.as_ref()).map(|folder| folder.to_string_lossy().into_owned()).unwrap_or_default(); let saved = path.filter(|path| path.is_file()).or(asked.map(|request| request.destination)); @@ -105,24 +116,48 @@ pub fn on_download(webview: Webview, event: DownloadEvent<'_>) -> *LAST.lock().unwrap() = Some(path.clone()); } } - let editor = webview.url().is_ok_and(|page| page.scheme() == "http" && page.host_str() == Some("127.0.0.1") && page.port() == Some(crate::ENGINE_PORT.load(Ordering::SeqCst))); - if !editor { - return true; - } - let detail = serde_json::json!({ + tell(&webview, serde_json::json!({ "url": url, "ok": success, "file": saved.as_deref().and_then(Path::file_name).map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(), "folder": saved.as_deref().and_then(Path::parent).map(|folder| folder.to_string_lossy().into_owned()).unwrap_or_default(), "unusable": unusable, - }); - let _ = webview.eval(format!("window.dispatchEvent(new CustomEvent('formweb-download', {{ detail: {detail} }}))")); + })); } _ => {} } true } +/// Sends a `formweb-download` event to the page, only when the page is the editor this shell started. +fn tell(webview: &Webview, detail: serde_json::Value) { + let editor = webview.url().is_ok_and(|page| page.scheme() == "http" && page.host_str() == Some("127.0.0.1") && page.port() == Some(crate::ENGINE_PORT.load(Ordering::SeqCst))); + if editor { + let _ = webview.eval(format!("window.dispatchEvent(new CustomEvent('formweb-download', {{ detail: {detail} }}))")); + } +} + +/// A path is taken when anything is there, a dangling link included. +fn occupied(path: &Path) -> bool { + std::fs::symlink_metadata(path).is_ok() +} + +/// A path as Windows and macOS compare names: without regard to case. +fn folded(path: &Path) -> String { + path.to_string_lossy().to_lowercase() +} + +/// The suggested name without the " (n)" the web view added because that name was taken in its own folder; a number +/// that was part of the page's name stays. +fn web_name(raw: &str, folder: Option<&Path>) -> String { + let plain = unnumbered(raw); + if plain != raw && folder.is_some_and(|folder| occupied(&folder.join(&plain))) { + plain + } else { + raw.to_string() + } +} + /// WebKitGTK picks the folder itself, from ~/.config/user-dirs.dirs, and without a Downloads entry there it saves into /// the folder the app was started from. Such a file is moved to ~/Downloads; anything that fails leaves it where it is. #[cfg(target_os = "linux")] @@ -132,7 +167,7 @@ fn settle(webview: &Webview, path: PathBuf) -> PathBuf { if !path.is_file() || path.parent() == Some(folder.as_path()) || std::fs::create_dir_all(&folder).is_err() { return path; } - let target = free(&folder, &unnumbered(name), Path::exists); + let target = free(&folder, &unnumbered(name), occupied); if std::fs::rename(&path, &target).is_ok() || (std::fs::copy(&path, &target).is_ok() && std::fs::remove_file(&path).is_ok()) { target } else { @@ -234,49 +269,112 @@ fn take_answer(name: &str) -> Option { Some(answers.remove(at).path) } -fn place_of(mode: &str, path: &str) -> Place { - match mode { - "folder" if !path.is_empty() && path.len() <= PATH_MAX => Place::Folder(PathBuf::from(path)), - "ask" => Place::Ask, +/// The page names a mode; a folder is only ever the one the person picked in the shell's own dialog (`recorded`), and +/// a path the page sends must name that folder. Anything else means Downloads. +fn place_of(mode: &str, path: &str, recorded: Option<&Path>) -> Place { + match (mode, recorded) { + ("folder", Some(folder)) if path.is_empty() || (path.len() <= PATH_MAX && Path::new(path) == folder) => Place::Folder(folder.to_path_buf()), + ("ask", _) => Place::Ask, _ => Place::Downloads, } } -/// Where the page's downloads go, as the person chose in Preferences. The folder is checked when a file is saved, not here. +/// The recorded folder in the record file's JSON; any error, an empty or relative path, or an oversized file means none. +fn read_record(file: &Path) -> Option { + let bytes = std::fs::read(file).ok().filter(|bytes| bytes.len() <= PATH_MAX * 2 + 64)?; + let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?; + let folder = value.get("folder")?.as_str().filter(|folder| !folder.is_empty() && folder.len() <= PATH_MAX)?; + Some(PathBuf::from(folder)).filter(|folder| folder.is_absolute()) +} + +/// Writes the record through a temporary file and a rename, so a crash leaves the old record or the new one; `None` +/// removes it. +fn write_record(file: &Path, folder: Option<&Path>) -> bool { + let Some(folder) = folder else { return std::fs::remove_file(file).is_ok() || !occupied(file) }; + let Some(parent) = file.parent() else { return false }; + let body = serde_json::json!({ "folder": folder.to_string_lossy() }).to_string(); + let temporary = parent.join(format!("{RECORD}.{}.tmp", std::process::id())); + let written = std::fs::create_dir_all(parent).is_ok() && std::fs::write(&temporary, body).is_ok() && std::fs::rename(&temporary, file).is_ok(); + if !written { + let _ = std::fs::remove_file(&temporary); + } + written +} + +fn record_file(app: &AppHandle) -> Option { + app.path().app_config_dir().ok().map(|folder| folder.join(RECORD)) +} + +fn recorded(app: &AppHandle) -> Option { + let mut chosen = CHOSEN.lock().unwrap(); + chosen.get_or_insert_with(|| record_file(app).and_then(|file| read_record(&file))).clone() +} + +fn record(app: &AppHandle, folder: Option) { + if let Some(file) = record_file(app) { + write_record(&file, folder.as_deref()); + } + *CHOSEN.lock().unwrap() = Some(folder); +} + +/// What the shell will do: the mode it took and the folder it has on record, for the page to show. +#[derive(serde::Serialize)] +pub struct ExportPlace { + mode: &'static str, + folder: String, +} + +/// Where the page's downloads go, as the person chose in Preferences. A folder must be the one recorded by +/// `choose_export_folder`; `forget` drops that record (Reset All Preferences). Waiting dialog answers are dropped. #[tauri::command] -pub fn set_export_place(mode: String, path: String) { - *PLACE.lock().unwrap() = place_of(&mode, &path); +pub fn set_export_place(app: AppHandle, mode: String, path: String, forget: Option) -> ExportPlace { + if forget == Some(true) { + record(&app, None); + } + let folder = recorded(&app); + let place = place_of(&mode, &path, folder.as_deref()); + let mode = match place { + Place::Downloads => "downloads", + Place::Folder(_) => "folder", + Place::Ask => "ask", + }; + *PLACE.lock().unwrap() = place; ANSWERS.lock().unwrap().clear(); + ExportPlace { mode, folder: folder.map(|folder| folder.to_string_lossy().into_owned()).unwrap_or_default() } } -fn start_folder(app: &AppHandle, wanted: &str) -> Option { - let wanted = (!wanted.is_empty() && wanted.len() <= PATH_MAX).then(|| PathBuf::from(wanted)).filter(|path| path.is_absolute() && path.is_dir()); - wanted.or_else(|| app.path().download_dir().ok().filter(|path| path.is_dir())) +fn start_folder(app: &AppHandle) -> Option { + recorded(app).filter(|path| path.is_dir()).or_else(|| app.path().download_dir().ok().filter(|path| path.is_dir())) } -/// The system folder dialog, opened on `start` when it is a folder; the chosen folder, or nothing after Cancel. +/// The system folder dialog. The folder the person picks is recorded by the shell (the only way a folder gets there) +/// and returned for the page to show; nothing after Cancel. #[tauri::command] -pub async fn choose_export_folder(app: AppHandle, start: String) -> Option { +pub async fn choose_export_folder(app: AppHandle) -> Option { let mut dialog = app.dialog().file().set_can_create_directories(true); - if let Some(folder) = start_folder(&app, &start) { + if let Some(folder) = start_folder(&app) { dialog = dialog.set_directory(folder); } if let Some(window) = app.get_webview_window("main") { dialog = dialog.set_parent(&window); } - let folder = dialog.blocking_pick_folder()?.into_path().ok()?; + let folder = dialog.blocking_pick_folder()?.into_path().ok().filter(|folder| folder.is_absolute())?; let text = folder.to_string_lossy().into_owned(); - (text.len() <= PATH_MAX).then_some(text) + if text.len() > PATH_MAX { + return None; + } + record(&app, Some(folder)); + Some(text) } /// The system save dialog for the file the page is about to download, before the download starts. The place is kept -/// for the next download of that name within `ANSWER_LIFE`; false after Cancel, and then nothing is kept. +/// for the next download of that name within `ANSWER_LIFE` and used once; false after Cancel, and then nothing is kept. #[tauri::command] pub async fn ask_export_place(app: AppHandle, name: String) -> bool { let suggested = clean(&name); - let name = clean(&unnumbered(&name)); + let name = suggested.clone(); let mut dialog = app.dialog().file().set_file_name(suggested.clone()).set_can_create_directories(true); - if let Some(folder) = start_folder(&app, "") { + if let Some(folder) = app.path().download_dir().ok().filter(|path| path.is_dir()) { dialog = dialog.set_directory(folder); } if let Some(window) = app.get_webview_window("main") { From db33c0198766a9925f04f9691a3926f04017117f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:00:26 -0500 Subject: [PATCH 06/38] i18n: the 55 new strings of 0.35.0 (audit markers, where exports are saved, the import review's outside files and its reasons, and the sentences about style rules kept after a conversion) in all 23 languages --- frontend/src/i18n/keys.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/cs.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/da.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/de.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/es-MX.ts | 3 ++ frontend/src/i18n/locales/es.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/fi.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/fr.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/hu.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/id.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/it.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/ja.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/ko.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/nb.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/nl.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/pl.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/pt-BR.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/ru.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/sv.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/th.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/tr.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/uk.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/vi.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/zh-CN.ts | 55 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/zh-TW.ts | 55 ++++++++++++++++++++++++++++++ 25 files changed, 1323 insertions(+) diff --git a/frontend/src/i18n/keys.ts b/frontend/src/i18n/keys.ts index ce0062e0..18f88550 100644 --- a/frontend/src/i18n/keys.ts +++ b/frontend/src/i18n/keys.ts @@ -3028,4 +3028,59 @@ export const KEYS: readonly string[] = [ "Not kept: {0} is unchanged.", "The element was changed elsewhere, so the trial was dropped.", "The change was refused.", + "Show audit markers", + "Show audit markers on the page", + "Puts a small marker on each element of this page that has an issue. Click a marker to select the element.", + "1 issue has no element, so it has no marker.", + "{0} issues have no element, so they have no marker.", + "Markers are drawn on the first {0} of {1} elements with issues on this page.", + "1 issue on {0}", + "{0} issues on {1}", + "Issues on {0}", + "The audit could not be run, so the audit markers are hidden.", + "Audit markers are on: each element of this page with an issue shows a marker.", + "Audit markers are off.", + "Where exports are saved", + "The Downloads folder", + "A folder you choose", + "Choose folder...", + "No folder chosen yet.", + "Ask each time", + "Every download from the editor follows this choice: Export static site, Download .fweb project, QR codes and picture exports. With Ask each time, each file asks where it goes. If the chosen folder cannot be used when a file is saved, the file goes to Downloads and the notice says so.", + "In a browser, the browser decides where downloads go.", + "Choose another folder", + "Choose the folder exports are saved to", + "Saving {0}...", + "{0} could not be saved to {1}. Check that the folder exists and has free space, then try again.", + "The chosen folder {0} is missing or cannot be written, so {1} was saved to {2}.", + "Nothing was saved.", + "{0} and {1}", + "{0}, {1}", + "{0} and 1 more host", + "{0} and {1} more hosts", + "Files from {0} were not brought along, so part of the look or behaviour may be missing.", + "1 stylesheet from {0}", + "{0} stylesheets from {1}", + "1 script from {0}", + "{0} scripts from {1}", + "1 more file", + "{0} more files", + "This page loads files from the web: {0}. These files are not brought along.", + "Kept as code, so the page keeps its own scripts and style rules, responsive ones included. The files it loads from the web are not brought along either way.", + "As elements, the page arrives without the files it loads from {0}, so part of its look or behaviour may be missing.", + "Kept as code, because 1 of {0} pages loads files from the web. As code the pages keep their own scripts and style rules, responsive ones included; those files are not brought along either way.", + "As elements, 1 of {0} pages arrives without the files it loads from {1}, so part of its look or behaviour may be missing.", + "Kept as code, because {0} of {1} pages load files from the web. As code the pages keep their own scripts and style rules, responsive ones included; those files are not brought along either way.", + "As elements, {0} of {1} pages arrive without the files they load from {2}, so part of their look or behaviour may be missing.", + "Kept 1 style rule for the content the page's script builds.", + "Kept {0} style rules for the content the page's script builds.", + "Kept 1 style rule for the content the page's script builds without checking whether the converted elements use it: checking took too long, so every rule was kept.", + "Kept {0} style rules for the content the page's script builds without checking which ones the converted elements use: checking took too long, so every rule was kept.", + "1 more style rule was left out: at most {1} rules and {2} KiB are kept for a script.", + "{0} more style rules were left out: at most {1} rules and {2} KiB are kept for a script.", + "The style rule kept for the content the page's script builds was left out because the page's code would be too large.", + "The {0} style rules kept for the content the page's script builds were left out because the page's code would be too large.", + "1 font or registered property from the page's stylesheet was left out because the site already uses its name.", + "{0} fonts or registered properties from the page's stylesheet were left out because the site already uses their names.", + "Exported {0} file.", ]; diff --git a/frontend/src/i18n/locales/cs.ts b/frontend/src/i18n/locales/cs.ts index 9a21ab4d..ad47bf59 100644 --- a/frontend/src/i18n/locales/cs.ts +++ b/frontend/src/i18n/locales/cs.ts @@ -3028,4 +3028,59 @@ export default [ "Neponecháno: {0} zůstává beze změny.", "Prvek byl změněn jinde, proto byla zkouška zrušena.", "Změna byla odmítnuta.", + "Zobrazit značky auditu", + "Zobrazovat značky auditu na stránce", + "Umístí malou značku na každý prvek této stránky, který má problém. Kliknutím na značku prvek vyberete.", + "1 problém nemá prvek, proto nemá značku.", + "Problémy bez prvku: {0}, proto nemají značku.", + "Značky se kreslí na prvních {0} z {1} prvků s problémy na této stránce.", + "1 problém u prvku {0}", + "Problémy u prvku {1}: {0}", + "Problémy u prvku {0}", + "Audit se nepodařilo spustit, proto jsou značky auditu skryté.", + "Značky auditu jsou zapnuté: každý prvek této stránky s problémem ukazuje značku.", + "Značky auditu jsou vypnuté.", + "Kam se ukládají exporty", + "Složka Stažené soubory", + "Složka, kterou zvolíte", + "Zvolit složku...", + "Zatím není zvolena žádná složka.", + "Pokaždé se zeptat", + "Každé stahování z editoru se řídí touto volbou: Exportovat statický web, Stáhnout projekt .fweb, kódy QR a exporty obrázků. S volbou Pokaždé se zeptat se každý soubor zeptá, kam má jít. Pokud zvolenou složku nelze při ukládání souboru použít, soubor se uloží do složky Stažené soubory a oznámení to uvede.", + "V prohlížeči rozhoduje o umístění stažených souborů prohlížeč.", + "Zvolit jinou složku", + "Zvolit složku, do které se ukládají exporty", + "Ukládání {0}...", + "{0} se nepodařilo uložit do {1}. Zkontrolujte, že složka existuje a má volné místo, a zkuste to znovu.", + "Zvolená složka {0} chybí nebo do ní nelze zapisovat, proto bylo {1} uloženo do {2}.", + "Nic nebylo uloženo.", + "{0} a {1}", + "{0}, {1}", + "{0} a 1 další hostitel", + "{0} a další hostitelé: {1}", + "Soubory z {0} nebyly přeneseny, proto může část vzhledu nebo chování chybět.", + "1 styl z {0}", + "styly z {1}: {0}", + "1 skript z {0}", + "skripty z {1}: {0}", + "1 další soubor", + "další soubory: {0}", + "Tato stránka načítá soubory z webu: {0}. Tyto soubory se nepřenášejí.", + "Ponecháno jako kód, takže si stránka zachová vlastní skripty a pravidla stylů, včetně responzivních. Soubory, které načítá z webu, se nepřenesou ani v jednom případě.", + "Jako prvky stránka přijde bez souborů, které načítá z {0}, takže část jejího vzhledu nebo chování může chybět.", + "Ponecháno jako kód, protože 1 z {0} stránek načítá soubory z webu. Jako kód si stránky zachovají vlastní skripty a pravidla stylů, včetně responzivních; tyto soubory se nepřenesou ani v jednom případě.", + "Jako prvky 1 z {0} stránek přijde bez souborů, které načítá z {1}, takže část jejího vzhledu nebo chování může chybět.", + "Ponecháno jako kód, protože stránky, které načítají soubory z webu: {0} z {1}. Jako kód si stránky zachovají vlastní skripty a pravidla stylů, včetně responzivních; tyto soubory se nepřenesou ani v jednom případě.", + "Jako prvky stránky ({0} z {1}) přijdou bez souborů, které načítají z {2}, takže část jejich vzhledu nebo chování může chybět.", + "Ponecháno 1 pravidlo stylu pro obsah, který sestavuje skript stránky.", + "Ponechaná pravidla stylu pro obsah, který sestavuje skript stránky: {0}.", + "Ponecháno 1 pravidlo stylu pro obsah, který sestavuje skript stránky, bez kontroly, zda ho převedené prvky používají: kontrola trvala příliš dlouho, proto byla ponechána všechna pravidla.", + "Ponechaná pravidla stylu pro obsah, který sestavuje skript stránky: {0}, bez kontroly, která z nich převedené prvky používají: kontrola trvala příliš dlouho, proto byla ponechána všechna pravidla.", + "Vynecháno ještě 1 pravidlo stylu: pro skript se ponechá nejvýše {1} pravidel a {2} KiB.", + "Vynechaná další pravidla stylu: {0}. Pro skript se ponechá nejvýše {1} pravidel a {2} KiB.", + "Pravidlo stylu ponechané pro obsah skriptu stránky bylo vynecháno, protože by kód stránky byl příliš velký.", + "Pravidla stylu ponechaná pro obsah skriptu stránky ({0}) byla vynechána, protože by kód stránky byl příliš velký.", + "Vynecháno 1 písmo nebo registrovaná vlastnost ze stylů stránky, protože web už používá jeho název.", + "Vynechaná písma nebo registrované vlastnosti ze stylů stránky: {0}, protože web už používá jejich názvy.", + "Exportováno souborů: {0}.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/da.ts b/frontend/src/i18n/locales/da.ts index 9f35247c..37bb1698 100644 --- a/frontend/src/i18n/locales/da.ts +++ b/frontend/src/i18n/locales/da.ts @@ -3028,4 +3028,59 @@ export default [ "Ikke beholdt: {0} er uændret.", "Elementet blev ændret et andet sted, så afprøvningen blev droppet.", "Ændringen blev afvist.", + "Vis auditmarkører", + "Vis auditmarkører på siden", + "Sætter en lille markør på hvert element på denne side, der har et problem. Klik på en markør for at vælge elementet.", + "1 problem har intet element, så det har ingen markør.", + "{0} problemer har intet element, så de har ingen markør.", + "Markører tegnes på de første {0} af {1} elementer med problemer på denne side.", + "1 problem på {0}", + "{0} problemer på {1}", + "Problemer på {0}", + "Audit kunne ikke køres, så auditmarkørerne er skjult.", + "Auditmarkører er slået til: hvert element på denne side med et problem viser en markør.", + "Auditmarkører er slået fra.", + "Hvor eksporter gemmes", + "Mappen Overførsler", + "En mappe, du vælger", + "Vælg mappe...", + "Der er ikke valgt nogen mappe endnu.", + "Spørg hver gang", + "Alle downloads fra editoren følger dette valg: Eksportér statisk site, Download .fweb-projekt, QR-koder og billedeksporter. Med Spørg hver gang spørger hver fil, hvor den skal hen. Hvis den valgte mappe ikke kan bruges, når en fil gemmes, havner filen i Overførsler, og meddelelsen siger det.", + "I en browser bestemmer browseren, hvor downloads havner.", + "Vælg en anden mappe", + "Vælg den mappe, eksporter gemmes i", + "Gemmer {0}...", + "{0} kunne ikke gemmes i {1}. Kontrollér, at mappen findes og har ledig plads, og prøv igen.", + "Den valgte mappe {0} mangler eller kan ikke skrives til, så {1} blev gemt i {2}.", + "Intet blev gemt.", + "{0} og {1}", + "{0}, {1}", + "{0} og 1 vært mere", + "{0} og {1} værter mere", + "Filer fra {0} kom ikke med, så en del af udseendet eller adfærden kan mangle.", + "1 stylesheet fra {0}", + "{0} stylesheets fra {1}", + "1 script fra {0}", + "{0} scripts fra {1}", + "1 fil mere", + "{0} filer mere", + "Denne side henter filer fra nettet: {0}. Disse filer kommer ikke med.", + "Beholdt som kode, så siden beholder sine egne scripts og stilregler, også de responsive. Filerne, den henter fra nettet, kommer ikke med i nogen af tilfældene.", + "Som elementer kommer siden uden de filer, den henter fra {0}, så en del af dens udseende eller adfærd kan mangle.", + "Beholdt som kode, fordi 1 af {0} sider henter filer fra nettet. Som kode beholder siderne deres egne scripts og stilregler, også de responsive; de filer kommer ikke med i nogen af tilfældene.", + "Som elementer kommer 1 af {0} sider uden de filer, den henter fra {1}, så en del af dens udseende eller adfærd kan mangle.", + "Beholdt som kode, fordi {0} af {1} sider henter filer fra nettet. Som kode beholder siderne deres egne scripts og stilregler, også de responsive; de filer kommer ikke med i nogen af tilfældene.", + "Som elementer kommer {0} af {1} sider uden de filer, de henter fra {2}, så en del af deres udseende eller adfærd kan mangle.", + "Beholdt 1 stilregel til det indhold, sidens script bygger.", + "Beholdt {0} stilregler til det indhold, sidens script bygger.", + "Beholdt 1 stilregel til det indhold, sidens script bygger, uden at kontrollere, om de konverterede elementer bruger den: kontrollen tog for lang tid, så alle regler blev beholdt.", + "Beholdt {0} stilregler til det indhold, sidens script bygger, uden at kontrollere, hvilke af dem de konverterede elementer bruger: kontrollen tog for lang tid, så alle regler blev beholdt.", + "1 stilregel mere blev udeladt: højst {1} regler og {2} KiB beholdes til et script.", + "{0} stilregler mere blev udeladt: højst {1} regler og {2} KiB beholdes til et script.", + "Stilreglen, der var beholdt til det indhold, sidens script bygger, blev udeladt, fordi sidens kode ville blive for stor.", + "De {0} stilregler, der var beholdt til det indhold, sidens script bygger, blev udeladt, fordi sidens kode ville blive for stor.", + "1 skrifttype eller registreret egenskab fra sidens stylesheet blev udeladt, fordi webstedet allerede bruger navnet.", + "{0} skrifttyper eller registrerede egenskaber fra sidens stylesheet blev udeladt, fordi webstedet allerede bruger navnene.", + "{0} fil eksporteret.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/de.ts b/frontend/src/i18n/locales/de.ts index 4188c25b..b85d971f 100644 --- a/frontend/src/i18n/locales/de.ts +++ b/frontend/src/i18n/locales/de.ts @@ -3028,4 +3028,59 @@ export default [ "Nicht behalten: {0} ist unverändert.", "Das Element wurde an anderer Stelle geändert, daher wurde der Versuch verworfen.", "Die Änderung wurde abgelehnt.", + "Audit-Markierungen anzeigen", + "Audit-Markierungen auf der Seite anzeigen", + "Setzt eine kleine Markierung auf jedes Element dieser Seite, das ein Problem hat. Klicke auf eine Markierung, um das Element auszuwählen.", + "1 Problem hat kein Element und daher keine Markierung.", + "{0} Probleme haben kein Element und daher keine Markierung.", + "Markierungen werden an den ersten {0} von {1} Elementen mit Problemen auf dieser Seite gezeichnet.", + "1 Problem an {0}", + "{0} Probleme an {1}", + "Probleme an {0}", + "Das Audit konnte nicht ausgeführt werden, daher sind die Audit-Markierungen ausgeblendet.", + "Audit-Markierungen sind an: Jedes Element dieser Seite mit einem Problem zeigt eine Markierung.", + "Audit-Markierungen sind aus.", + "Speicherort für Exporte", + "Der Downloads-Ordner", + "Ein Ordner deiner Wahl", + "Ordner wählen...", + "Noch kein Ordner gewählt.", + "Jedes Mal fragen", + "Jeder Download aus dem Editor folgt dieser Wahl: Statische Website exportieren, .fweb-Projekt herunterladen, QR-Codes und Bildexporte. Mit Jedes Mal fragen fragt jede Datei, wohin sie soll. Kann der gewählte Ordner beim Speichern einer Datei nicht verwendet werden, landet die Datei in Downloads und der Hinweis sagt es.", + "In einem Browser entscheidet der Browser, wohin Downloads gehen.", + "Anderen Ordner wählen", + "Den Ordner wählen, in dem Exporte gespeichert werden", + "{0} wird gespeichert...", + "{0} konnte nicht unter {1} gespeichert werden. Prüfe, ob der Ordner existiert und genug freien Speicher hat, und versuche es dann erneut.", + "Der gewählte Ordner {0} fehlt oder ist nicht beschreibbar, daher wurde {1} unter {2} gespeichert.", + "Es wurde nichts gespeichert.", + "{0} und {1}", + "{0}, {1}", + "{0} und 1 weiterer Host", + "{0} und {1} weitere Hosts", + "Dateien von {0} wurden nicht mitgenommen, daher kann ein Teil des Aussehens oder Verhaltens fehlen.", + "1 Stylesheet von {0}", + "{0} Stylesheets von {1}", + "1 Skript von {0}", + "{0} Skripte von {1}", + "1 weitere Datei", + "{0} weitere Dateien", + "Diese Seite lädt Dateien aus dem Web: {0}. Diese Dateien werden nicht mitgenommen.", + "Als Code behalten: So behält die Seite ihre eigenen Skripte und Stilregeln, auch die responsiven. Die Dateien, die sie aus dem Web lädt, werden in keinem Fall mitgenommen.", + "Als Elemente kommt die Seite ohne die Dateien an, die sie von {0} lädt, daher kann ein Teil ihres Aussehens oder Verhaltens fehlen.", + "Als Code behalten, weil 1 von {0} Seiten Dateien aus dem Web lädt. Als Code behalten die Seiten ihre eigenen Skripte und Stilregeln, auch die responsiven; diese Dateien werden in keinem Fall mitgenommen.", + "Als Elemente kommt 1 von {0} Seiten ohne die Dateien an, die sie von {1} lädt, daher kann ein Teil ihres Aussehens oder Verhaltens fehlen.", + "Als Code behalten, weil {0} von {1} Seiten Dateien aus dem Web laden. Als Code behalten die Seiten ihre eigenen Skripte und Stilregeln, auch die responsiven; diese Dateien werden in keinem Fall mitgenommen.", + "Als Elemente kommen {0} von {1} Seiten ohne die Dateien an, die sie von {2} laden, daher kann ein Teil ihres Aussehens oder Verhaltens fehlen.", + "Für den Inhalt, den das Skript der Seite aufbaut, wurde 1 Stilregel behalten.", + "Für den Inhalt, den das Skript der Seite aufbaut, wurden {0} Stilregeln behalten.", + "Für den Inhalt, den das Skript der Seite aufbaut, wurde 1 Stilregel behalten, ohne zu prüfen, ob die umgewandelten Elemente sie verwenden: Die Prüfung dauerte zu lange, daher wurden alle Regeln behalten.", + "Für den Inhalt, den das Skript der Seite aufbaut, wurden {0} Stilregeln behalten, ohne zu prüfen, welche davon die umgewandelten Elemente verwenden: Die Prüfung dauerte zu lange, daher wurden alle Regeln behalten.", + "1 weitere Stilregel wurde weggelassen: Für ein Skript werden höchstens {1} Regeln und {2} KiB behalten.", + "{0} weitere Stilregeln wurden weggelassen: Für ein Skript werden höchstens {1} Regeln und {2} KiB behalten.", + "Die für den Inhalt des Seitenskripts behaltene Stilregel wurde weggelassen, weil der Code der Seite zu groß würde.", + "Die {0} für den Inhalt des Seitenskripts behaltenen Stilregeln wurden weggelassen, weil der Code der Seite zu groß würde.", + "1 Schrift oder registrierte Eigenschaft aus dem Stylesheet der Seite wurde weggelassen, weil die Website ihren Namen schon verwendet.", + "{0} Schriften oder registrierte Eigenschaften aus dem Stylesheet der Seite wurden weggelassen, weil die Website ihre Namen schon verwendet.", + "{0} Datei exportiert.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/es-MX.ts b/frontend/src/i18n/locales/es-MX.ts index 10014817..334deb4e 100644 --- a/frontend/src/i18n/locales/es-MX.ts +++ b/frontend/src/i18n/locales/es-MX.ts @@ -92,4 +92,7 @@ export default { "Click to add a stop": "Haz clic para agregar una parada", "A clicked choice shows on the page and is written when you press Keep. With this off, choices are written at once.": "Una opción en la que haces clic se muestra en la página y se guarda cuando presionas Conservar. Con esto desactivado, las opciones se guardan al instante.", "A clicked choice now shows on the page until you press Keep.": "Una opción en la que haces clic se muestra ahora en la página hasta que presiones Conservar.", + "{0} could not be saved to {1}. Check that the folder exists and has free space, then try again.": "No se pudo guardar {0} en {1}. Verifica que la carpeta exista y tenga espacio libre, y vuelve a intentarlo.", + "Kept 1 style rule for the content the page's script builds without checking whether the converted elements use it: checking took too long, so every rule was kept.": "Se conservó 1 regla de estilo para el contenido que construye el script de la página sin verificar si los elementos convertidos la usan: la verificación tardaba demasiado, así que se conservaron todas las reglas.", + "Kept {0} style rules for the content the page's script builds without checking which ones the converted elements use: checking took too long, so every rule was kept.": "Se conservaron {0} reglas de estilo para el contenido que construye el script de la página sin verificar cuáles usan los elementos convertidos: la verificación tardaba demasiado, así que se conservaron todas las reglas.", } as Record; diff --git a/frontend/src/i18n/locales/es.ts b/frontend/src/i18n/locales/es.ts index bbe49a51..306082c1 100644 --- a/frontend/src/i18n/locales/es.ts +++ b/frontend/src/i18n/locales/es.ts @@ -3028,4 +3028,59 @@ export default [ "No se conservó: {0} no cambia.", "El elemento se cambió en otro lugar, así que la prueba se descartó.", "Se rechazó el cambio.", + "Mostrar marcadores de auditoría", + "Mostrar marcadores de auditoría en la página", + "Pone un pequeño marcador en cada elemento de esta página que tiene un problema. Haz clic en un marcador para seleccionar el elemento.", + "1 problema no tiene elemento, así que no tiene marcador.", + "{0} problemas no tienen elemento, así que no tienen marcador.", + "Los marcadores se dibujan en los primeros {0} de {1} elementos con problemas de esta página.", + "1 problema en {0}", + "{0} problemas en {1}", + "Problemas en {0}", + "No se pudo ejecutar la auditoría, así que los marcadores de auditoría están ocultos.", + "Marcadores de auditoría activados: cada elemento de esta página con un problema muestra un marcador.", + "Marcadores de auditoría desactivados.", + "Dónde se guardan las exportaciones", + "La carpeta Descargas", + "Una carpeta que elijas", + "Elegir carpeta...", + "Aún no se eligió ninguna carpeta.", + "Preguntar cada vez", + "Todas las descargas del editor siguen esta elección: Exportar sitio estático, Descargar proyecto .fweb, los códigos QR y las exportaciones de imágenes. Con Preguntar cada vez, cada archivo pregunta adónde va. Si la carpeta elegida no se puede usar al guardar un archivo, el archivo va a Descargas y el aviso lo indica.", + "En un navegador, el navegador decide adónde van las descargas.", + "Elegir otra carpeta", + "Elegir la carpeta donde se guardan las exportaciones", + "Guardando {0}...", + "No se pudo guardar {0} en {1}. Comprueba que la carpeta existe y tiene espacio libre, y vuelve a intentarlo.", + "La carpeta elegida {0} no existe o no se puede escribir en ella, así que {1} se guardó en {2}.", + "No se guardó nada.", + "{0} y {1}", + "{0}, {1}", + "{0} y 1 host más", + "{0} y {1} hosts más", + "Los archivos de {0} no se trajeron, así que puede faltar parte del aspecto o del comportamiento.", + "1 hoja de estilo de {0}", + "{0} hojas de estilo de {1}", + "1 script de {0}", + "{0} scripts de {1}", + "1 archivo más", + "{0} archivos más", + "Esta página carga archivos de la web: {0}. Estos archivos no se traen.", + "Se mantiene como código, así que la página conserva sus propios scripts y reglas de estilo, incluidas las adaptables. Los archivos que carga de la web no se traen en ningún caso.", + "Como elementos, la página llega sin los archivos que carga de {0}, así que puede faltar parte de su aspecto o de su comportamiento.", + "Se mantiene como código porque 1 de {0} páginas carga archivos de la web. Como código, las páginas conservan sus propios scripts y reglas de estilo, incluidas las adaptables; esos archivos no se traen en ningún caso.", + "Como elementos, 1 de {0} páginas llega sin los archivos que carga de {1}, así que puede faltar parte de su aspecto o de su comportamiento.", + "Se mantiene como código porque {0} de {1} páginas cargan archivos de la web. Como código, las páginas conservan sus propios scripts y reglas de estilo, incluidas las adaptables; esos archivos no se traen en ningún caso.", + "Como elementos, {0} de {1} páginas llegan sin los archivos que cargan de {2}, así que puede faltar parte de su aspecto o de su comportamiento.", + "Se conservó 1 regla de estilo para el contenido que construye el script de la página.", + "Se conservaron {0} reglas de estilo para el contenido que construye el script de la página.", + "Se conservó 1 regla de estilo para el contenido que construye el script de la página sin comprobar si los elementos convertidos la usan: la comprobación tardaba demasiado, así que se conservaron todas las reglas.", + "Se conservaron {0} reglas de estilo para el contenido que construye el script de la página sin comprobar cuáles usan los elementos convertidos: la comprobación tardaba demasiado, así que se conservaron todas las reglas.", + "Se omitió 1 regla de estilo más: como máximo se conservan {1} reglas y {2} KiB para un script.", + "Se omitieron {0} reglas de estilo más: como máximo se conservan {1} reglas y {2} KiB para un script.", + "Se omitió la regla de estilo conservada para el contenido que construye el script de la página, porque el código de la página sería demasiado grande.", + "Se omitieron las {0} reglas de estilo conservadas para el contenido que construye el script de la página, porque el código de la página sería demasiado grande.", + "Se omitió 1 fuente o propiedad registrada de la hoja de estilo de la página porque el sitio ya usa su nombre.", + "Se omitieron {0} fuentes o propiedades registradas de la hoja de estilo de la página porque el sitio ya usa sus nombres.", + "Se exportó {0} archivo.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/fi.ts b/frontend/src/i18n/locales/fi.ts index d3b611f7..aa276fc5 100644 --- a/frontend/src/i18n/locales/fi.ts +++ b/frontend/src/i18n/locales/fi.ts @@ -3028,4 +3028,59 @@ export default [ "Ei säilytetty: {0} on ennallaan.", "Elementtiä muutettiin muualla, joten kokeilu hylättiin.", "Muutos hylättiin.", + "Näytä auditointimerkit", + "Näytä auditointimerkit sivulla", + "Lisää pienen merkin jokaiseen tämän sivun elementtiin, jossa on ongelma. Valitse elementti napsauttamalla merkkiä.", + "1 ongelmalla ei ole elementtiä, joten sillä ei ole merkkiä.", + "Ongelmia ilman elementtiä: {0}, joten niillä ei ole merkkiä.", + "Merkit piirretään tämän sivun {1} ongelmallisesta elementistä ensimmäisiin {0}.", + "1 ongelma: {0}", + "{0} ongelmaa: {1}", + "Ongelmat: {0}", + "Auditointia ei voitu suorittaa, joten auditointimerkit on piilotettu.", + "Auditointimerkit ovat päällä: jokaisessa tämän sivun ongelmallisessa elementissä näkyy merkki.", + "Auditointimerkit ovat pois päältä.", + "Mihin viennit tallennetaan", + "Lataukset-kansio", + "Valitsemasi kansio", + "Valitse kansio...", + "Kansiota ei ole vielä valittu.", + "Kysy joka kerta", + "Kaikki editorin lataukset noudattavat tätä valintaa: Vie staattinen sivusto, Lataa .fweb-projekti, QR-koodit ja kuvien viennit. Kun valintana on Kysy joka kerta, jokainen tiedosto kysyy, minne se menee. Jos valittua kansiota ei voi käyttää tiedostoa tallennettaessa, tiedosto menee Lataukset-kansioon ja ilmoitus kertoo siitä.", + "Selaimessa selain päättää, minne lataukset menevät.", + "Valitse toinen kansio", + "Valitse kansio, johon viennit tallennetaan", + "Tallennetaan {0}...", + "Tiedostoa {0} ei voitu tallentaa kohteeseen {1}. Tarkista, että kansio on olemassa ja siinä on vapaata tilaa, ja yritä sitten uudelleen.", + "Valittua kansiota {0} ei ole tai siihen ei voi kirjoittaa, joten {1} tallennettiin kohteeseen {2}.", + "Mitään ei tallennettu.", + "{0} ja {1}", + "{0}, {1}", + "{0} ja 1 muu palvelin", + "{0} ja {1} muuta palvelinta", + "Tiedostoja palvelimelta {0} ei tuotu mukana, joten osa ulkoasusta tai toiminnasta voi puuttua.", + "1 tyylitiedosto palvelimelta {0}", + "{0} tyylitiedostoa palvelimelta {1}", + "1 skripti palvelimelta {0}", + "{0} skriptiä palvelimelta {1}", + "1 muu tiedosto", + "{0} muuta tiedostoa", + "Tämä sivu lataa tiedostoja verkosta: {0}. Näitä tiedostoja ei tuoda mukana.", + "Säilytetään koodina, joten sivu pitää omat skriptinsä ja tyylisääntönsä, myös responsiiviset. Tiedostoja, joita se lataa verkosta, ei tuoda kummassakaan tapauksessa.", + "Elementteinä sivu tulee ilman tiedostoja, joita se lataa palvelimelta {0}, joten osa sen ulkoasusta tai toiminnasta voi puuttua.", + "Säilytetään koodina, koska 1 sivu {0} sivusta lataa tiedostoja verkosta. Koodina sivut pitävät omat skriptinsä ja tyylisääntönsä, myös responsiiviset; niitä tiedostoja ei tuoda kummassakaan tapauksessa.", + "Elementteinä 1 sivu {0} sivusta tulee ilman tiedostoja, joita se lataa palvelimelta {1}, joten osa sen ulkoasusta tai toiminnasta voi puuttua.", + "Säilytetään koodina, koska {0} sivua {1} sivusta lataa tiedostoja verkosta. Koodina sivut pitävät omat skriptinsä ja tyylisääntönsä, myös responsiiviset; niitä tiedostoja ei tuoda kummassakaan tapauksessa.", + "Elementteinä {0} sivua {1} sivusta tulee ilman tiedostoja, joita ne lataavat palvelimelta {2}, joten osa niiden ulkoasusta tai toiminnasta voi puuttua.", + "Säilytettiin 1 tyylisääntö sisällölle, jonka sivun skripti rakentaa.", + "Säilytettiin {0} tyylisääntöä sisällölle, jonka sivun skripti rakentaa.", + "Säilytettiin 1 tyylisääntö sisällölle, jonka sivun skripti rakentaa, tarkistamatta, käyttävätkö muunnetut elementit sitä: tarkistus kesti liian kauan, joten kaikki säännöt säilytettiin.", + "Säilytettiin {0} tyylisääntöä sisällölle, jonka sivun skripti rakentaa, tarkistamatta, mitä niistä muunnetut elementit käyttävät: tarkistus kesti liian kauan, joten kaikki säännöt säilytettiin.", + "1 tyylisääntö lisää jätettiin pois: skriptille säilytetään enintään {1} sääntöä ja {2} KiB.", + "{0} tyylisääntöä lisää jätettiin pois: skriptille säilytetään enintään {1} sääntöä ja {2} KiB.", + "Sivun skriptin rakentamalle sisällölle säilytetty tyylisääntö jätettiin pois, koska sivun koodista tulisi liian suuri.", + "Sivun skriptin rakentamalle sisällölle säilytetyt {0} tyylisääntöä jätettiin pois, koska sivun koodista tulisi liian suuri.", + "1 fontti tai rekisteröity ominaisuus jätettiin pois sivun tyylitiedostosta, koska sivusto käyttää jo sen nimeä.", + "{0} fonttia tai rekisteröityä ominaisuutta jätettiin pois sivun tyylitiedostosta, koska sivusto käyttää jo niiden nimiä.", + "Viety {0} tiedosto.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/fr.ts b/frontend/src/i18n/locales/fr.ts index 0f156253..18b405ec 100644 --- a/frontend/src/i18n/locales/fr.ts +++ b/frontend/src/i18n/locales/fr.ts @@ -3028,4 +3028,59 @@ export default [ "Non gardé : {0} est inchangé.", "L’élément a été modifié ailleurs, l’essai a donc été abandonné.", "La modification a été refusée.", + "Afficher les marqueurs d’audit", + "Afficher les marqueurs d’audit sur la page", + "Place un petit marqueur sur chaque élément de cette page qui a un problème. Cliquez sur un marqueur pour sélectionner l’élément.", + "1 problème n’a pas d’élément, il n’a donc pas de marqueur.", + "{0} problèmes n’ont pas d’élément, ils n’ont donc pas de marqueur.", + "Les marqueurs sont dessinés sur les {0} premiers des {1} éléments ayant des problèmes sur cette page.", + "1 problème sur {0}", + "{0} problèmes sur {1}", + "Problèmes sur {0}", + "L’audit n’a pas pu être lancé, les marqueurs d’audit sont donc masqués.", + "Marqueurs d’audit activés : chaque élément de cette page qui a un problème affiche un marqueur.", + "Marqueurs d’audit désactivés.", + "Emplacement des exportations", + "Le dossier Téléchargements", + "Un dossier de votre choix", + "Choisir un dossier...", + "Aucun dossier choisi pour l’instant.", + "Demander à chaque fois", + "Tous les téléchargements de l’éditeur suivent ce choix : Exporter le site statique, Télécharger le projet .fweb, les codes QR et les exportations d’images. Avec Demander à chaque fois, chaque fichier demande où il va. Si le dossier choisi ne peut pas être utilisé au moment d’enregistrer un fichier, le fichier va dans Téléchargements et la notification l’indique.", + "Dans un navigateur, c’est le navigateur qui décide où vont les téléchargements.", + "Choisir un autre dossier", + "Choisir le dossier où les exportations sont enregistrées", + "Enregistrement de {0}...", + "Impossible d’enregistrer {0} dans {1}. Vérifiez que le dossier existe et dispose d’espace libre, puis réessayez.", + "Le dossier choisi {0} est introuvable ou n’est pas accessible en écriture, {1} a donc été enregistré dans {2}.", + "Rien n’a été enregistré.", + "{0} et {1}", + "{0}, {1}", + "{0} et 1 autre hôte", + "{0} et {1} autres hôtes", + "Les fichiers de {0} n’ont pas été importés, une partie de l’apparence ou du comportement peut donc manquer.", + "1 feuille de style de {0}", + "{0} feuilles de style de {1}", + "1 script de {0}", + "{0} scripts de {1}", + "1 autre fichier", + "{0} autres fichiers", + "Cette page charge des fichiers depuis le web : {0}. Ces fichiers ne sont pas importés.", + "Gardée en code : la page conserve ainsi ses propres scripts et règles de style, y compris les règles adaptatives. Les fichiers qu’elle charge depuis le web ne sont importés dans aucun cas.", + "En éléments, la page arrive sans les fichiers qu’elle charge depuis {0}, une partie de son apparence ou de son comportement peut donc manquer.", + "Gardées en code, car 1 page sur {0} charge des fichiers depuis le web. En code, les pages conservent leurs propres scripts et règles de style, y compris les règles adaptatives ; ces fichiers ne sont importés dans aucun cas.", + "En éléments, 1 page sur {0} arrive sans les fichiers qu’elle charge depuis {1}, une partie de son apparence ou de son comportement peut donc manquer.", + "Gardées en code, car {0} pages sur {1} chargent des fichiers depuis le web. En code, les pages conservent leurs propres scripts et règles de style, y compris les règles adaptatives ; ces fichiers ne sont importés dans aucun cas.", + "En éléments, {0} pages sur {1} arrivent sans les fichiers qu’elles chargent depuis {2}, une partie de leur apparence ou de leur comportement peut donc manquer.", + "1 règle de style gardée pour le contenu que construit le script de la page.", + "{0} règles de style gardées pour le contenu que construit le script de la page.", + "1 règle de style gardée pour le contenu que construit le script de la page, sans vérifier si les éléments convertis l’utilisent : la vérification prenait trop de temps, toutes les règles ont donc été gardées.", + "{0} règles de style gardées pour le contenu que construit le script de la page, sans vérifier lesquelles les éléments convertis utilisent : la vérification prenait trop de temps, toutes les règles ont donc été gardées.", + "1 règle de style de plus a été laissée de côté : au plus {1} règles et {2} Kio sont gardés pour un script.", + "{0} règles de style de plus ont été laissées de côté : au plus {1} règles et {2} Kio sont gardés pour un script.", + "La règle de style gardée pour le contenu que construit le script de la page a été laissée de côté, car le code de la page serait trop volumineux.", + "Les {0} règles de style gardées pour le contenu que construit le script de la page ont été laissées de côté, car le code de la page serait trop volumineux.", + "1 police ou propriété enregistrée de la feuille de style de la page a été laissée de côté, car le site utilise déjà son nom.", + "{0} polices ou propriétés enregistrées de la feuille de style de la page ont été laissées de côté, car le site utilise déjà leurs noms.", + "{0} fichier exporté.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/hu.ts b/frontend/src/i18n/locales/hu.ts index c5a2455f..550c7716 100644 --- a/frontend/src/i18n/locales/hu.ts +++ b/frontend/src/i18n/locales/hu.ts @@ -3028,4 +3028,59 @@ export default [ "Nincs megtartva: {0} változatlan.", "Az elemet máshol módosították, ezért a kipróbálás elvetve.", "A módosítást elutasították.", + "Auditjelölők megjelenítése", + "Auditjelölők megjelenítése az oldalon", + "Kis jelölőt tesz az oldal minden olyan elemére, amelynek problémája van. Kattints egy jelölőre az elem kijelöléséhez.", + "1 problémához nem tartozik elem, ezért nincs jelölője.", + "{0} problémához nem tartozik elem, ezért nincs jelölőjük.", + "A jelölők az oldal {1} problémás eleméből az első {0} elemen jelennek meg.", + "1 probléma itt: {0}", + "{0} probléma itt: {1}", + "Problémák itt: {0}", + "Az auditot nem sikerült lefuttatni, ezért az auditjelölők rejtve vannak.", + "Az auditjelölők be vannak kapcsolva: az oldal minden problémás eleme jelölőt mutat.", + "Az auditjelölők ki vannak kapcsolva.", + "Az exportok mentési helye", + "A Letöltések mappa", + "Egy általad választott mappa", + "Mappa kiválasztása...", + "Még nincs kiválasztott mappa.", + "Kérdezzen rá minden alkalommal", + "A szerkesztő minden letöltése ezt a választást követi: Statikus webhely exportálása, .fweb projekt letöltése, QR-kódok és képexportok. A Kérdezzen rá minden alkalommal beállításnál minden fájl megkérdezi, hová kerüljön. Ha a választott mappa a fájl mentésekor nem használható, a fájl a Letöltések mappába kerül, és az értesítés jelzi ezt.", + "Böngészőben a böngésző dönti el, hová kerülnek a letöltések.", + "Másik mappa kiválasztása", + "Az exportok mentési mappájának kiválasztása", + "{0} mentése...", + "{0} nem menthető ide: {1}. Ellenőrizd, hogy a mappa létezik-e és van-e rajta szabad hely, majd próbáld újra.", + "A választott mappa ({0}) hiányzik vagy nem írható, ezért a(z) {1} ide került: {2}.", + "Semmi sem lett mentve.", + "{0} és {1}", + "{0}, {1}", + "{0} és még 1 kiszolgáló", + "{0} és még {1} kiszolgáló", + "A következő helyekről származó fájlok nem kerültek át: {0}, ezért a megjelenés vagy a működés egy része hiányozhat.", + "1 stíluslap innen: {0}", + "{0} stíluslap innen: {1}", + "1 szkript innen: {0}", + "{0} szkript innen: {1}", + "még 1 fájl", + "még {0} fájl", + "Ez az oldal fájlokat tölt be a webről: {0}. Ezek a fájlok nem kerülnek át.", + "Kódként megtartva, így az oldal megtartja saját szkriptjeit és stílusszabályait, a reszponzívakat is. A webről betöltött fájlok egyik esetben sem kerülnek át.", + "Elemekként az oldal a következő helyről betöltött fájlok nélkül érkezik: {0}, ezért a megjelenése vagy a működése egy része hiányozhat.", + "Kódként megtartva, mert {0} oldalból 1 fájlokat tölt be a webről. Kódként az oldalak megtartják saját szkriptjeiket és stílusszabályaikat, a reszponzívakat is; ezek a fájlok egyik esetben sem kerülnek át.", + "Elemekként {0} oldalból 1 a következő helyről betöltött fájlok nélkül érkezik: {1}, ezért a megjelenése vagy a működése egy része hiányozhat.", + "Kódként megtartva, mert {1} oldalból {0} fájlokat tölt be a webről. Kódként az oldalak megtartják saját szkriptjeiket és stílusszabályaikat, a reszponzívakat is; ezek a fájlok egyik esetben sem kerülnek át.", + "Elemekként {1} oldalból {0} a következő helyekről betöltött fájlok nélkül érkezik: {2}, ezért a megjelenésük vagy a működésük egy része hiányozhat.", + "1 stílusszabály megtartva a tartalomhoz, amelyet az oldal szkriptje felépít.", + "{0} stílusszabály megtartva a tartalomhoz, amelyet az oldal szkriptje felépít.", + "1 stílusszabály megtartva a tartalomhoz, amelyet az oldal szkriptje felépít, annak ellenőrzése nélkül, hogy az átalakított elemek használják-e: az ellenőrzés túl sokáig tartott, ezért minden szabály megmaradt.", + "{0} stílusszabály megtartva a tartalomhoz, amelyet az oldal szkriptje felépít, annak ellenőrzése nélkül, hogy melyiket használják az átalakított elemek: az ellenőrzés túl sokáig tartott, ezért minden szabály megmaradt.", + "Még 1 stílusszabály kimaradt: egy szkripthez legfeljebb {1} szabály és {2} KiB marad meg.", + "Még {0} stílusszabály kimaradt: egy szkripthez legfeljebb {1} szabály és {2} KiB marad meg.", + "Az oldal szkriptje által felépített tartalomhoz megtartott stílusszabály kimaradt, mert az oldal kódja túl nagy lenne.", + "Az oldal szkriptje által felépített tartalomhoz megtartott {0} stílusszabály kimaradt, mert az oldal kódja túl nagy lenne.", + "Az oldal stíluslapjáról 1 betűtípus vagy regisztrált tulajdonság kimaradt, mert a webhely már használja a nevét.", + "Az oldal stíluslapjáról {0} betűtípus vagy regisztrált tulajdonság kimaradt, mert a webhely már használja a nevüket.", + "{0} fájl exportálva.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/id.ts b/frontend/src/i18n/locales/id.ts index dba24e9d..b9f6e376 100644 --- a/frontend/src/i18n/locales/id.ts +++ b/frontend/src/i18n/locales/id.ts @@ -3028,4 +3028,59 @@ export default [ "Tidak dipertahankan: {0} tidak berubah.", "Elemen diubah di tempat lain, jadi uji coba dibatalkan.", "Perubahan ditolak.", + "Tampilkan penanda audit", + "Tampilkan penanda audit di halaman", + "Memasang penanda kecil pada setiap elemen di halaman ini yang memiliki masalah. Klik penanda untuk memilih elemennya.", + "1 masalah tidak memiliki elemen, jadi tidak memiliki penanda.", + "{0} masalah tidak memiliki elemen, jadi tidak memiliki penanda.", + "Penanda digambar pada {0} elemen pertama dari {1} elemen bermasalah di halaman ini.", + "1 masalah pada {0}", + "{0} masalah pada {1}", + "Masalah pada {0}", + "Audit tidak dapat dijalankan, jadi penanda audit disembunyikan.", + "Penanda audit aktif: setiap elemen di halaman ini yang memiliki masalah menampilkan penanda.", + "Penanda audit nonaktif.", + "Tempat ekspor disimpan", + "Folder Unduhan", + "Folder yang Anda pilih", + "Pilih folder...", + "Belum ada folder yang dipilih.", + "Tanyakan setiap kali", + "Setiap unduhan dari editor mengikuti pilihan ini: Ekspor situs statis, Unduh proyek .fweb, kode QR, dan ekspor gambar. Dengan Tanyakan setiap kali, setiap file menanyakan ke mana ia disimpan. Jika folder yang dipilih tidak dapat digunakan saat file disimpan, file masuk ke Unduhan dan pemberitahuan menyebutkannya.", + "Di browser, browser yang menentukan ke mana unduhan disimpan.", + "Pilih folder lain", + "Pilih folder tempat ekspor disimpan", + "Menyimpan {0}...", + "{0} tidak dapat disimpan ke {1}. Periksa apakah folder itu ada dan masih punya ruang kosong, lalu coba lagi.", + "Folder yang dipilih, {0}, tidak ada atau tidak dapat ditulisi, jadi {1} disimpan ke {2}.", + "Tidak ada yang disimpan.", + "{0} dan {1}", + "{0}, {1}", + "{0} dan 1 host lainnya", + "{0} dan {1} host lainnya", + "File dari {0} tidak ikut dibawa, jadi sebagian tampilan atau perilaku mungkin hilang.", + "1 lembar gaya dari {0}", + "{0} lembar gaya dari {1}", + "1 skrip dari {0}", + "{0} skrip dari {1}", + "1 file lainnya", + "{0} file lainnya", + "Halaman ini memuat file dari web: {0}. File ini tidak ikut dibawa.", + "Dipertahankan sebagai kode, jadi halaman mempertahankan skrip dan aturan gayanya sendiri, termasuk yang responsif. File yang dimuatnya dari web tidak ikut dibawa dalam kedua pilihan.", + "Sebagai elemen, halaman datang tanpa file yang dimuatnya dari {0}, jadi sebagian tampilan atau perilakunya mungkin hilang.", + "Dipertahankan sebagai kode, karena 1 dari {0} halaman memuat file dari web. Sebagai kode, halaman mempertahankan skrip dan aturan gayanya sendiri, termasuk yang responsif; file tersebut tidak ikut dibawa dalam kedua pilihan.", + "Sebagai elemen, 1 dari {0} halaman datang tanpa file yang dimuatnya dari {1}, jadi sebagian tampilan atau perilakunya mungkin hilang.", + "Dipertahankan sebagai kode, karena {0} dari {1} halaman memuat file dari web. Sebagai kode, halaman mempertahankan skrip dan aturan gayanya sendiri, termasuk yang responsif; file tersebut tidak ikut dibawa dalam kedua pilihan.", + "Sebagai elemen, {0} dari {1} halaman datang tanpa file yang dimuatnya dari {2}, jadi sebagian tampilan atau perilakunya mungkin hilang.", + "1 aturan gaya dipertahankan untuk konten yang dibangun skrip halaman.", + "{0} aturan gaya dipertahankan untuk konten yang dibangun skrip halaman.", + "1 aturan gaya dipertahankan untuk konten yang dibangun skrip halaman tanpa memeriksa apakah elemen yang diubah memakainya: pemeriksaan terlalu lama, jadi semua aturan dipertahankan.", + "{0} aturan gaya dipertahankan untuk konten yang dibangun skrip halaman tanpa memeriksa mana yang dipakai elemen yang diubah: pemeriksaan terlalu lama, jadi semua aturan dipertahankan.", + "1 aturan gaya lagi ditinggalkan: paling banyak {1} aturan dan {2} KiB dipertahankan untuk satu skrip.", + "{0} aturan gaya lagi ditinggalkan: paling banyak {1} aturan dan {2} KiB dipertahankan untuk satu skrip.", + "Aturan gaya yang dipertahankan untuk konten yang dibangun skrip halaman ditinggalkan karena kode halaman akan terlalu besar.", + "{0} aturan gaya yang dipertahankan untuk konten yang dibangun skrip halaman ditinggalkan karena kode halaman akan terlalu besar.", + "1 font atau properti terdaftar dari lembar gaya halaman ditinggalkan karena situs sudah memakai namanya.", + "{0} font atau properti terdaftar dari lembar gaya halaman ditinggalkan karena situs sudah memakai namanya.", + "{0} file diekspor.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/it.ts b/frontend/src/i18n/locales/it.ts index 11d1a1f7..52bf9759 100644 --- a/frontend/src/i18n/locales/it.ts +++ b/frontend/src/i18n/locales/it.ts @@ -3028,4 +3028,59 @@ export default [ "Non mantenuto: {0} è invariato.", "L’elemento è stato modificato altrove, quindi la prova è stata annullata.", "La modifica è stata rifiutata.", + "Mostra indicatori dell’audit", + "Mostra indicatori dell’audit sulla pagina", + "Mette un piccolo indicatore su ogni elemento di questa pagina che ha un problema. Fai clic su un indicatore per selezionare l’elemento.", + "1 problema non ha un elemento, quindi non ha un indicatore.", + "{0} problemi non hanno un elemento, quindi non hanno un indicatore.", + "Gli indicatori sono disegnati sui primi {0} di {1} elementi con problemi in questa pagina.", + "1 problema su {0}", + "{0} problemi su {1}", + "Problemi su {0}", + "Non è stato possibile eseguire l’audit, quindi gli indicatori dell’audit sono nascosti.", + "Indicatori dell’audit attivi: ogni elemento di questa pagina con un problema mostra un indicatore.", + "Indicatori dell’audit disattivati.", + "Dove vengono salvate le esportazioni", + "La cartella Download", + "Una cartella a tua scelta", + "Scegli cartella...", + "Nessuna cartella ancora scelta.", + "Chiedi ogni volta", + "Ogni download dall’editor segue questa scelta: Esporta sito statico, Scarica progetto .fweb, i codici QR e le esportazioni di immagini. Con Chiedi ogni volta, ogni file chiede dove andare. Se la cartella scelta non può essere usata quando un file viene salvato, il file va in Download e l’avviso lo indica.", + "In un browser, è il browser a decidere dove vanno i download.", + "Scegli un’altra cartella", + "Scegli la cartella in cui vengono salvate le esportazioni", + "Salvataggio di {0}...", + "Impossibile salvare {0} in {1}. Controlla che la cartella esista e abbia spazio libero, poi riprova.", + "La cartella scelta {0} non esiste o non è scrivibile, quindi {1} è stato salvato in {2}.", + "Non è stato salvato nulla.", + "{0} e {1}", + "{0}, {1}", + "{0} e 1 altro host", + "{0} e altri {1} host", + "I file da {0} non sono stati portati, quindi parte dell’aspetto o del comportamento potrebbe mancare.", + "1 foglio di stile da {0}", + "{0} fogli di stile da {1}", + "1 script da {0}", + "{0} script da {1}", + "1 altro file", + "altri {0} file", + "Questa pagina carica file dal web: {0}. Questi file non vengono portati.", + "Mantenuta come codice, così la pagina conserva i propri script e regole di stile, comprese quelle responsive. I file che carica dal web non vengono portati in nessun caso.", + "Come elementi, la pagina arriva senza i file che carica da {0}, quindi parte del suo aspetto o del suo comportamento potrebbe mancare.", + "Mantenute come codice, perché 1 pagina su {0} carica file dal web. Come codice le pagine conservano i propri script e regole di stile, comprese quelle responsive; quei file non vengono portati in nessun caso.", + "Come elementi, 1 pagina su {0} arriva senza i file che carica da {1}, quindi parte del suo aspetto o del suo comportamento potrebbe mancare.", + "Mantenute come codice, perché {0} pagine su {1} caricano file dal web. Come codice le pagine conservano i propri script e regole di stile, comprese quelle responsive; quei file non vengono portati in nessun caso.", + "Come elementi, {0} pagine su {1} arrivano senza i file che caricano da {2}, quindi parte del loro aspetto o del loro comportamento potrebbe mancare.", + "Mantenuta 1 regola di stile per il contenuto che costruisce lo script della pagina.", + "Mantenute {0} regole di stile per il contenuto che costruisce lo script della pagina.", + "Mantenuta 1 regola di stile per il contenuto che costruisce lo script della pagina senza controllare se gli elementi convertiti la usano: il controllo richiedeva troppo tempo, quindi sono state mantenute tutte le regole.", + "Mantenute {0} regole di stile per il contenuto che costruisce lo script della pagina senza controllare quali usano gli elementi convertiti: il controllo richiedeva troppo tempo, quindi sono state mantenute tutte le regole.", + "1 altra regola di stile è stata esclusa: per uno script si mantengono al massimo {1} regole e {2} KiB.", + "Altre {0} regole di stile sono state escluse: per uno script si mantengono al massimo {1} regole e {2} KiB.", + "La regola di stile mantenuta per il contenuto che costruisce lo script della pagina è stata esclusa perché il codice della pagina sarebbe troppo grande.", + "Le {0} regole di stile mantenute per il contenuto che costruisce lo script della pagina sono state escluse perché il codice della pagina sarebbe troppo grande.", + "1 font o proprietà registrata del foglio di stile della pagina è stato escluso perché il sito usa già il suo nome.", + "{0} font o proprietà registrate del foglio di stile della pagina sono stati esclusi perché il sito usa già i loro nomi.", + "Esportato {0} file.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ja.ts b/frontend/src/i18n/locales/ja.ts index 9d2ae7a5..75cfb20d 100644 --- a/frontend/src/i18n/locales/ja.ts +++ b/frontend/src/i18n/locales/ja.ts @@ -3028,4 +3028,59 @@ export default [ "確定されませんでした: {0} は変更されていません。", "要素が別の場所で変更されたため、試用を取り消しました。", "変更は拒否されました。", + "監査マーカーを表示", + "ページに監査マーカーを表示", + "このページで問題のある各要素に小さなマーカーを付けます。マーカーをクリックすると要素を選択します。", + "1 件の問題には要素がないため、マーカーはありません。", + "{0} 件の問題には要素がないため、マーカーはありません。", + "マーカーは、このページで問題のある {1} 個の要素のうち最初の {0} 個に描かれます。", + "{0} の問題 1 件", + "{1} の問題 {0} 件", + "{0} の問題", + "監査を実行できなかったため、監査マーカーを非表示にしました。", + "監査マーカーはオンです: このページで問題のある各要素にマーカーが表示されます。", + "監査マーカーはオフです。", + "書き出しの保存先", + "ダウンロードフォルダー", + "選んだフォルダー", + "フォルダーを選択...", + "フォルダーはまだ選択されていません。", + "毎回確認する", + "エディターからのダウンロードはすべてこの選択に従います: 「静的サイトを書き出し」「.fweb プロジェクトをダウンロード」、QR コード、画像の書き出し。「毎回確認する」では、ファイルごとに保存先を確認します。ファイルの保存時に選んだフォルダーを使えない場合、ファイルはダウンロードフォルダーに保存され、通知でそのことを伝えます。", + "ブラウザーでは、ダウンロードの保存先はブラウザーが決めます。", + "別のフォルダーを選択", + "書き出しの保存先フォルダーを選択", + "{0} を保存しています...", + "{0} を {1} に保存できませんでした。フォルダーが存在し、空き容量があることを確認してから、もう一度お試しください。", + "選んだフォルダー {0} が見つからないか書き込めないため、{1} を {2} に保存しました。", + "何も保存されませんでした。", + "{0} と {1}", + "{0}、{1}", + "{0} とほか 1 個のホスト", + "{0} とほか {1} 個のホスト", + "{0} のファイルは取り込まれなかったため、見た目や動作の一部が欠けている可能性があります。", + "{0} のスタイルシート 1 個", + "{1} のスタイルシート {0} 個", + "{0} のスクリプト 1 個", + "{1} のスクリプト {0} 個", + "ほか 1 個のファイル", + "ほか {0} 個のファイル", + "このページは Web からファイルを読み込みます: {0}。これらのファイルは取り込まれません。", + "コードのまま残すため、ページは独自のスクリプトとスタイルルール (レスポンシブのものを含む) を保ちます。Web から読み込むファイルは、どちらの場合も取り込まれません。", + "要素として取り込むと、ページは {0} から読み込むファイルなしで届くため、見た目や動作の一部が欠ける可能性があります。", + "{0} ページのうち 1 ページが Web からファイルを読み込むため、コードのまま残します。コードとしてなら、ページは独自のスクリプトとスタイルルール (レスポンシブのものを含む) を保ちます。これらのファイルはどちらの場合も取り込まれません。", + "要素として取り込むと、{0} ページのうち 1 ページは {1} から読み込むファイルなしで届くため、見た目や動作の一部が欠ける可能性があります。", + "{1} ページのうち {0} ページが Web からファイルを読み込むため、コードのまま残します。コードとしてなら、ページは独自のスクリプトとスタイルルール (レスポンシブのものを含む) を保ちます。これらのファイルはどちらの場合も取り込まれません。", + "要素として取り込むと、{1} ページのうち {0} ページは {2} から読み込むファイルなしで届くため、見た目や動作の一部が欠ける可能性があります。", + "ページのスクリプトが作るコンテンツのために、スタイルルールを 1 個残しました。", + "ページのスクリプトが作るコンテンツのために、スタイルルールを {0} 個残しました。", + "ページのスクリプトが作るコンテンツのために、変換した要素が使うかどうかを確認せずにスタイルルールを 1 個残しました: 確認に時間がかかりすぎたため、すべてのルールを残しました。", + "ページのスクリプトが作るコンテンツのために、変換した要素がどれを使うかを確認せずにスタイルルールを {0} 個残しました: 確認に時間がかかりすぎたため、すべてのルールを残しました。", + "さらにスタイルルール 1 個を省きました: 1 つのスクリプトに残せるのは最大 {1} 個のルールと {2} KiB です。", + "さらにスタイルルール {0} 個を省きました: 1 つのスクリプトに残せるのは最大 {1} 個のルールと {2} KiB です。", + "ページのスクリプトが作るコンテンツ用に残したスタイルルールを省きました: ページのコードが大きくなりすぎるためです。", + "ページのスクリプトが作るコンテンツ用に残したスタイルルール {0} 個を省きました: ページのコードが大きくなりすぎるためです。", + "ページのスタイルシートのフォントまたは登録済みプロパティ 1 個を省きました: サイトですでにその名前が使われています。", + "ページのスタイルシートのフォントまたは登録済みプロパティ {0} 個を省きました: サイトですでにその名前が使われています。", + "{0} 個のファイルを書き出しました。", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ko.ts b/frontend/src/i18n/locales/ko.ts index 2ff78f3b..f8e5ed00 100644 --- a/frontend/src/i18n/locales/ko.ts +++ b/frontend/src/i18n/locales/ko.ts @@ -3028,4 +3028,59 @@ export default [ "유지하지 않음: {0}은(는) 변경되지 않았습니다.", "요소가 다른 곳에서 변경되어 시험 적용을 취소했습니다.", "변경이 거부되었습니다.", + "감사 마커 표시", + "페이지에 감사 마커 표시", + "이 페이지에서 문제가 있는 각 요소에 작은 마커를 표시합니다. 마커를 클릭하면 요소를 선택합니다.", + "문제 1개에 요소가 없어 마커가 없습니다.", + "문제 {0}개에 요소가 없어 마커가 없습니다.", + "마커는 이 페이지에서 문제가 있는 요소 {1}개 중 처음 {0}개에 그려집니다.", + "{0}의 문제 1개", + "{1}의 문제 {0}개", + "{0}의 문제", + "감사를 실행할 수 없어 감사 마커를 숨겼습니다.", + "감사 마커가 켜졌습니다: 이 페이지에서 문제가 있는 각 요소에 마커가 표시됩니다.", + "감사 마커가 꺼졌습니다.", + "내보내기 저장 위치", + "다운로드 폴더", + "직접 선택한 폴더", + "폴더 선택...", + "아직 선택한 폴더가 없습니다.", + "매번 묻기", + "편집기의 모든 다운로드는 이 선택을 따릅니다: 정적 사이트 내보내기, .fweb 프로젝트 다운로드, QR 코드, 그림 내보내기. 매번 묻기를 선택하면 파일마다 저장 위치를 묻습니다.파일을 저장할 때 선택한 폴더를 사용할 수 없으면 파일은 다운로드 폴더로 가고 알림에서 이를 알려 줍니다.", + "브라우저에서는 다운로드 위치를 브라우저가 정합니다.", + "다른 폴더 선택", + "내보내기를 저장할 폴더 선택", + "{0} 저장 중...", + "{0}을(를) {1}에 저장할 수 없습니다. 폴더가 있고 여유 공간이 있는지 확인한 후 다시 시도하세요.", + "선택한 폴더 {0}이(가) 없거나 쓸 수 없어 {1}을(를) {2}에 저장했습니다.", + "아무것도 저장되지 않았습니다.", + "{0} 및 {1}", + "{0}, {1}", + "{0} 외 호스트 1개", + "{0} 외 호스트 {1}개", + "{0}의 파일은 가져오지 않았으므로 모양이나 동작의 일부가 빠질 수 있습니다.", + "{0}의 스타일시트 1개", + "{1}의 스타일시트 {0}개", + "{0}의 스크립트 1개", + "{1}의 스크립트 {0}개", + "파일 1개 더", + "파일 {0}개 더", + "이 페이지는 웹에서 파일을 불러옵니다: {0}. 이 파일들은 가져오지 않습니다.", + "코드로 유지하므로 페이지는 반응형 규칙을 포함한 자체 스크립트와 스타일 규칙을 유지합니다. 웹에서 불러오는 파일은 어느 쪽이든 가져오지 않습니다.", + "요소로 가져오면 페이지는 {0}에서 불러오는 파일 없이 들어오므로 모양이나 동작의 일부가 빠질 수 있습니다.", + "페이지 {0}개 중 1개가 웹에서 파일을 불러오므로 코드로 유지합니다. 코드로 두면 페이지는 반응형 규칙을 포함한 자체 스크립트와 스타일 규칙을 유지하며, 그 파일들은 어느 쪽이든 가져오지 않습니다.", + "요소로 가져오면 페이지 {0}개 중 1개는 {1}에서 불러오는 파일 없이 들어오므로 모양이나 동작의 일부가 빠질 수 있습니다.", + "페이지 {1}개 중 {0}개가 웹에서 파일을 불러오므로 코드로 유지합니다. 코드로 두면 페이지는 반응형 규칙을 포함한 자체 스크립트와 스타일 규칙을 유지하며, 그 파일들은 어느 쪽이든 가져오지 않습니다.", + "요소로 가져오면 페이지 {1}개 중 {0}개는 {2}에서 불러오는 파일 없이 들어오므로 모양이나 동작의 일부가 빠질 수 있습니다.", + "페이지 스크립트가 만드는 콘텐츠를 위해 스타일 규칙 1개를 유지했습니다.", + "페이지 스크립트가 만드는 콘텐츠를 위해 스타일 규칙 {0}개를 유지했습니다.", + "변환된 요소가 사용하는지 확인하지 않고 페이지 스크립트가 만드는 콘텐츠를 위해 스타일 규칙 1개를 유지했습니다: 확인에 시간이 너무 오래 걸려 모든 규칙을 유지했습니다.", + "변환된 요소가 어느 규칙을 사용하는지 확인하지 않고 페이지 스크립트가 만드는 콘텐츠를 위해 스타일 규칙 {0}개를 유지했습니다: 확인에 시간이 너무 오래 걸려 모든 규칙을 유지했습니다.", + "스타일 규칙 1개를 더 뺐습니다: 스크립트 하나에는 규칙 최대 {1}개와 {2} KiB까지만 유지됩니다.", + "스타일 규칙 {0}개를 더 뺐습니다: 스크립트 하나에는 규칙 최대 {1}개와 {2} KiB까지만 유지됩니다.", + "페이지 코드가 너무 커지므로 페이지 스크립트가 만드는 콘텐츠용으로 유지한 스타일 규칙을 뺐습니다.", + "페이지 코드가 너무 커지므로 페이지 스크립트가 만드는 콘텐츠용으로 유지한 스타일 규칙 {0}개를 뺐습니다.", + "사이트에서 이미 그 이름을 쓰고 있으므로 페이지 스타일시트의 글꼴 또는 등록된 속성 1개를 뺐습니다.", + "사이트에서 이미 그 이름들을 쓰고 있으므로 페이지 스타일시트의 글꼴 또는 등록된 속성 {0}개를 뺐습니다.", + "파일 {0}개를 내보냈습니다.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/nb.ts b/frontend/src/i18n/locales/nb.ts index 30ed7456..f6091740 100644 --- a/frontend/src/i18n/locales/nb.ts +++ b/frontend/src/i18n/locales/nb.ts @@ -3028,4 +3028,59 @@ export default [ "Ikke beholdt: {0} er uendret.", "Elementet ble endret et annet sted, så utprøvingen ble forkastet.", "Endringen ble avvist.", + "Vis revisjonsmarkører", + "Vis revisjonsmarkører på siden", + "Setter en liten markør på hvert element på denne siden som har et problem. Klikk på en markør for å velge elementet.", + "1 problem har ikke noe element, så det har ingen markør.", + "{0} problemer har ikke noe element, så de har ingen markør.", + "Markører tegnes på de første {0} av {1} elementer med problemer på denne siden.", + "1 problem på {0}", + "{0} problemer på {1}", + "Problemer på {0}", + "Revisjonen kunne ikke kjøres, så revisjonsmarkørene er skjult.", + "Revisjonsmarkører er på: hvert element på denne siden med et problem viser en markør.", + "Revisjonsmarkører er av.", + "Hvor eksporter lagres", + "Nedlastinger-mappen", + "En mappe du velger", + "Velg mappe...", + "Ingen mappe er valgt ennå.", + "Spør hver gang", + "Alle nedlastinger fra redigeringsprogrammet følger dette valget: Eksporter statisk nettsted, Last ned .fweb-prosjekt, QR-koder og bildeeksporter. Med Spør hver gang spør hver fil hvor den skal. Hvis den valgte mappen ikke kan brukes når en fil lagres, havner filen i Nedlastinger, og varselet sier fra.", + "I en nettleser bestemmer nettleseren hvor nedlastinger havner.", + "Velg en annen mappe", + "Velg mappen eksporter lagres i", + "Lagrer {0}...", + "{0} kunne ikke lagres i {1}. Sjekk at mappen finnes og har ledig plass, og prøv igjen.", + "Den valgte mappen {0} mangler eller kan ikke skrives til, så {1} ble lagret i {2}.", + "Ingenting ble lagret.", + "{0} og {1}", + "{0}, {1}", + "{0} og 1 vert til", + "{0} og {1} verter til", + "Filer fra {0} ble ikke med, så en del av utseendet eller virkemåten kan mangle.", + "1 stilark fra {0}", + "{0} stilark fra {1}", + "1 skript fra {0}", + "{0} skript fra {1}", + "1 fil til", + "{0} filer til", + "Denne siden laster filer fra nettet: {0}. Disse filene blir ikke med.", + "Beholdt som kode, så siden beholder sine egne skript og stilregler, også de responsive. Filene den laster fra nettet, blir ikke med i noe tilfelle.", + "Som elementer kommer siden uten filene den laster fra {0}, så en del av utseendet eller virkemåten kan mangle.", + "Beholdt som kode fordi 1 av {0} sider laster filer fra nettet. Som kode beholder sidene sine egne skript og stilregler, også de responsive; de filene blir ikke med i noe tilfelle.", + "Som elementer kommer 1 av {0} sider uten filene den laster fra {1}, så en del av utseendet eller virkemåten kan mangle.", + "Beholdt som kode fordi {0} av {1} sider laster filer fra nettet. Som kode beholder sidene sine egne skript og stilregler, også de responsive; de filene blir ikke med i noe tilfelle.", + "Som elementer kommer {0} av {1} sider uten filene de laster fra {2}, så en del av utseendet eller virkemåten deres kan mangle.", + "Beholdt 1 stilregel for innholdet sidens skript bygger.", + "Beholdt {0} stilregler for innholdet sidens skript bygger.", + "Beholdt 1 stilregel for innholdet sidens skript bygger, uten å sjekke om de konverterte elementene bruker den: sjekken tok for lang tid, så alle reglene ble beholdt.", + "Beholdt {0} stilregler for innholdet sidens skript bygger, uten å sjekke hvilke av dem de konverterte elementene bruker: sjekken tok for lang tid, så alle reglene ble beholdt.", + "1 stilregel til ble utelatt: høyst {1} regler og {2} KiB beholdes for et skript.", + "{0} stilregler til ble utelatt: høyst {1} regler og {2} KiB beholdes for et skript.", + "Stilregelen som var beholdt for innholdet sidens skript bygger, ble utelatt fordi sidens kode ville blitt for stor.", + "De {0} stilreglene som var beholdt for innholdet sidens skript bygger, ble utelatt fordi sidens kode ville blitt for stor.", + "1 skrift eller registrert egenskap fra sidens stilark ble utelatt fordi nettstedet allerede bruker navnet.", + "{0} skrifter eller registrerte egenskaper fra sidens stilark ble utelatt fordi nettstedet allerede bruker navnene.", + "Eksporterte {0} fil.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/nl.ts b/frontend/src/i18n/locales/nl.ts index ba9c6f61..9984fdce 100644 --- a/frontend/src/i18n/locales/nl.ts +++ b/frontend/src/i18n/locales/nl.ts @@ -3028,4 +3028,59 @@ export default [ "Niet behouden: {0} is ongewijzigd.", "Het element is elders gewijzigd, dus de proef is vervallen.", "De wijziging is geweigerd.", + "Auditmarkeringen tonen", + "Auditmarkeringen op de pagina tonen", + "Zet een kleine markering op elk element van deze pagina dat een probleem heeft. Klik op een markering om het element te selecteren.", + "1 probleem heeft geen element, dus het heeft geen markering.", + "{0} problemen hebben geen element, dus ze hebben geen markering.", + "Markeringen worden getekend op de eerste {0} van {1} elementen met problemen op deze pagina.", + "1 probleem op {0}", + "{0} problemen op {1}", + "Problemen op {0}", + "De audit kon niet worden uitgevoerd, dus de auditmarkeringen zijn verborgen.", + "Auditmarkeringen staan aan: elk element van deze pagina met een probleem toont een markering.", + "Auditmarkeringen staan uit.", + "Waar exports worden opgeslagen", + "De map Downloads", + "Een map die je kiest", + "Map kiezen...", + "Nog geen map gekozen.", + "Elke keer vragen", + "Elke download uit de editor volgt deze keuze: Statische site exporteren, .fweb-project downloaden, QR-codes en afbeeldingsexports. Met Elke keer vragen vraagt elk bestand waar het heen moet. Als de gekozen map niet kan worden gebruikt wanneer een bestand wordt opgeslagen, gaat het bestand naar Downloads en zegt de melding dat.", + "In een browser bepaalt de browser waar downloads terechtkomen.", + "Een andere map kiezen", + "De map kiezen waarin exports worden opgeslagen", + "{0} opslaan...", + "{0} kon niet worden opgeslagen in {1}. Controleer of de map bestaat en vrije ruimte heeft, en probeer het opnieuw.", + "De gekozen map {0} ontbreekt of is niet beschrijfbaar, dus {1} is opgeslagen in {2}.", + "Er is niets opgeslagen.", + "{0} en {1}", + "{0}, {1}", + "{0} en nog 1 host", + "{0} en nog {1} hosts", + "Bestanden van {0} zijn niet meegenomen, dus een deel van het uiterlijk of gedrag kan ontbreken.", + "1 stylesheet van {0}", + "{0} stylesheets van {1}", + "1 script van {0}", + "{0} scripts van {1}", + "nog 1 bestand", + "nog {0} bestanden", + "Deze pagina laadt bestanden van het web: {0}. Deze bestanden worden niet meegenomen.", + "Als code bewaard, zodat de pagina haar eigen scripts en stijlregels houdt, ook de responsieve. De bestanden die ze van het web laadt, worden in geen geval meegenomen.", + "Als elementen komt de pagina binnen zonder de bestanden die ze van {0} laadt, dus een deel van haar uiterlijk of gedrag kan ontbreken.", + "Als code bewaard, omdat 1 van {0} pagina's bestanden van het web laadt. Als code houden de pagina's hun eigen scripts en stijlregels, ook de responsieve; die bestanden worden in geen geval meegenomen.", + "Als elementen komt 1 van {0} pagina's binnen zonder de bestanden die ze van {1} laadt, dus een deel van haar uiterlijk of gedrag kan ontbreken.", + "Als code bewaard, omdat {0} van {1} pagina's bestanden van het web laden. Als code houden de pagina's hun eigen scripts en stijlregels, ook de responsieve; die bestanden worden in geen geval meegenomen.", + "Als elementen komen {0} van {1} pagina's binnen zonder de bestanden die ze van {2} laden, dus een deel van hun uiterlijk of gedrag kan ontbreken.", + "1 stijlregel bewaard voor de inhoud die het script van de pagina bouwt.", + "{0} stijlregels bewaard voor de inhoud die het script van de pagina bouwt.", + "1 stijlregel bewaard voor de inhoud die het script van de pagina bouwt, zonder te controleren of de omgezette elementen haar gebruiken: controleren duurde te lang, dus elke regel is bewaard.", + "{0} stijlregels bewaard voor de inhoud die het script van de pagina bouwt, zonder te controleren welke de omgezette elementen gebruiken: controleren duurde te lang, dus elke regel is bewaard.", + "Nog 1 stijlregel is weggelaten: voor een script worden hoogstens {1} regels en {2} KiB bewaard.", + "Nog {0} stijlregels zijn weggelaten: voor een script worden hoogstens {1} regels en {2} KiB bewaard.", + "De stijlregel die voor de inhoud van het paginascript was bewaard, is weggelaten omdat de code van de pagina te groot zou worden.", + "De {0} stijlregels die voor de inhoud van het paginascript waren bewaard, zijn weggelaten omdat de code van de pagina te groot zou worden.", + "1 lettertype of geregistreerde eigenschap uit de stylesheet van de pagina is weggelaten omdat de site die naam al gebruikt.", + "{0} lettertypen of geregistreerde eigenschappen uit de stylesheet van de pagina zijn weggelaten omdat de site die namen al gebruikt.", + "{0} bestand geëxporteerd.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/pl.ts b/frontend/src/i18n/locales/pl.ts index 9821f83c..36567b00 100644 --- a/frontend/src/i18n/locales/pl.ts +++ b/frontend/src/i18n/locales/pl.ts @@ -3028,4 +3028,59 @@ export default [ "Nie zachowano: {0} bez zmian.", "Element został zmieniony gdzie indziej, więc próba została odrzucona.", "Zmiana została odrzucona.", + "Pokaż znaczniki audytu", + "Pokazuj znaczniki audytu na stronie", + "Umieszcza mały znacznik na każdym elemencie tej strony, który ma problem. Kliknij znacznik, aby zaznaczyć element.", + "1 problem nie ma elementu, więc nie ma znacznika.", + "Problemy bez elementu: {0}, więc nie mają znaczników.", + "Znaczniki są rysowane na pierwszych {0} z {1} elementów z problemami na tej stronie.", + "1 problem w elemencie {0}", + "Problemy w elemencie {1}: {0}", + "Problemy w elemencie {0}", + "Nie udało się uruchomić audytu, więc znaczniki audytu są ukryte.", + "Znaczniki audytu są włączone: każdy element tej strony z problemem pokazuje znacznik.", + "Znaczniki audytu są wyłączone.", + "Gdzie zapisywane są eksporty", + "Folder Pobrane", + "Wybrany przez ciebie folder", + "Wybierz folder...", + "Nie wybrano jeszcze folderu.", + "Pytaj za każdym razem", + "Każde pobranie z edytora stosuje się do tego wyboru: Eksportuj witrynę statyczną, Pobierz projekt .fweb, kody QR i eksporty obrazów. Przy Pytaj za każdym razem każdy plik pyta, gdzie ma trafić. Jeśli wybranego folderu nie da się użyć przy zapisywaniu pliku, plik trafia do folderu Pobrane, a powiadomienie o tym informuje.", + "W przeglądarce to przeglądarka decyduje, gdzie trafiają pobrane pliki.", + "Wybierz inny folder", + "Wybierz folder, w którym zapisywane są eksporty", + "Zapisywanie {0}...", + "Nie udało się zapisać {0} w {1}. Sprawdź, czy folder istnieje i ma wolne miejsce, a następnie spróbuj ponownie.", + "Wybrany folder {0} nie istnieje lub nie można w nim zapisywać, więc zapisano {1} w {2}.", + "Nic nie zostało zapisane.", + "{0} i {1}", + "{0}, {1}", + "{0} i 1 inny host", + "{0} i inne hosty: {1}", + "Pliki z {0} nie zostały przeniesione, więc może brakować części wyglądu lub działania.", + "1 arkusz stylów z {0}", + "arkusze stylów z {1}: {0}", + "1 skrypt z {0}", + "skrypty z {1}: {0}", + "1 inny plik", + "inne pliki: {0}", + "Ta strona wczytuje pliki z internetu: {0}. Te pliki nie są przenoszone.", + "Zachowana jako kod, więc strona zachowuje własne skrypty i reguły stylów, także responsywne. Pliki, które wczytuje z internetu, nie są przenoszone w żadnym przypadku.", + "Jako elementy strona trafi bez plików, które wczytuje z {0}, więc może zabraknąć części jej wyglądu lub działania.", + "Zachowane jako kod, bo 1 z {0} stron wczytuje pliki z internetu. Jako kod strony zachowują własne skrypty i reguły stylów, także responsywne; tych plików nie przenosi się w żadnym przypadku.", + "Jako elementy 1 z {0} stron trafi bez plików, które wczytuje z {1}, więc może zabraknąć części jej wyglądu lub działania.", + "Zachowane jako kod, bo strony wczytujące pliki z internetu: {0} z {1}. Jako kod strony zachowują własne skrypty i reguły stylów, także responsywne; tych plików nie przenosi się w żadnym przypadku.", + "Jako elementy strony ({0} z {1}) trafią bez plików, które wczytują z {2}, więc może zabraknąć części ich wyglądu lub działania.", + "Zachowano 1 regułę stylu dla treści, którą buduje skrypt strony.", + "Zachowane reguły stylu dla treści, którą buduje skrypt strony: {0}.", + "Zachowano 1 regułę stylu dla treści, którą buduje skrypt strony, bez sprawdzania, czy zamienione elementy jej używają: sprawdzanie trwało zbyt długo, więc zachowano wszystkie reguły.", + "Zachowane reguły stylu dla treści, którą buduje skrypt strony: {0}, bez sprawdzania, których z nich używają zamienione elementy: sprawdzanie trwało zbyt długo, więc zachowano wszystkie reguły.", + "Pominięto jeszcze 1 regułę stylu: dla skryptu zachowuje się najwyżej {1} reguł i {2} KiB.", + "Pominięte kolejne reguły stylu: {0}. Dla skryptu zachowuje się najwyżej {1} reguł i {2} KiB.", + "Reguła stylu zachowana dla treści budowanej przez skrypt strony została pominięta, bo kod strony byłby za duży.", + "Reguły stylu zachowane dla treści budowanej przez skrypt strony ({0}) zostały pominięte, bo kod strony byłby za duży.", + "Pominięto 1 czcionkę lub zarejestrowaną właściwość z arkusza stylów strony, bo witryna już używa jej nazwy.", + "Pominięte czcionki lub zarejestrowane właściwości z arkusza stylów strony: {0}, bo witryna już używa ich nazw.", + "Wyeksportowano plików: {0}.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/pt-BR.ts b/frontend/src/i18n/locales/pt-BR.ts index 57dfdb56..b37d7dd4 100644 --- a/frontend/src/i18n/locales/pt-BR.ts +++ b/frontend/src/i18n/locales/pt-BR.ts @@ -3028,4 +3028,59 @@ export default [ "Não mantido: {0} não mudou.", "O elemento foi alterado em outro lugar, então o teste foi descartado.", "A alteração foi recusada.", + "Mostrar marcadores de auditoria", + "Mostrar marcadores de auditoria na página", + "Coloca um pequeno marcador em cada elemento desta página que tem um problema. Clique em um marcador para selecionar o elemento.", + "1 problema não tem elemento, então não tem marcador.", + "{0} problemas não têm elemento, então não têm marcador.", + "Os marcadores são desenhados nos primeiros {0} de {1} elementos com problemas desta página.", + "1 problema em {0}", + "{0} problemas em {1}", + "Problemas em {0}", + "Não foi possível executar a auditoria, então os marcadores de auditoria estão ocultos.", + "Marcadores de auditoria ativados: cada elemento desta página com um problema mostra um marcador.", + "Marcadores de auditoria desativados.", + "Onde as exportações são salvas", + "A pasta Downloads", + "Uma pasta que você escolher", + "Escolher pasta...", + "Nenhuma pasta escolhida ainda.", + "Perguntar sempre", + "Todos os downloads do editor seguem esta escolha: Exportar site estático, Baixar projeto .fweb, códigos QR e exportações de imagens. Com Perguntar sempre, cada arquivo pergunta para onde vai. Se a pasta escolhida não puder ser usada quando um arquivo for salvo, o arquivo vai para Downloads e o aviso informa isso.", + "Em um navegador, o navegador decide para onde vão os downloads.", + "Escolher outra pasta", + "Escolher a pasta onde as exportações são salvas", + "Salvando {0}...", + "Não foi possível salvar {0} em {1}. Verifique se a pasta existe e tem espaço livre e tente novamente.", + "A pasta escolhida {0} não existe ou não permite gravação, então {1} foi salvo em {2}.", + "Nada foi salvo.", + "{0} e {1}", + "{0}, {1}", + "{0} e mais 1 host", + "{0} e mais {1} hosts", + "Os arquivos de {0} não foram trazidos, então parte da aparência ou do comportamento pode estar faltando.", + "1 folha de estilo de {0}", + "{0} folhas de estilo de {1}", + "1 script de {0}", + "{0} scripts de {1}", + "mais 1 arquivo", + "mais {0} arquivos", + "Esta página carrega arquivos da web: {0}. Esses arquivos não são trazidos.", + "Mantida como código, então a página conserva seus próprios scripts e regras de estilo, inclusive os responsivos. Os arquivos que ela carrega da web não são trazidos de nenhuma forma.", + "Como elementos, a página chega sem os arquivos que carrega de {0}, então parte da aparência ou do comportamento pode faltar.", + "Mantidas como código porque 1 de {0} páginas carrega arquivos da web. Como código, as páginas conservam seus próprios scripts e regras de estilo, inclusive os responsivos; esses arquivos não são trazidos de nenhuma forma.", + "Como elementos, 1 de {0} páginas chega sem os arquivos que carrega de {1}, então parte da aparência ou do comportamento pode faltar.", + "Mantidas como código porque {0} de {1} páginas carregam arquivos da web. Como código, as páginas conservam seus próprios scripts e regras de estilo, inclusive os responsivos; esses arquivos não são trazidos de nenhuma forma.", + "Como elementos, {0} de {1} páginas chegam sem os arquivos que carregam de {2}, então parte da aparência ou do comportamento pode faltar.", + "1 regra de estilo mantida para o conteúdo que o script da página constrói.", + "{0} regras de estilo mantidas para o conteúdo que o script da página constrói.", + "1 regra de estilo mantida para o conteúdo que o script da página constrói sem verificar se os elementos convertidos a usam: a verificação demorou demais, então todas as regras foram mantidas.", + "{0} regras de estilo mantidas para o conteúdo que o script da página constrói sem verificar quais delas os elementos convertidos usam: a verificação demorou demais, então todas as regras foram mantidas.", + "Mais 1 regra de estilo foi deixada de fora: no máximo {1} regras e {2} KiB são mantidos para um script.", + "Mais {0} regras de estilo foram deixadas de fora: no máximo {1} regras e {2} KiB são mantidos para um script.", + "A regra de estilo mantida para o conteúdo que o script da página constrói foi deixada de fora porque o código da página ficaria grande demais.", + "As {0} regras de estilo mantidas para o conteúdo que o script da página constrói foram deixadas de fora porque o código da página ficaria grande demais.", + "1 fonte ou propriedade registrada da folha de estilo da página foi deixada de fora porque o site já usa o nome dela.", + "{0} fontes ou propriedades registradas da folha de estilo da página foram deixadas de fora porque o site já usa os nomes delas.", + "{0} arquivo exportado.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ru.ts b/frontend/src/i18n/locales/ru.ts index 12ba244b..ab8df5e2 100644 --- a/frontend/src/i18n/locales/ru.ts +++ b/frontend/src/i18n/locales/ru.ts @@ -3028,4 +3028,59 @@ export default [ "Не оставлено: {0} без изменений.", "Элемент был изменён в другом месте, поэтому проба отменена.", "Изменение отклонено.", + "Показать маркеры аудита", + "Показывать маркеры аудита на странице", + "Ставит небольшой маркер на каждый элемент этой страницы, у которого есть проблема. Нажмите на маркер, чтобы выбрать элемент.", + "У 1 проблемы нет элемента, поэтому у неё нет маркера.", + "Проблем без элемента: {0}, поэтому у них нет маркеров.", + "Маркеры нарисованы на первых {0} из {1} элементов с проблемами на этой странице.", + "1 проблема у элемента {0}", + "Проблем у элемента {1}: {0}", + "Проблемы у элемента {0}", + "Не удалось выполнить аудит, поэтому маркеры аудита скрыты.", + "Маркеры аудита включены: каждый элемент этой страницы с проблемой показывает маркер.", + "Маркеры аудита выключены.", + "Куда сохраняются экспортированные файлы", + "Папка «Загрузки»", + "Папка, которую вы выберете", + "Выбрать папку...", + "Папка ещё не выбрана.", + "Спрашивать каждый раз", + "Все загрузки из редактора следуют этому выбору: «Экспорт статического сайта», «Скачать проект .fweb», QR-коды и экспорт изображений. При «Спрашивать каждый раз» каждый файл спрашивает, куда его сохранить. Если выбранную папку нельзя использовать при сохранении файла, файл попадает в «Загрузки», и уведомление сообщает об этом.", + "В браузере место для загрузок выбирает сам браузер.", + "Выбрать другую папку", + "Выбрать папку для сохранения экспортированных файлов", + "Сохранение {0}...", + "Не удалось сохранить {0} в {1}. Убедитесь, что папка существует и в ней есть свободное место, затем повторите попытку.", + "Выбранная папка {0} отсутствует или недоступна для записи, поэтому {1} сохранён в {2}.", + "Ничего не сохранено.", + "{0} и {1}", + "{0}, {1}", + "{0} и ещё 1 хост", + "{0} и другие хосты ({1})", + "Файлы с {0} не перенесены, поэтому часть оформления или поведения может отсутствовать.", + "1 таблица стилей с {0}", + "таблицы стилей с {1} ({0})", + "1 скрипт с {0}", + "скрипты с {1} ({0})", + "ещё 1 файл", + "ещё файлы ({0})", + "Эта страница загружает файлы из интернета: {0}. Эти файлы не переносятся.", + "Оставлено как код, поэтому страница сохраняет свои скрипты и правила стилей, включая адаптивные. Файлы, которые она загружает из интернета, не переносятся ни в одном из вариантов.", + "Как элементы страница придёт без файлов, которые она загружает с {0}, поэтому часть её оформления или поведения может отсутствовать.", + "Оставлено как код, потому что 1 из {0} страниц загружает файлы из интернета. Как код страницы сохраняют свои скрипты и правила стилей, включая адаптивные; эти файлы не переносятся ни в одном из вариантов.", + "Как элементы 1 из {0} страниц придёт без файлов, которые она загружает с {1}, поэтому часть её оформления или поведения может отсутствовать.", + "Оставлено как код, потому что страниц, загружающих файлы из интернета: {0} из {1}. Как код страницы сохраняют свои скрипты и правила стилей, включая адаптивные; эти файлы не переносятся ни в одном из вариантов.", + "Как элементы страницы ({0} из {1}) придут без файлов, которые они загружают с {2}, поэтому часть их оформления или поведения может отсутствовать.", + "Сохранено правило стиля для содержимого, которое строит скрипт страницы.", + "Сохранено правил стиля для содержимого, которое строит скрипт страницы: {0}.", + "Сохранено правило стиля для содержимого, которое строит скрипт страницы, без проверки, используют ли его преобразованные элементы: проверка заняла слишком много времени, поэтому сохранены все правила.", + "Сохранено правил стиля для содержимого, которое строит скрипт страницы: {0}, без проверки, какие из них используют преобразованные элементы: проверка заняла слишком много времени, поэтому сохранены все правила.", + "Пропущено ещё одно правило стиля: для скрипта сохраняется не больше {1} правил и {2} КиБ.", + "Пропущено ещё правил стиля: {0}. Для скрипта сохраняется не больше {1} правил и {2} КиБ.", + "Правило стиля, сохранённое для содержимого скрипта страницы, пропущено, потому что код страницы стал бы слишком большим.", + "Правила стиля, сохранённые для содержимого скрипта страницы ({0}), пропущены, потому что код страницы стал бы слишком большим.", + "Шрифт или зарегистрированное свойство из таблицы стилей страницы пропущено, потому что сайт уже использует это имя.", + "Пропущено шрифтов или зарегистрированных свойств из таблицы стилей страницы: {0}, потому что сайт уже использует эти имена.", + "Экспортировано файлов: {0}.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/sv.ts b/frontend/src/i18n/locales/sv.ts index 1e1e33d8..2da66bb9 100644 --- a/frontend/src/i18n/locales/sv.ts +++ b/frontend/src/i18n/locales/sv.ts @@ -3028,4 +3028,59 @@ export default [ "Inte behållet: {0} är oförändrat.", "Elementet ändrades på annat håll, så provningen släpptes.", "Ändringen avvisades.", + "Visa granskningsmarkörer", + "Visa granskningsmarkörer på sidan", + "Sätter en liten markör på varje element på den här sidan som har ett problem. Klicka på en markör för att markera elementet.", + "1 problem har inget element, så det har ingen markör.", + "{0} problem har inget element, så de har ingen markör.", + "Markörer ritas på de första {0} av {1} element med problem på den här sidan.", + "1 problem på {0}", + "{0} problem på {1}", + "Problem på {0}", + "Granskningen kunde inte köras, så granskningsmarkörerna är dolda.", + "Granskningsmarkörer är på: varje element på den här sidan med ett problem visar en markör.", + "Granskningsmarkörer är av.", + "Var exporter sparas", + "Mappen Hämtade filer", + "En mapp som du väljer", + "Välj mapp...", + "Ingen mapp har valts än.", + "Fråga varje gång", + "Alla nedladdningar från redigeraren följer det här valet: Exportera statisk webbplats, Ladda ned .fweb-projekt, QR-koder och bildexporter. Med Fråga varje gång frågar varje fil var den ska hamna. Om den valda mappen inte kan användas när en fil sparas hamnar filen i Hämtade filer och meddelandet säger det.", + "I en webbläsare bestämmer webbläsaren var nedladdningar hamnar.", + "Välj en annan mapp", + "Välj mappen som exporter sparas i", + "Sparar {0}...", + "{0} kunde inte sparas i {1}. Kontrollera att mappen finns och har ledigt utrymme och försök sedan igen.", + "Den valda mappen {0} saknas eller går inte att skriva till, så {1} sparades i {2}.", + "Inget sparades.", + "{0} och {1}", + "{0}, {1}", + "{0} och 1 värd till", + "{0} och {1} värdar till", + "Filer från {0} följde inte med, så en del av utseendet eller beteendet kan saknas.", + "1 formatmall från {0}", + "{0} formatmallar från {1}", + "1 skript från {0}", + "{0} skript från {1}", + "1 fil till", + "{0} filer till", + "Den här sidan läser in filer från webben: {0}. De filerna följer inte med.", + "Behålls som kod, så sidan behåller sina egna skript och stilregler, även de responsiva. Filerna som den läser in från webben följer inte med i något av fallen.", + "Som element kommer sidan utan filerna som den läser in från {0}, så en del av dess utseende eller beteende kan saknas.", + "Behålls som kod eftersom 1 av {0} sidor läser in filer från webben. Som kod behåller sidorna sina egna skript och stilregler, även de responsiva; de filerna följer inte med i något av fallen.", + "Som element kommer 1 av {0} sidor utan filerna som den läser in från {1}, så en del av dess utseende eller beteende kan saknas.", + "Behålls som kod eftersom {0} av {1} sidor läser in filer från webben. Som kod behåller sidorna sina egna skript och stilregler, även de responsiva; de filerna följer inte med i något av fallen.", + "Som element kommer {0} av {1} sidor utan filerna som de läser in från {2}, så en del av deras utseende eller beteende kan saknas.", + "Behöll 1 stilregel för innehållet som sidans skript bygger.", + "Behöll {0} stilregler för innehållet som sidans skript bygger.", + "Behöll 1 stilregel för innehållet som sidans skript bygger utan att kontrollera om de konverterade elementen använder den: kontrollen tog för lång tid, så alla regler behölls.", + "Behöll {0} stilregler för innehållet som sidans skript bygger utan att kontrollera vilka av dem de konverterade elementen använder: kontrollen tog för lång tid, så alla regler behölls.", + "1 stilregel till utelämnades: högst {1} regler och {2} KiB behålls för ett skript.", + "{0} stilregler till utelämnades: högst {1} regler och {2} KiB behålls för ett skript.", + "Stilregeln som behölls för innehållet som sidans skript bygger utelämnades eftersom sidans kod skulle bli för stor.", + "De {0} stilregler som behölls för innehållet som sidans skript bygger utelämnades eftersom sidans kod skulle bli för stor.", + "1 typsnitt eller registrerad egenskap från sidans formatmall utelämnades eftersom webbplatsen redan använder namnet.", + "{0} typsnitt eller registrerade egenskaper från sidans formatmall utelämnades eftersom webbplatsen redan använder namnen.", + "{0} fil exporterades.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/th.ts b/frontend/src/i18n/locales/th.ts index 0161dc90..0628c7f7 100644 --- a/frontend/src/i18n/locales/th.ts +++ b/frontend/src/i18n/locales/th.ts @@ -3028,4 +3028,59 @@ export default [ "ไม่ได้เก็บไว้: {0} ไม่เปลี่ยนแปลง", "องค์ประกอบถูกเปลี่ยนจากที่อื่น จึงยกเลิกการลองใช้", "การเปลี่ยนแปลงถูกปฏิเสธ", + "แสดงเครื่องหมายการตรวจสอบ", + "แสดงเครื่องหมายการตรวจสอบบนหน้า", + "ใส่เครื่องหมายเล็กๆ บนแต่ละองค์ประกอบของหน้านี้ที่มีปัญหา คลิกเครื่องหมายเพื่อเลือกองค์ประกอบนั้น", + "ปัญหา 1 รายการไม่มีองค์ประกอบ จึงไม่มีเครื่องหมาย", + "ปัญหา {0} รายการไม่มีองค์ประกอบ จึงไม่มีเครื่องหมาย", + "เครื่องหมายแสดงบน {0} องค์ประกอบแรกจาก {1} องค์ประกอบที่มีปัญหาในหน้านี้", + "ปัญหา 1 รายการใน {0}", + "ปัญหา {0} รายการใน {1}", + "ปัญหาใน {0}", + "เรียกใช้การตรวจสอบไม่ได้ จึงซ่อนเครื่องหมายการตรวจสอบไว้", + "เปิดเครื่องหมายการตรวจสอบแล้ว: แต่ละองค์ประกอบของหน้านี้ที่มีปัญหาจะแสดงเครื่องหมาย", + "ปิดเครื่องหมายการตรวจสอบแล้ว", + "ที่บันทึกไฟล์ส่งออก", + "โฟลเดอร์ดาวน์โหลด", + "โฟลเดอร์ที่คุณเลือก", + "เลือกโฟลเดอร์...", + "ยังไม่ได้เลือกโฟลเดอร์", + "ถามทุกครั้ง", + "การดาวน์โหลดทั้งหมดจากตัวแก้ไขจะทำตามตัวเลือกนี้: ส่งออกไซต์แบบสถิต ดาวน์โหลดโปรเจกต์ .fweb คิวอาร์โค้ด และการส่งออกรูปภาพ เมื่อเลือก ถามทุกครั้ง แต่ละไฟล์จะถามว่าจะบันทึกที่ใด หากใช้โฟลเดอร์ที่เลือกไม่ได้ขณะบันทึกไฟล์ ไฟล์จะไปที่โฟลเดอร์ดาวน์โหลดและการแจ้งเตือนจะบอกไว้", + "ในเบราว์เซอร์ เบราว์เซอร์จะเป็นผู้กำหนดว่าไฟล์ดาวน์โหลดไปอยู่ที่ใด", + "เลือกโฟลเดอร์อื่น", + "เลือกโฟลเดอร์ที่จะบันทึกไฟล์ส่งออก", + "กำลังบันทึก {0}...", + "บันทึก {0} ลงใน {1} ไม่ได้ ตรวจสอบว่าโฟลเดอร์มีอยู่และมีพื้นที่ว่าง แล้วลองอีกครั้ง", + "ไม่พบโฟลเดอร์ที่เลือก {0} หรือเขียนลงไม่ได้ จึงบันทึก {1} ลงใน {2}", + "ไม่ได้บันทึกสิ่งใด", + "{0} และ {1}", + "{0}, {1}", + "{0} และโฮสต์อื่นอีก 1 รายการ", + "{0} และโฮสต์อื่นอีก {1} รายการ", + "ไม่ได้นำไฟล์จาก {0} มาด้วย ลักษณะหรือการทำงานบางส่วนจึงอาจหายไป", + "สไตล์ชีต 1 รายการจาก {0}", + "สไตล์ชีต {0} รายการจาก {1}", + "สคริปต์ 1 รายการจาก {0}", + "สคริปต์ {0} รายการจาก {1}", + "ไฟล์อื่นอีก 1 ไฟล์", + "ไฟล์อื่นอีก {0} ไฟล์", + "หน้านี้โหลดไฟล์จากเว็บ: {0} ไฟล์เหล่านี้จะไม่ถูกนำมาด้วย", + "เก็บไว้เป็นโค้ด หน้าจึงคงสคริปต์และกฎสไตล์ของตัวเองไว้ รวมถึงกฎแบบตอบสนอง ไฟล์ที่หน้าโหลดจากเว็บจะไม่ถูกนำมาด้วยไม่ว่าจะเลือกแบบใด", + "หากนำเข้าเป็นองค์ประกอบ หน้าจะมาโดยไม่มีไฟล์ที่โหลดจาก {0} ลักษณะหรือการทำงานบางส่วนจึงอาจหายไป", + "เก็บไว้เป็นโค้ด เพราะ 1 จาก {0} หน้าโหลดไฟล์จากเว็บ เมื่อเป็นโค้ด หน้าจะคงสคริปต์และกฎสไตล์ของตัวเองไว้ รวมถึงกฎแบบตอบสนอง ไฟล์เหล่านั้นจะไม่ถูกนำมาด้วยไม่ว่าจะเลือกแบบใด", + "หากนำเข้าเป็นองค์ประกอบ 1 จาก {0} หน้าจะมาโดยไม่มีไฟล์ที่โหลดจาก {1} ลักษณะหรือการทำงานบางส่วนจึงอาจหายไป", + "เก็บไว้เป็นโค้ด เพราะ {0} จาก {1} หน้าโหลดไฟล์จากเว็บ เมื่อเป็นโค้ด หน้าจะคงสคริปต์และกฎสไตล์ของตัวเองไว้ รวมถึงกฎแบบตอบสนอง ไฟล์เหล่านั้นจะไม่ถูกนำมาด้วยไม่ว่าจะเลือกแบบใด", + "หากนำเข้าเป็นองค์ประกอบ {0} จาก {1} หน้าจะมาโดยไม่มีไฟล์ที่โหลดจาก {2} ลักษณะหรือการทำงานบางส่วนจึงอาจหายไป", + "เก็บกฎสไตล์ 1 ข้อไว้สำหรับเนื้อหาที่สคริปต์ของหน้าสร้าง", + "เก็บกฎสไตล์ {0} ข้อไว้สำหรับเนื้อหาที่สคริปต์ของหน้าสร้าง", + "เก็บกฎสไตล์ 1 ข้อไว้สำหรับเนื้อหาที่สคริปต์ของหน้าสร้างโดยไม่ได้ตรวจว่าองค์ประกอบที่แปลงแล้วใช้กฎนั้นหรือไม่: การตรวจใช้เวลานานเกินไป จึงเก็บกฎไว้ทั้งหมด", + "เก็บกฎสไตล์ {0} ข้อไว้สำหรับเนื้อหาที่สคริปต์ของหน้าสร้างโดยไม่ได้ตรวจว่าองค์ประกอบที่แปลงแล้วใช้กฎข้อใด: การตรวจใช้เวลานานเกินไป จึงเก็บกฎไว้ทั้งหมด", + "ละกฎสไตล์อีก 1 ข้อ: เก็บได้สูงสุด {1} กฎและ {2} KiB ต่อสคริปต์", + "ละกฎสไตล์อีก {0} ข้อ: เก็บได้สูงสุด {1} กฎและ {2} KiB ต่อสคริปต์", + "ละกฎสไตล์ที่เก็บไว้สำหรับเนื้อหาที่สคริปต์ของหน้าสร้าง เพราะโค้ดของหน้าจะใหญ่เกินไป", + "ละกฎสไตล์ {0} ข้อที่เก็บไว้สำหรับเนื้อหาที่สคริปต์ของหน้าสร้าง เพราะโค้ดของหน้าจะใหญ่เกินไป", + "ละฟอนต์หรือคุณสมบัติที่ลงทะเบียน 1 รายการจากสไตล์ชีตของหน้า เพราะไซต์ใช้ชื่อนั้นอยู่แล้ว", + "ละฟอนต์หรือคุณสมบัติที่ลงทะเบียน {0} รายการจากสไตล์ชีตของหน้า เพราะไซต์ใช้ชื่อเหล่านั้นอยู่แล้ว", + "ส่งออกแล้ว {0} ไฟล์", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/tr.ts b/frontend/src/i18n/locales/tr.ts index d4875efe..07be2c3f 100644 --- a/frontend/src/i18n/locales/tr.ts +++ b/frontend/src/i18n/locales/tr.ts @@ -3028,4 +3028,59 @@ export default [ "Korunmadı: {0} değişmedi.", "Öğe başka bir yerde değiştirildi, bu yüzden deneme bırakıldı.", "Değişiklik reddedildi.", + "Denetim işaretçilerini göster", + "Denetim işaretçilerini sayfada göster", + "Bu sayfada sorunu olan her öğeye küçük bir işaretçi koyar. Öğeyi seçmek için bir işaretçiye tıklayın.", + "1 sorunun öğesi yok, bu yüzden işaretçisi de yok.", + "{0} sorunun öğesi yok, bu yüzden işaretçileri de yok.", + "İşaretçiler, bu sayfada sorunu olan {1} öğenin ilk {0} tanesine çizilir.", + "{0} üzerinde 1 sorun", + "{1} üzerinde {0} sorun", + "{0} üzerindeki sorunlar", + "Denetim çalıştırılamadı, bu yüzden denetim işaretçileri gizlendi.", + "Denetim işaretçileri açık: bu sayfada sorunu olan her öğe bir işaretçi gösterir.", + "Denetim işaretçileri kapalı.", + "Dışa aktarılanların kaydedileceği yer", + "İndirilenler klasörü", + "Seçtiğiniz bir klasör", + "Klasör seç...", + "Henüz klasör seçilmedi.", + "Her seferinde sor", + "Düzenleyicideki her indirme bu seçimi izler: Statik siteyi dışa aktar, .fweb projesini indir, QR kodları ve resim dışa aktarımları. Her seferinde sor seçiliyken her dosya nereye gideceğini sorar. Seçilen klasör bir dosya kaydedilirken kullanılamazsa dosya İndirilenler klasörüne gider ve bildirim bunu söyler.", + "Tarayıcıda indirmelerin nereye gideceğine tarayıcı karar verir.", + "Başka bir klasör seç", + "Dışa aktarılanların kaydedileceği klasörü seç", + "{0} kaydediliyor...", + "{0}, {1} konumuna kaydedilemedi. Klasörün var olduğunu ve boş alanı olduğunu kontrol edip yeniden deneyin.", + "Seçilen {0} klasörü yok veya yazılamıyor, bu yüzden {1}, {2} konumuna kaydedildi.", + "Hiçbir şey kaydedilmedi.", + "{0} ve {1}", + "{0}, {1}", + "{0} ve 1 sunucu daha", + "{0} ve {1} sunucu daha", + "Şu kaynaklardan gelen dosyalar getirilmedi: {0}. Bu yüzden görünümün veya davranışın bir kısmı eksik olabilir.", + "{0} kaynağından 1 stil sayfası", + "{1} kaynağından {0} stil sayfası", + "{0} kaynağından 1 betik", + "{1} kaynağından {0} betik", + "1 dosya daha", + "{0} dosya daha", + "Bu sayfa web'den dosya yüklüyor: {0}. Bu dosyalar getirilmez.", + "Kod olarak korunur, böylece sayfa duyarlı olanlar dahil kendi betiklerini ve stil kurallarını korur. Web'den yüklediği dosyalar her iki durumda da getirilmez.", + "Öğe olarak, sayfa şu kaynaktan yüklediği dosyalar olmadan gelir: {0}. Bu yüzden görünümünün veya davranışının bir kısmı eksik olabilir.", + "Kod olarak korunur, çünkü {0} sayfadan 1 tanesi web'den dosya yüklüyor. Kod olarak sayfalar duyarlı olanlar dahil kendi betiklerini ve stil kurallarını korur; bu dosyalar her iki durumda da getirilmez.", + "Öğe olarak, {0} sayfadan 1 tanesi şu kaynaktan yüklediği dosyalar olmadan gelir: {1}. Bu yüzden görünümünün veya davranışının bir kısmı eksik olabilir.", + "Kod olarak korunur, çünkü {1} sayfadan {0} tanesi web'den dosya yüklüyor. Kod olarak sayfalar duyarlı olanlar dahil kendi betiklerini ve stil kurallarını korur; bu dosyalar her iki durumda da getirilmez.", + "Öğe olarak, {1} sayfadan {0} tanesi şu kaynaklardan yükledikleri dosyalar olmadan gelir: {2}. Bu yüzden görünümlerinin veya davranışlarının bir kısmı eksik olabilir.", + "Sayfanın betiğinin oluşturduğu içerik için 1 stil kuralı korundu.", + "Sayfanın betiğinin oluşturduğu içerik için {0} stil kuralı korundu.", + "Sayfanın betiğinin oluşturduğu içerik için 1 stil kuralı, dönüştürülen öğelerin onu kullanıp kullanmadığı denetlenmeden korundu: denetim çok uzun sürdü, bu yüzden tüm kurallar korundu.", + "Sayfanın betiğinin oluşturduğu içerik için {0} stil kuralı, dönüştürülen öğelerin hangilerini kullandığı denetlenmeden korundu: denetim çok uzun sürdü, bu yüzden tüm kurallar korundu.", + "1 stil kuralı daha dışarıda bırakıldı: bir betik için en fazla {1} kural ve {2} KiB korunur.", + "{0} stil kuralı daha dışarıda bırakıldı: bir betik için en fazla {1} kural ve {2} KiB korunur.", + "Sayfanın betiğinin oluşturduğu içerik için korunan stil kuralı, sayfanın kodu çok büyük olacağı için dışarıda bırakıldı.", + "Sayfanın betiğinin oluşturduğu içerik için korunan {0} stil kuralı, sayfanın kodu çok büyük olacağı için dışarıda bırakıldı.", + "Sayfanın stil sayfasındaki 1 yazı tipi veya kayıtlı özellik, site adını zaten kullandığı için dışarıda bırakıldı.", + "Sayfanın stil sayfasındaki {0} yazı tipi veya kayıtlı özellik, site adlarını zaten kullandığı için dışarıda bırakıldı.", + "{0} dosya dışa aktarıldı.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/uk.ts b/frontend/src/i18n/locales/uk.ts index ee962a0c..c9ef14aa 100644 --- a/frontend/src/i18n/locales/uk.ts +++ b/frontend/src/i18n/locales/uk.ts @@ -3028,4 +3028,59 @@ export default [ "Не залишено: {0} без змін.", "Елемент змінено в іншому місці, тому пробу скасовано.", "Зміну відхилено.", + "Показати маркери аудиту", + "Показувати маркери аудиту на сторінці", + "Ставить невеликий маркер на кожен елемент цієї сторінки, який має проблему. Натисніть маркер, щоб вибрати елемент.", + "1 проблема не має елемента, тому не має маркера.", + "Проблем без елемента: {0}, тому вони не мають маркерів.", + "Маркери намальовано на перших {0} з {1} елементів із проблемами на цій сторінці.", + "1 проблема в елементі {0}", + "Проблем в елементі {1}: {0}", + "Проблеми в елементі {0}", + "Не вдалося виконати аудит, тому маркери аудиту приховано.", + "Маркери аудиту ввімкнено: кожен елемент цієї сторінки з проблемою показує маркер.", + "Маркери аудиту вимкнено.", + "Куди зберігаються експортовані файли", + "Папка «Завантаження»", + "Папка, яку ви виберете", + "Вибрати папку...", + "Папку ще не вибрано.", + "Питати щоразу", + "Усі завантаження з редактора дотримуються цього вибору: «Експорт статичного сайту», «Завантажити проєкт .fweb», QR-коди й експорт зображень. З «Питати щоразу» кожен файл питає, куди його зберегти. Якщо вибрану папку не вдається використати під час збереження файлу, файл потрапляє до «Завантаження», і сповіщення про це повідомляє.", + "У браузері місце для завантажень вибирає сам браузер.", + "Вибрати іншу папку", + "Вибрати папку для збереження експортованих файлів", + "Збереження {0}...", + "Не вдалося зберегти {0} у {1}. Переконайтеся, що папка існує й має вільне місце, а тоді повторіть спробу.", + "Вибраної папки {0} немає або в неї не можна записувати, тому {1} збережено в {2}.", + "Нічого не збережено.", + "{0} і {1}", + "{0}, {1}", + "{0} і ще 1 хост", + "{0} та інші хости ({1})", + "Файли з {0} не перенесено, тому частина оформлення або поведінки може бути відсутня.", + "1 таблиця стилів з {0}", + "таблиці стилів з {1} ({0})", + "1 скрипт з {0}", + "скрипти з {1} ({0})", + "ще 1 файл", + "ще файли ({0})", + "Ця сторінка завантажує файли з інтернету: {0}. Ці файли не переносяться.", + "Залишено як код, тому сторінка зберігає власні скрипти й правила стилів, зокрема адаптивні. Файли, які вона завантажує з інтернету, не переносяться в жодному з варіантів.", + "Як елементи сторінка прийде без файлів, які вона завантажує з {0}, тому частина її оформлення або поведінки може бути відсутня.", + "Залишено як код, бо 1 з {0} сторінок завантажує файли з інтернету. Як код сторінки зберігають власні скрипти й правила стилів, зокрема адаптивні; ці файли не переносяться в жодному з варіантів.", + "Як елементи 1 з {0} сторінок прийде без файлів, які вона завантажує з {1}, тому частина її оформлення або поведінки може бути відсутня.", + "Залишено як код, бо сторінок, що завантажують файли з інтернету: {0} з {1}. Як код сторінки зберігають власні скрипти й правила стилів, зокрема адаптивні; ці файли не переносяться в жодному з варіантів.", + "Як елементи сторінки ({0} з {1}) прийдуть без файлів, які вони завантажують з {2}, тому частина їхнього оформлення або поведінки може бути відсутня.", + "Збережено правило стилю для вмісту, який будує скрипт сторінки.", + "Збережено правил стилю для вмісту, який будує скрипт сторінки: {0}.", + "Збережено правило стилю для вмісту, який будує скрипт сторінки, без перевірки, чи використовують його перетворені елементи: перевірка тривала задовго, тому збережено всі правила.", + "Збережено правил стилю для вмісту, який будує скрипт сторінки: {0}, без перевірки, які з них використовують перетворені елементи: перевірка тривала задовго, тому збережено всі правила.", + "Пропущено ще одне правило стилю: для скрипту зберігається не більше {1} правил і {2} КіБ.", + "Пропущено ще правил стилю: {0}. Для скрипту зберігається не більше {1} правил і {2} КіБ.", + "Правило стилю, збережене для вмісту скрипту сторінки, пропущено, бо код сторінки став би завеликим.", + "Правила стилю, збережені для вмісту скрипту сторінки ({0}), пропущено, бо код сторінки став би завеликим.", + "Шрифт або зареєстровану властивість із таблиці стилів сторінки пропущено, бо сайт уже використовує цю назву.", + "Пропущено шрифтів або зареєстрованих властивостей із таблиці стилів сторінки: {0}, бо сайт уже використовує ці назви.", + "Експортовано файлів: {0}.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/vi.ts b/frontend/src/i18n/locales/vi.ts index bd8e57bf..fde8fcb1 100644 --- a/frontend/src/i18n/locales/vi.ts +++ b/frontend/src/i18n/locales/vi.ts @@ -3028,4 +3028,59 @@ export default [ "Chưa giữ: {0} không thay đổi.", "Phần tử đã được thay đổi ở nơi khác, nên bản thử đã bị bỏ.", "Thay đổi đã bị từ chối.", + "Hiện điểm đánh dấu kiểm toán", + "Hiện điểm đánh dấu kiểm toán trên trang", + "Đặt một điểm đánh dấu nhỏ lên mỗi phần tử của trang này có vấn đề. Nhấp vào một điểm đánh dấu để chọn phần tử đó.", + "1 vấn đề không có phần tử, nên không có điểm đánh dấu.", + "{0} vấn đề không có phần tử, nên không có điểm đánh dấu.", + "Điểm đánh dấu được vẽ trên {0} phần tử đầu tiên trong số {1} phần tử có vấn đề trên trang này.", + "1 vấn đề trên {0}", + "{0} vấn đề trên {1}", + "Các vấn đề trên {0}", + "Không thể chạy kiểm toán, nên các điểm đánh dấu kiểm toán bị ẩn.", + "Điểm đánh dấu kiểm toán đang bật: mỗi phần tử của trang này có vấn đề sẽ hiện một điểm đánh dấu.", + "Điểm đánh dấu kiểm toán đang tắt.", + "Nơi lưu các bản xuất", + "Thư mục Tải xuống", + "Một thư mục bạn chọn", + "Chọn thư mục...", + "Chưa chọn thư mục nào.", + "Hỏi mỗi lần", + "Mọi lượt tải xuống từ trình chỉnh sửa đều theo lựa chọn này: Xuất trang web tĩnh, Tải xuống dự án .fweb, mã QR và bản xuất hình ảnh. Với Hỏi mỗi lần, mỗi tệp sẽ hỏi nơi lưu. Nếu không dùng được thư mục đã chọn khi lưu tệp, tệp sẽ vào Tải xuống và thông báo sẽ nói rõ.", + "Trong trình duyệt, trình duyệt quyết định nơi lưu tệp tải xuống.", + "Chọn thư mục khác", + "Chọn thư mục để lưu các bản xuất", + "Đang lưu {0}...", + "Không thể lưu {0} vào {1}. Hãy kiểm tra thư mục có tồn tại và còn dung lượng trống, rồi thử lại.", + "Thư mục đã chọn {0} không tồn tại hoặc không ghi được, nên {1} đã được lưu vào {2}.", + "Không có gì được lưu.", + "{0} và {1}", + "{0}, {1}", + "{0} và 1 máy chủ khác", + "{0} và {1} máy chủ khác", + "Các tệp từ {0} không được mang theo, nên một phần giao diện hoặc hoạt động có thể bị thiếu.", + "1 biểu định kiểu từ {0}", + "{0} biểu định kiểu từ {1}", + "1 tập lệnh từ {0}", + "{0} tập lệnh từ {1}", + "1 tệp khác", + "{0} tệp khác", + "Trang này tải tệp từ web: {0}. Các tệp này không được mang theo.", + "Giữ dưới dạng mã, nên trang giữ nguyên tập lệnh và quy tắc kiểu của riêng nó, kể cả các quy tắc đáp ứng. Các tệp trang tải từ web không được mang theo trong cả hai cách.", + "Dưới dạng phần tử, trang sẽ vào mà không có các tệp nó tải từ {0}, nên một phần giao diện hoặc hoạt động có thể bị thiếu.", + "Giữ dưới dạng mã, vì 1 trong {0} trang tải tệp từ web. Dưới dạng mã, các trang giữ nguyên tập lệnh và quy tắc kiểu của riêng chúng, kể cả các quy tắc đáp ứng; các tệp đó không được mang theo trong cả hai cách.", + "Dưới dạng phần tử, 1 trong {0} trang sẽ vào mà không có các tệp nó tải từ {1}, nên một phần giao diện hoặc hoạt động có thể bị thiếu.", + "Giữ dưới dạng mã, vì {0} trong {1} trang tải tệp từ web. Dưới dạng mã, các trang giữ nguyên tập lệnh và quy tắc kiểu của riêng chúng, kể cả các quy tắc đáp ứng; các tệp đó không được mang theo trong cả hai cách.", + "Dưới dạng phần tử, {0} trong {1} trang sẽ vào mà không có các tệp chúng tải từ {2}, nên một phần giao diện hoặc hoạt động có thể bị thiếu.", + "Đã giữ 1 quy tắc kiểu cho nội dung mà tập lệnh của trang tạo ra.", + "Đã giữ {0} quy tắc kiểu cho nội dung mà tập lệnh của trang tạo ra.", + "Đã giữ 1 quy tắc kiểu cho nội dung mà tập lệnh của trang tạo ra mà không kiểm tra xem các phần tử đã chuyển có dùng nó không: việc kiểm tra mất quá lâu, nên mọi quy tắc đều được giữ.", + "Đã giữ {0} quy tắc kiểu cho nội dung mà tập lệnh của trang tạo ra mà không kiểm tra các phần tử đã chuyển dùng quy tắc nào: việc kiểm tra mất quá lâu, nên mọi quy tắc đều được giữ.", + "Đã bỏ thêm 1 quy tắc kiểu: mỗi tập lệnh chỉ giữ tối đa {1} quy tắc và {2} KiB.", + "Đã bỏ thêm {0} quy tắc kiểu: mỗi tập lệnh chỉ giữ tối đa {1} quy tắc và {2} KiB.", + "Đã bỏ quy tắc kiểu được giữ cho nội dung mà tập lệnh của trang tạo ra, vì mã của trang sẽ quá lớn.", + "Đã bỏ {0} quy tắc kiểu được giữ cho nội dung mà tập lệnh của trang tạo ra, vì mã của trang sẽ quá lớn.", + "Đã bỏ 1 phông chữ hoặc thuộc tính đã đăng ký từ biểu định kiểu của trang, vì trang web đã dùng tên đó.", + "Đã bỏ {0} phông chữ hoặc thuộc tính đã đăng ký từ biểu định kiểu của trang, vì trang web đã dùng các tên đó.", + "Đã xuất {0} tệp.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 326304de..e676f2d4 100644 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3028,4 +3028,59 @@ export default [ "未保留:{0} 未更改。", "该元素已在别处更改,因此已放弃试用。", "更改被拒绝。", + "显示审计标记", + "在页面上显示审计标记", + "在此页面上每个有问题的元素上放一个小标记。点击标记即可选择该元素。", + "1 个问题没有对应元素,因此没有标记。", + "{0} 个问题没有对应元素,因此没有标记。", + "此页面上有问题的元素共 {1} 个,标记只画在前 {0} 个上。", + "{0} 上有 1 个问题", + "{1} 上有 {0} 个问题", + "{0} 上的问题", + "无法运行审计,因此已隐藏审计标记。", + "审计标记已开启:此页面上每个有问题的元素都会显示一个标记。", + "审计标记已关闭。", + "导出文件的保存位置", + "“下载”文件夹", + "你选择的文件夹", + "选择文件夹...", + "尚未选择文件夹。", + "每次询问", + "编辑器中的所有下载都遵循此选择:“导出静态站点”“下载 .fweb 项目”、二维码和图片导出。选择“每次询问”时,每个文件都会询问保存位置。如果保存文件时无法使用所选文件夹,文件会保存到“下载”文件夹,通知中会说明。", + "在浏览器中,下载保存到哪里由浏览器决定。", + "选择其他文件夹", + "选择导出文件的保存文件夹", + "正在保存 {0}...", + "无法将 {0} 保存到 {1}。请检查该文件夹是否存在并有可用空间,然后重试。", + "所选文件夹 {0} 不存在或无法写入,因此已将 {1} 保存到 {2}。", + "未保存任何内容。", + "{0} 和 {1}", + "{0}、{1}", + "{0} 及另外 1 个主机", + "{0} 及另外 {1} 个主机", + "来自 {0} 的文件没有带过来,因此部分外观或行为可能缺失。", + "来自 {0} 的 1 个样式表", + "来自 {1} 的 {0} 个样式表", + "来自 {0} 的 1 个脚本", + "来自 {1} 的 {0} 个脚本", + "另外 1 个文件", + "另外 {0} 个文件", + "此页面从网络加载文件:{0}。这些文件不会带过来。", + "保留为代码,页面因此保留自己的脚本和样式规则,包括响应式规则。无论哪种方式,它从网络加载的文件都不会带过来。", + "以元素导入时,页面不会带上它从 {0} 加载的文件,因此部分外观或行为可能缺失。", + "保留为代码,因为 {0} 个页面中有 1 个从网络加载文件。作为代码,页面保留自己的脚本和样式规则,包括响应式规则;无论哪种方式,这些文件都不会带过来。", + "以元素导入时,{0} 个页面中有 1 个不会带上它从 {1} 加载的文件,因此部分外观或行为可能缺失。", + "保留为代码,因为 {1} 个页面中有 {0} 个从网络加载文件。作为代码,页面保留自己的脚本和样式规则,包括响应式规则;无论哪种方式,这些文件都不会带过来。", + "以元素导入时,{1} 个页面中有 {0} 个不会带上它们从 {2} 加载的文件,因此部分外观或行为可能缺失。", + "为页面脚本构建的内容保留了 1 条样式规则。", + "为页面脚本构建的内容保留了 {0} 条样式规则。", + "为页面脚本构建的内容保留了 1 条样式规则,未检查转换后的元素是否使用它:检查耗时过长,因此保留了所有规则。", + "为页面脚本构建的内容保留了 {0} 条样式规则,未检查转换后的元素使用了其中哪些:检查耗时过长,因此保留了所有规则。", + "又省略了 1 条样式规则:每个脚本最多保留 {1} 条规则和 {2} KiB。", + "又省略了 {0} 条样式规则:每个脚本最多保留 {1} 条规则和 {2} KiB。", + "为页面脚本构建的内容保留的样式规则被省略了,因为页面代码会过大。", + "为页面脚本构建的内容保留的 {0} 条样式规则被省略了,因为页面代码会过大。", + "页面样式表中的 1 个字体或注册属性被省略了,因为网站已在使用它的名称。", + "页面样式表中的 {0} 个字体或注册属性被省略了,因为网站已在使用它们的名称。", + "已导出 {0} 个文件。", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index d746332f..e1fc126d 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -3028,4 +3028,59 @@ export default [ "未保留:{0} 未變更。", "此元素已在別處變更,因此已放棄試用。", "變更遭到拒絕。", + "顯示稽核標記", + "在頁面上顯示稽核標記", + "在此頁面上每個有問題的元素上放一個小標記。按一下標記即可選取該元素。", + "1 個問題沒有對應元素,因此沒有標記。", + "{0} 個問題沒有對應元素,因此沒有標記。", + "此頁面上有問題的元素共 {1} 個,標記只畫在前 {0} 個上。", + "{0} 上有 1 個問題", + "{1} 上有 {0} 個問題", + "{0} 上的問題", + "無法執行稽核,因此已隱藏稽核標記。", + "稽核標記已開啟:此頁面上每個有問題的元素都會顯示一個標記。", + "稽核標記已關閉。", + "匯出檔案的儲存位置", + "「下載」資料夾", + "你選擇的資料夾", + "選擇資料夾...", + "尚未選擇資料夾。", + "每次詢問", + "編輯器中的所有下載都會依照此選擇:「匯出靜態網站」「下載 .fweb 專案」、QR 碼和圖片匯出。選擇「每次詢問」時,每個檔案都會詢問儲存位置。如果儲存檔案時無法使用所選資料夾,檔案會儲存到「下載」資料夾,通知中會說明。", + "在瀏覽器中,下載儲存到哪裡由瀏覽器決定。", + "選擇其他資料夾", + "選擇匯出檔案的儲存資料夾", + "正在儲存 {0}...", + "無法將 {0} 儲存到 {1}。請檢查該資料夾是否存在並有可用空間,然後再試一次。", + "所選資料夾 {0} 不存在或無法寫入,因此已將 {1} 儲存到 {2}。", + "未儲存任何內容。", + "{0} 和 {1}", + "{0}、{1}", + "{0} 及另外 1 個主機", + "{0} 及另外 {1} 個主機", + "來自 {0} 的檔案沒有帶過來,因此部分外觀或行為可能缺失。", + "來自 {0} 的 1 個樣式表", + "來自 {1} 的 {0} 個樣式表", + "來自 {0} 的 1 個指令碼", + "來自 {1} 的 {0} 個指令碼", + "另外 1 個檔案", + "另外 {0} 個檔案", + "此頁面從網路載入檔案:{0}。這些檔案不會帶過來。", + "保留為程式碼,頁面因此保留自己的指令碼和樣式規則,包括響應式規則。無論哪種方式,它從網路載入的檔案都不會帶過來。", + "以元素匯入時,頁面不會帶上它從 {0} 載入的檔案,因此部分外觀或行為可能缺失。", + "保留為程式碼,因為 {0} 個頁面中有 1 個從網路載入檔案。作為程式碼,頁面保留自己的指令碼和樣式規則,包括響應式規則;無論哪種方式,這些檔案都不會帶過來。", + "以元素匯入時,{0} 個頁面中有 1 個不會帶上它從 {1} 載入的檔案,因此部分外觀或行為可能缺失。", + "保留為程式碼,因為 {1} 個頁面中有 {0} 個從網路載入檔案。作為程式碼,頁面保留自己的指令碼和樣式規則,包括響應式規則;無論哪種方式,這些檔案都不會帶過來。", + "以元素匯入時,{1} 個頁面中有 {0} 個不會帶上它們從 {2} 載入的檔案,因此部分外觀或行為可能缺失。", + "為頁面指令碼建構的內容保留了 1 條樣式規則。", + "為頁面指令碼建構的內容保留了 {0} 條樣式規則。", + "為頁面指令碼建構的內容保留了 1 條樣式規則,未檢查轉換後的元素是否使用它:檢查耗時過長,因此保留了所有規則。", + "為頁面指令碼建構的內容保留了 {0} 條樣式規則,未檢查轉換後的元素使用了其中哪些:檢查耗時過長,因此保留了所有規則。", + "又省略了 1 條樣式規則:每個指令碼最多保留 {1} 條規則和 {2} KiB。", + "又省略了 {0} 條樣式規則:每個指令碼最多保留 {1} 條規則和 {2} KiB。", + "為頁面指令碼建構的內容保留的樣式規則被省略了,因為頁面程式碼會過大。", + "為頁面指令碼建構的內容保留的 {0} 條樣式規則被省略了,因為頁面程式碼會過大。", + "頁面樣式表中的 1 個字型或註冊屬性被省略了,因為網站已在使用它的名稱。", + "頁面樣式表中的 {0} 個字型或註冊屬性被省略了,因為網站已在使用它們的名稱。", + "已匯出 {0} 個檔案。", ] as readonly string[]; From 95e8d73ce6ca25397fd6402bd1d4e48fc131b5b8 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 17:08:09 -0500 Subject: [PATCH 07/38] fix(wave): an audit marker sits centred on the top right corner of its element and is placed in the same frame as a resize, the import review says which older warnings its outside list already covers and shows those once, kept rules scale a pixel line height with the page, a menu command that leaves a trial alone keeps the trial and gives focus back to its control, and a dialog closed after a menu no longer leaves the keys on the page --- backend/app/authoring_tools.py | 2 +- backend/app/site_import.py | 13 ++++++-- frontend/src/features/audit-markers.ts | 35 +++++++++++++++----- frontend/src/features/convert/measure.ts | 25 ++++++++++++++ frontend/src/features/library/site-import.ts | 2 +- frontend/src/features/library/types.ts | 2 +- frontend/src/features/try/choice-list.ts | 5 +-- frontend/src/features/try/index.ts | 32 ++++++++++++++++-- frontend/src/main.ts | 8 ++++- 9 files changed, 104 insertions(+), 20 deletions(-) diff --git a/backend/app/authoring_tools.py b/backend/app/authoring_tools.py index f2f8e071..80a91aa8 100644 --- a/backend/app/authoring_tools.py +++ b/backend/app/authoring_tools.py @@ -50,7 +50,7 @@ {'starter': IDENT, 'values': FIELD_VALUES, 'update_components': {'type': 'boolean', 'default': False}}, ['starter']), tool('library_import_html', 'Import a finished HTML page as one code section: style tags become its css, the first inline script its js, the body markup its html. Allows code sections on the site. One undo step; the result runs in the exported site, not on the canvas. With bring_in elements the open editor window then converts it to editable elements (a second undo step) and conversion holds its result sentence; with no window open it stays a code section and conversion says so.', {'html': {'type': 'string', 'minLength': 1, 'maxLength': 1048576}, 'css': {'type': 'string', 'maxLength': 262144}, 'name': {'type': 'string', 'maxLength': 120}, 'parent': NODE, 'page': NODE, 'index': {'type': 'integer', 'minimum': 0}, 'bring_in': BRING_IN}, ['html']), - tool('library_import_site', 'Import a static site from a zip (data: the .zip bytes as base64): every HTML file becomes a page holding one code section with its local stylesheets and first script, pictures and WOFF2 fonts are stored as assets, and links between the pages follow their new routes. action review (default) changes nothing and lists the pages with their routes, warnings and outside (the stylesheets and scripts the page loads from other hosts, in document order: kind, host and url, at most 20, with outsideMore counting the rest; they are named, never fetched, and do not come along), the assets, the skipped files with reasons, canReplace and the revision; show it to the person. action import adds them as new pages (mode new) or swaps the content of pages whose route matches (mode replace, only when the review says canReplace), in one undo step; pass the review\'s revision as expected_revision (the older name revision is still accepted) so a site changed since is refused. At most about 48 MiB of zip through this tool, 1,000 files outside node_modules, __MACOSX and dot folders (40,000 entries in all), 100 pages and 128 MiB unpacked. A zip of a project\'s source (package.json with no HTML page, .ts, .tsx, .jsx, .vue or .svelte files under its src folder or loaded by a page, a %PUBLIC_URL% placeholder, or a module script that imports a package by name with no import map) is refused: build it and zip the output folder. With bring_in elements the open editor window then converts the imported pages to editable elements (a second undo step) and conversion holds its result sentence; with no window open they stay code sections and conversion says so.', + tool('library_import_site', 'Import a static site from a zip (data: the .zip bytes as base64): every HTML file becomes a page holding one code section with its local stylesheets and first script, pictures and WOFF2 fonts are stored as assets, and links between the pages follow their new routes. action review (default) changes nothing and lists the pages with their routes, warnings and outside (the stylesheets and scripts the page loads from other hosts, in document order: kind, host and url, at most 20, with outsideMore counting the rest, and outsideWarnings giving the indexes of the warnings that outside names in full; they are named, never fetched, and do not come along), the assets, the skipped files with reasons, canReplace and the revision; show it to the person. action import adds them as new pages (mode new) or swaps the content of pages whose route matches (mode replace, only when the review says canReplace), in one undo step; pass the review\'s revision as expected_revision (the older name revision is still accepted) so a site changed since is refused. At most about 48 MiB of zip through this tool, 1,000 files outside node_modules, __MACOSX and dot folders (40,000 entries in all), 100 pages and 128 MiB unpacked. A zip of a project\'s source (package.json with no HTML page, .ts, .tsx, .jsx, .vue or .svelte files under its src folder or loaded by a page, a %PUBLIC_URL% placeholder, or a module script that imports a package by name with no import map) is refused: build it and zip the output folder. With bring_in elements the open editor window then converts the imported pages to editable elements (a second undo step) and conversion holds its result sentence; with no window open they stay code sections and conversion says so.', {'data': {'type': 'string', 'minLength': 4, 'maxLength': 67108864}, 'action': {'type': 'string', 'enum': ['review', 'import'], 'default': 'review'}, 'mode': {'type': 'string', 'enum': ['new', 'replace'], 'default': 'new'}, 'bring_in': BRING_IN, 'expected_revision': {**REVISION, 'description': 'The revision the review returned. A site changed since then is refused without changing anything.'}, 'revision': {'type': 'integer', 'minimum': 0, 'description': 'Older name for expected_revision, still accepted; expected_revision wins when both are given.'}}, ['data'], destructive=True), tool('send_to_formpublisher', 'Send the open site to FormPublisher on this computer, as File > Send to FormPublisher does: delivered "live" when FormPublisher is running (returns its site id and revision), or "inbox" with the path of the zip it will import next time it runs. Also returns warnings: the export\'s own warning strings, the same as export_site gives. Does not change the site.', {'locale': {'type': 'string', 'maxLength': 40}}), diff --git a/backend/app/site_import.py b/backend/app/site_import.py index 51544deb..79600395 100644 --- a/backend/app/site_import.py +++ b/backend/app/site_import.py @@ -601,6 +601,7 @@ def _page(site: Site, path: str, body: bytes, kit_script) -> dict: missing: set = set() warnings: list[str] = [] outside_scripts, outside_styles = set(), set() + named_scripts = named_styles = True site.used, site.room, site.overflow, site.loops, site.deep, site.outside, site.listing = set(), CSS_CAP, False, set(), set(), [], [] title = TITLE.search(document) title = re.sub(r'\s+', ' ', unescape(title.group(1))).strip()[:200] if title else '' @@ -631,6 +632,7 @@ def _page(site: Site, path: str, body: bytes, kit_script) -> dict: site.listing.append(('script', source)) if found is None: outside_scripts.add(source[:120]) + named_scripts = named_scripts and outside_file('script', source) is not None elif found[0] in site.files and site.files[found[0]][0] == 'script': content = _text(site.files[found[0]][1]) if content.strip(): @@ -650,6 +652,7 @@ def _page(site: Site, path: str, body: bytes, kit_script) -> dict: if found is None: if href.strip() and block.start() < body_at: outside_styles.add(href[:120]) + named_styles = named_styles and outside_file('stylesheet', href) is not None elif found[0] in site.files and site.files[found[0]][0] == 'style': inlined.add(whole) if not site.take(found[0]): @@ -672,8 +675,11 @@ def _page(site: Site, path: str, body: bytes, kit_script) -> dict: warnings.append(f'The script was left out: {error}') if foreign: warnings.append(left_out_scripts(foreign)) - for found, noun, where in ((outside_scripts, 'external script', ''), (outside_styles, 'external stylesheet', ' in the page head')): + covered = [] + for found, noun, where, named in ((outside_scripts, 'external script', '', named_scripts), (outside_styles, 'external stylesheet', ' in the page head', named_styles)): if found: + if named and not more: + covered.append(len(warnings)) shown = sorted(found) warnings.append(f'{len(shown)} {noun}{"s" if len(shown) != 1 else ""}{where} {"is" if len(shown) == 1 else "are"} not brought along: {", ".join(shown[:5])}{"..." if len(shown) > 5 else ""}.') if site.loops: @@ -695,7 +701,7 @@ def _page(site: Site, path: str, body: bytes, kit_script) -> dict: warnings.append(f'{len(shown)} reference{"s" if len(shown) != 1 else ""} point{"" if len(shown) != 1 else "s"} at files that were skipped or are not in the archive: {", ".join(item[:80] for item in shown[:5])}{"..." if len(shown) > 5 else ""}.') name = (title or posixpath.basename(path).rsplit('.', 1)[0] or 'Imported page')[:120] return {'file': path, 'name': name, 'title': title, 'description': description, 'html': markup, 'css': css, 'js': script.strip(), 'module': module and bool(script.strip()), 'warnings': warnings, 'overflow': site.overflow, - 'outside': outside, 'outsideMore': more} + 'outside': outside, 'outsideMore': more, 'outsideWarnings': covered} def _emptiable(site: dict, root: str) -> bool: @@ -778,7 +784,8 @@ def plan(archive: dict, site: dict, kit_script) -> dict: def review(result: dict) -> dict: pages = [{'file': p['file'], 'name': p['name'], 'title': p['title'], 'description': p['description'], 'route': p['route'], 'newRoute': p['newRoute'], - 'replaces': p['replaces'], 'bytes': p['bytes'], 'warnings': p['warnings'], 'outside': p['outside'], 'outsideMore': p['outsideMore']} for p in result['pages']] + 'replaces': p['replaces'], 'bytes': p['bytes'], 'warnings': p['warnings'], 'outside': p['outside'], 'outsideMore': p['outsideMore'], + 'outsideWarnings': p['outsideWarnings']} for p in result['pages']] matched = [p['replaces'] for p in pages if p['replaces']] blocked = [m['name'] for m in matched if not m['safe']] reason = '' diff --git a/frontend/src/features/audit-markers.ts b/frontend/src/features/audit-markers.ts index 757d7b7f..6c1a9f47 100644 --- a/frontend/src/features/audit-markers.ts +++ b/frontend/src/features/audit-markers.ts @@ -14,7 +14,8 @@ export interface AuditMarkersHost { page: () => string; editing: () => boolean; busy: () => boolean; - pick: (id: string, message: string, again: () => void) => void; + pick: (id: string, message: string, again: () => void) => string; + unsay: (line: string) => void; rescue: () => (HTMLElement | null | undefined)[]; status: (message: string, error?: boolean) => void; } @@ -39,7 +40,7 @@ const MAX_TEXT = 300; const MAX_LINES = 20; const MAX_NAME = 80; const SIZE = 20; -const INSET = 2; +const GONE_MS = 5000; const RANK: Record = { error: 3, warning: 2, info: 1 }; const SHAPE = ['info', 'info', 'warning', 'error']; @@ -59,6 +60,9 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { let answer: Answer | null = null; let failed = false; let failedAt = ''; + let picked = ''; + let pickedAt = 0; + let line = ''; let said = false; let out = false; let due = false; @@ -88,7 +92,7 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { box.dataset.ownKeys = ''; const boxLabel = element('label', 'checkbox-field'); boxLabel.append(box, element('span', '', 'Show audit markers on the page')); - const about = element('p', 'micro', 'Puts a small marker on each element of this page that has an issue. Click a marker to select the element.'); + const about = element('p', 'micro', 'Puts a small marker on each element of this page that has an issue. Markers show on the page when this dialog is closed. Click a marker to select the element.'); const note = element('p', 'micro fw-audit-note'); const row = element('div', 'fw-audit-switch'); row.append(boxLabel, about, note); @@ -196,7 +200,15 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { function activate(id: string): void { const dot = shown.find(item => item.id === id); if (!dot || blocked()) return; - host.pick(id, dot.messages[0] || '', () => activate(id)); + if (!current?.site.nodes[id]) { + shown = shown.filter(item => item.id !== id); + fill(); + place(); + return; + } + line = host.pick(id, dot.messages[0] || '', () => activate(id)); + picked = id; + pickedAt = performance.now(); const after = shown.find(item => item.id === id); if (after && after.messages.length > 1) { open = id; @@ -237,6 +249,7 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { } const still = map.still(); const seen = map.visible(); + const room = host.stage.getBoundingClientRect(); const active = focused(); const nodes = [...layer.children] as HTMLElement[]; const spots = nodes.map(node => { @@ -244,8 +257,9 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { const rect: Box | null = at ? bounds(at) : null; if (!rect) return ''; const corner = still.toParent(rect.left + rect.width, rect.top); - const left = Math.round(corner.x - SIZE - INSET), top = Math.round(corner.y + INSET); - return left >= seen.left && top >= seen.top && left + SIZE <= seen.left + seen.width && top + SIZE <= seen.top + seen.height ? `${left},${top}` : ''; + if (corner.x < seen.left - 0.5 || corner.y < seen.top - 0.5 || corner.x > seen.left + seen.width + 0.5 || corner.y > seen.top + seen.height + 0.5) return ''; + const left = Math.round(corner.x) - SIZE / 2, top = Math.round(corner.y) - SIZE / 2; + return left >= room.left && top >= room.top && left + SIZE <= room.right && top + SIZE <= room.bottom ? `${left},${top}` : ''; }); for (let index = 0; index < nodes.length; index++) { const node = nodes[index], id = node.dataset.key || '', spot = spots[index]; @@ -357,6 +371,8 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { function sync(next: EditorState): void { current = next; + if (picked && !next.site.nodes[picked] && line && performance.now() - pickedAt < GONE_MS) host.unsay(line); + if (picked && !next.site.nodes[picked]) picked = ''; if (!on) return; if (!valid() && failedAt !== `${next.site.id}:${next.revision}`) want(); if (answer) paint(); else poke(); @@ -380,8 +396,9 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { poke(); }; for (const type of ['pointerdown', 'pointerup', 'pointercancel', 'pointermove', 'keydown', 'keyup', 'click', 'focusin', 'input', 'change', 'scroll', 'transitionend']) window.addEventListener(type, watch, { capture: true, passive: true }); - window.addEventListener('resize', poke); - const sized = new ResizeObserver(poke); + const now = (): void => { if (on) place(); }; + window.addEventListener('resize', now); + const sized = new ResizeObserver(now); sized.observe(host.stage); sized.observe(host.frame); new MutationObserver(poke).observe(host.dialog, { attributes: true, attributeFilter: ['hidden'] }); @@ -392,7 +409,7 @@ export function installAuditMarkers(host: AuditMarkersHost): AuditMarkers { if (!at || !view) return; doc = at; for (const type of ['pointerdown', 'pointerup', 'pointercancel', 'pointermove', 'dblclick', 'focusout', 'keyup', 'scroll', 'load']) at.addEventListener(type, watch, { capture: true, passive: true }); - new view.ResizeObserver(poke).observe(at.documentElement); + new view.ResizeObserver(now).observe(at.documentElement); new view.MutationObserver(poke).observe(at.documentElement, { attributes: true, attributeFilter: ['data-fw-dragging', 'data-fw-holding'] }); poke(); }); diff --git a/frontend/src/features/convert/measure.ts b/frontend/src/features/convert/measure.ts index f3715a75..1c8c2a0d 100644 --- a/frontend/src/features/convert/measure.ts +++ b/frontend/src/features/convert/measure.ts @@ -217,6 +217,30 @@ function fillWindow(view: Window, frame: HTMLIFrameElement, root: Record, Element][]): void { + const doc = view.document; + for (const [styles, el] of entries) { + const written = styles['line-height']; + if (!written?.endsWith('px') || VOID_TAGS.has(el.localName)) continue; + const size = parseFloat(read(view, el, ['font-size'])['font-size']), height = parseFloat(written); + if (!(size > 0) || !(height > 0)) continue; + const probe = doc.createElement('fw-probe'); + probe.setAttribute('style', `display:block;font-size:${round(size * 2 + 3)}px`); + el.append(probe); + const inner = parseFloat(read(view, probe, ['line-height'])['line-height']); + probe.remove(); + const ratio = Math.round(height / size * 10000) / 10000; + if (Math.abs(inner - ratio * (size * 2 + 3)) < 0.6 && Math.abs(inner - height) > 0.6) styles['line-height'] = String(ratio); + } +} + export interface Kept { css: string; rules: number; all: boolean; over: number; clash: number } /** How long checking which rules the converted elements use may take before every rule is kept unchecked. */ @@ -600,6 +624,7 @@ export async function measure(source: Source, options: Options, only?: number): scriptWords(source.js, words); } fillWindow(view, original.frame, only === undefined ? rootStyles : null, sized); + lineRatios(view, [...(only === undefined ? [[rootStyles, original.doc.body] as [Record, Element]] : []), ...sized.map(([node, el]) => [node.styles, el] as [Record, Element])]); const scope = only === undefined ? options.scope : nodes.find(node => node.parent === ROOT)?.id; const hostScript = only !== undefined && options.keepScript && !!source.js.trim(); if (hostScript) scriptWords(source.js, words); diff --git a/frontend/src/features/library/site-import.ts b/frontend/src/features/library/site-import.ts index f6b8b848..e4da8c95 100644 --- a/frontend/src/features/library/site-import.ts +++ b/frontend/src/features/library/site-import.ts @@ -361,7 +361,7 @@ export class SiteImport { text(name, page.name); const replacing = this.mode === 'replace' && page.replaces; text(route, `${page.file} → ${replacing ? page.route : page.newRoute}`); - const notes = [replacing ? t('Replaces the content of {0}.', [page.replaces!.name]) : page.newRoute !== page.route ? t('{0} is taken, so it gets {1}.', [page.route, page.newRoute]) : '', ...page.warnings.map(item => t(item))].filter(Boolean); + const notes = [replacing ? t('Replaces the content of {0}.', [page.replaces!.name]) : page.newRoute !== page.route ? t('{0} is taken, so it gets {1}.', [page.route, page.newRoute]) : '', ...page.warnings.filter((_, index) => !page.outsideWarnings?.includes(index)).map(item => t(item))].filter(Boolean); text(meta, notes.join(' ')); meta.hidden = !notes.length; } diff --git a/frontend/src/features/library/types.ts b/frontend/src/features/library/types.ts index 0ee5e6f9..328d4d1d 100644 --- a/frontend/src/features/library/types.ts +++ b/frontend/src/features/library/types.ts @@ -24,7 +24,7 @@ export type LibResult = { root?: string; pages?: string[]; warnings?: string[]; export type SiteSkip = { file: string; reason: string }; /** A stylesheet or script a page loads from another host: named in the review, never fetched. */ export type SiteOutside = { kind: 'stylesheet' | 'script'; host: string; url: string }; -export type SitePage = { file: string; name: string; title: string; description: string; route: string; newRoute: string; replaces: { id: string; name: string; safe: boolean } | null; bytes: number; warnings: string[]; outside?: SiteOutside[]; outsideMore?: number }; +export type SitePage = { file: string; name: string; title: string; description: string; route: string; newRoute: string; replaces: { id: string; name: string; safe: boolean } | null; bytes: number; warnings: string[]; outside?: SiteOutside[]; outsideMore?: number; outsideWarnings?: number[] }; export type SiteReview = { pages: SitePage[]; assets: { count: number; bytes: number }; supportFiles: number; skipped: SiteSkip[]; ignored: number; canReplace: boolean; replaceNote: string; notes: string[]; revision: number }; /** POST /api/library/import-site: the batch state plus the pages made, assets stored and files skipped. */ export type SiteResult = { pages?: string[]; assets?: number; skipped?: SiteSkip[]; warnings?: string[]; message?: string }; diff --git a/frontend/src/features/try/choice-list.ts b/frontend/src/features/try/choice-list.ts index a8daaef9..4e4bb29f 100644 --- a/frontend/src/features/try/choice-list.ts +++ b/frontend/src/features/try/choice-list.ts @@ -57,6 +57,7 @@ export function installChoiceLists(kit: TryKit, options: TryOptions): void { const bar = (): HTMLElement | null => document.querySelector('[data-try-bar]'); const inBar = (node: Node | null): boolean => !!node && !!bar()?.contains(node); const live = (): boolean => !!trial && !trial.over; + const inMenus = (node: Node | null): boolean => node instanceof Element && !!node.closest('.fw-menubar, .fw-menu'); function aria(select: HTMLSelectElement): void { if (kit.enabled()) { @@ -286,13 +287,13 @@ export function installChoiceLists(kit: TryKit, options: TryOptions): void { function outside(event: Event): void { const target = event.target as Node; - if (!field || pop.contains(target) || field.select.contains(target) || inBar(target)) return; + if (!field || pop.contains(target) || field.select.contains(target) || inBar(target) || (live() && inMenus(target))) return; close(); } function moved(event: FocusEvent): void { const target = event.target as Node; - if (!field || pop.contains(target) || target === field.select || inBar(target)) return; + if (!field || pop.contains(target) || target === field.select || inBar(target) || (live() && inMenus(target))) return; if (live()) { if (!trial!.pending) trial!.revert(); return; } hide(); } diff --git a/frontend/src/features/try/index.ts b/frontend/src/features/try/index.ts index 393f2f25..169c8598 100644 --- a/frontend/src/features/try/index.ts +++ b/frontend/src/features/try/index.ts @@ -5,13 +5,15 @@ import { installChoiceLists } from './choice-list'; import type { LayerFrame, Trial, TrialEnd, TrialOwner, TryKit, TryOptions } from './types'; const STORE = 'formweb.try-choices'; -const PASS = new Set(['edit.copy', 'file.save', 'view.search', 'view.try-choices', 'view.audit-markers']); +const PASS = new Set(['edit.copy', 'file.save', 'view.search', 'view.try-choices', 'view.audit-markers', 'view.hover-outline']); const SURFACE = '.fw-menubar, .fw-menu, .fw-search-pop, [data-cmd]'; const MENU = '.fw-menubar, .fw-menu, .fw-search-pop'; +const MENUS = '.fw-menubar, .fw-menu'; const LANDING_MS = 30000; const AIMED_MS = 15000; type Live = { trial: Trial; owner: TrialOwner; node: string; scope: string; base: string; value: string | null; pending: boolean; over: boolean; detached: boolean; end(how: TrialEnd, message?: string): void }; +type Parked = { entry: Live; back: HTMLElement }; function ended(owner: TrialOwner, how: TrialEnd): void { try { owner.ended(how); } catch (error) { console.error(error); } @@ -21,6 +23,11 @@ function within(target: EventTarget | null, selector: string): boolean { return target instanceof Element && !!target.closest(selector); } +function inMenubar(target: EventTarget | null): boolean { + if (within(target, '.fw-menubar')) return true; + return within(target, '.fw-menu') && !!document.querySelector('.fw-menubar [aria-expanded="true"]'); +} + function readOn(): boolean { try { return localStorage.getItem(STORE) !== '0'; } catch { return true; } } @@ -39,6 +46,7 @@ export function installTry(options: TryOptions): TryKit { let liveScope = ''; let watching = 0; let aimed = 0; + let parked: Parked | null = null; let said = ''; let swallowing = false; let repeat = false; @@ -64,6 +72,17 @@ export function installTry(options: TryOptions): TryKit { const hidden = (entry: Live): boolean => !entry.owner.anchor.isConnected || entry.owner.anchor.getClientRects().length === 0; + const owns = (entry: Live, target: EventTarget | null): boolean => target instanceof Node + && (bar.element.contains(target) || entry.owner.anchor.contains(target) || (entry.owner.inside?.() ?? []).some(part => part.contains(target))); + + const unpark = (spot: Parked): void => { + const now = document.activeElement; + if (!document.hasFocus() || (now && now !== document.body && !(within(now, MENUS) && now.getClientRects().length === 0))) return; + if (parked === spot) parked = null; + const back = [spot.back, spot.entry.owner.anchor, ...(spot.entry.owner.inside?.() ?? [])].find(node => node.isConnected && node.getClientRects().length > 0 && !(node as HTMLButtonElement).disabled && !node.closest('[inert]')); + back?.focus({ preventScroll: true }); + }; + const check = (fromSync: boolean): void => { const scope = options.scope(); const editing = options.editing(); @@ -85,6 +104,7 @@ export function installTry(options: TryOptions): TryKit { watching = 0; if (!current && !lives.size) return; check(false); + if (parked && parked.entry === current && !current.pending) unpark(parked); if (current || lives.size) watching = requestAnimationFrame(tick); }; watching = requestAnimationFrame(tick); @@ -208,7 +228,12 @@ export function installTry(options: TryOptions): TryKit { if (!entry || entry.over || entry.pending) return; const target = event.target as Node | null; if (!target || target === document.body || within(target, '.fw-search-pop')) return; - if (bar.element.contains(target) || entry.owner.anchor.contains(target) || (entry.owner.inside?.() ?? []).some(part => part.contains(target))) return; + if (owns(entry, target)) { parked = null; return; } + if (inMenubar(target)) { + if (parked?.entry !== entry) parked = { entry, back: owns(entry, event.relatedTarget) ? event.relatedTarget as HTMLElement : entry.owner.anchor }; + return; + } + parked = null; const shown = entry.value !== null; entry.trial.revert(); aimed = shown && within(target, SURFACE) ? performance.now() : 0; @@ -252,6 +277,7 @@ export function installTry(options: TryOptions): TryKit { }, begin(owner: TrialOwner): Trial { aimed = 0; + parked = null; retire(); const entry = create(owner); current = entry; @@ -283,6 +309,8 @@ export function installTry(options: TryOptions): TryKit { draw(); }, intercept(command: string): boolean { + const spot = parked; + if (spot && within(document.activeElement, MENUS)) setTimeout(() => unpark(spot)); if (PASS.has(command)) return false; const undo = command === 'edit.undo'; const wasAimed = aimed && performance.now() - aimed < AIMED_MS; diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 50cce785..138ee320 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -1079,7 +1079,7 @@ const auditMarkers = installAuditMarkers({ editing: () => !preview && !fullPreview.isOpen && !demoPreview.isOpen && !featureStudio.opened && !!home.root.hidden, busy: () => tryKit.busy(), pick: (id, message, again) => { const page = state().site.pages.find(item => descendants(item.root).has(id)); - if (!page || !state().site.nodes[id]) return; + if (!page || !state().site.nodes[id]) return ''; pageId = page.id; selectedId = id; update(state()); @@ -1088,7 +1088,9 @@ const auditMarkers = installAuditMarkers({ const line = t('Selected {0}: {1}', [currentNode().name, message]); status(line); notice.show(line, { error: true, action: { label: 'Show again', run: again } }); + return line; }, + unsay: line => { if (statusMessage.textContent === line) { status(''); notice.hide(); } }, rescue: () => [inspectorTabButtons.get(activeInspector), auditButton], status }); auditPane.append(auditSummary, auditMarkers.row, auditList); @@ -1905,6 +1907,10 @@ function closeDialog(): void { scrim.hidden = true; dialogMode = ''; lastFocus?.focus(); + if (document.activeElement === document.body) { + const tab = inspectorTabs.querySelector('button.active'); + (tab?.getClientRects().length ? tab : auditButton).focus({ preventScroll: true }); + } } async function createSite(name: string, starter: string): Promise { await replace('/api/new', { name, blank: true }); From 2f9df78cec9240cbfce8fc712e4a6e561dcb2eb5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 17:08:16 -0500 Subject: [PATCH 08/38] =?UTF-8?q?feat(search):=20Search=20properties=20lis?= =?UTF-8?q?ts=20what=20matches=20as=20text=20with=20its=20place,=20as=20in?= =?UTF-8?q?=20Fade=20up=20=C2=B7=20Motion=20>=20Presets,=20finds=20segment?= =?UTF-8?q?=20choices,=20list=20items=20and=20motion=20presets=20as=20well?= =?UTF-8?q?=20as=20fields,=20and=20no=20longer=20goes=20to=20a=20result=20?= =?UTF-8?q?or=20marks=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/commands/catalogue.ts | 2 +- frontend/src/features/inspector/search.ts | 226 ++++++++++------------ frontend/src/main.ts | 2 +- frontend/src/styles/inspector-search.css | 16 +- 4 files changed, 108 insertions(+), 138 deletions(-) diff --git a/frontend/src/commands/catalogue.ts b/frontend/src/commands/catalogue.ts index 6ef5719f..0f55ab71 100644 --- a/frontend/src/commands/catalogue.ts +++ b/frontend/src/commands/catalogue.ts @@ -100,7 +100,7 @@ const META: Record = { 'vector.grid.prefs': { description: 'Open the dialog for gridline spacing and subdivisions.' }, 'vector.outline': { description: 'Show the edited SVG as thin unfilled outlines without changing the document. Outside vector editing the key is Redo.', when: 'Use to inspect overlapping artwork.' }, 'view.search': { description: 'Open the command search.' }, - 'inspector.search': { description: 'Open the right panel and focus Search properties, which filters every inspector tab by label, section, CSS property or a synonym and jumps to the chosen field.', when: 'Use when the person looks for a property and does not know which tab holds it.' }, + 'inspector.search': { description: 'Open the right panel and focus Search properties, which lists the settings, list items, segment choices and motion presets of every inspector tab that match a label, section, CSS property, value or synonym, each with the tab and section where it is.', when: 'Use when the person looks for a property and does not know which tab holds it.' }, 'vector.lasso': { description: 'Lasso tool: drag a freehand loop to select the shapes (or anchors, in direct selection mode) inside it; Shift adds, Alt removes.' }, 'vector.wand': { description: 'Magic Wand tool: click a shape to select every shape in the same SVG with a similar fill, stroke, weight or opacity (tolerances in the Vector panel Select section).' }, 'vector.eyedropper': { description: 'Eyedropper tool: click a shape to copy its fill, stroke, weight, opacity and dash onto the selected shapes as one undo step.' }, diff --git a/frontend/src/features/inspector/search.ts b/frontend/src/features/inspector/search.ts index c6499a85..e72bf0fb 100644 --- a/frontend/src/features/inspector/search.ts +++ b/frontend/src/features/inspector/search.ts @@ -5,29 +5,31 @@ import { SYNONYMS } from './search-terms'; import '../../styles/inspector-search.css'; export interface SearchTab { id: string; button: HTMLElement; pane: HTMLElement } -export interface SearchOptions { after: HTMLElement; scroll: HTMLElement; tabs: SearchTab[]; select(id: string): void } +export interface SearchOptions { after: HTMLElement; scroll: HTMLElement; tabs: SearchTab[] } export interface InspectorSearch { focus(): void; clear(): void } interface Entry { key: string; group: string; - tab: string; - tabName: string; - sectionName: string; - isSection: boolean; + parent: string; + kind: 'section' | 'field' | 'choice'; name: string; + place: string; css: string; - target: HTMLElement; off: boolean; words: { name: string; prop: string; place: string }; } -interface Row { key: string; heading?: string; entry?: Entry } +interface Row { key: string; entry: Entry; value: number; order: number } const MAX_ROWS = 120; -const PULSE_MS = 1600; +const MAX_ENTRIES = 4000; +const MAX_CHOICES = 64; +const MAX_TEXT = 120; +const SEP = ' > '; const FIELDS = '.field, .checkbox-field, :scope > button, .inspect-actions > button'; +const OWNER = '.field, .checkbox-field'; const norm = (value: string): string => value.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim(); -const clean = (value: string | null | undefined): string => (value || '').replace(/\s+/g, ' ').trim(); +const clean = (value: string | null | undefined): string => (value || '').slice(0, MAX_TEXT * 4).replace(/\s+/g, ' ').trim().slice(0, MAX_TEXT); const GROUPS = SYNONYMS.map(group => group.map(norm)); export function sectionId(title: string): string { @@ -62,6 +64,7 @@ function rank(entry: Entry, token: string): number { if (name.includes(token)) return 2; if (prop.includes(token)) return 3; const own = ` ${name} ${prop}`; + if (entry.kind === 'choice') return place.includes(token) ? 5 : -1; if (token.length >= 2) { for (const group of GROUPS) { if (!group.some(member => member === token || member.startsWith(token))) continue; @@ -86,9 +89,7 @@ export function installInspectorSearch(options: SearchOptions): InspectorSearch input.type = 'text'; input.autocomplete = 'off'; input.spellcheck = false; - input.setAttribute('role', 'combobox'); - input.setAttribute('aria-autocomplete', 'list'); - input.setAttribute('aria-expanded', 'false'); + input.maxLength = MAX_TEXT; labelAttr(input, 'placeholder', 'Search properties'); labelAttr(input, 'aria-label', 'Search properties'); const clearButton = element('button', 'inspector-search-clear'); @@ -102,9 +103,12 @@ export function installInspectorSearch(options: SearchOptions): InspectorSearch const results = element('div', 'inspector-results'); results.hidden = true; + const note = element('p', 'inspector-results-note'); + note.id = 'inspector-results-note'; + label(note, 'Each result shows where to find it. Open that tab and section to use it.'); const list = element('div', 'inspector-results-list'); list.id = 'inspector-results-list'; - list.setAttribute('role', 'listbox'); + list.setAttribute('role', 'list'); const empty = element('p', 'inspector-results-empty'); empty.setAttribute('role', 'status'); empty.hidden = true; @@ -114,45 +118,61 @@ export function installInspectorSearch(options: SearchOptions): InspectorSearch more.hidden = true; label(more, 'Showing the first {0} results. Type more to narrow it down.', [MAX_ROWS]); labelAttr(more, 'title', 'Showing the first {0} results. Type more to narrow it down.', [MAX_ROWS]); - results.append(list, more, empty); - input.setAttribute('aria-controls', list.id); + results.append(note, list, more, empty); + input.setAttribute('aria-describedby', note.id); options.after.after(bar); options.scroll.before(results); - const entries = new Map(); let index: Entry[] = []; let dirty = true; let open = false; let queued = false; let savedTop = 0; - let activeKey = ''; - let pulsing: HTMLElement | null = null; - let pulseTimer = 0; - let picks: Entry[] = []; - let serial = 0; function build(): Entry[] { const found: Entry[] = []; - entries.clear(); for (const tab of options.tabs) { const tabName = clean(tab.button.textContent); const sections = new Map(); tab.pane.querySelectorAll('.inspector-section').forEach(section => { - if (!shown(section, tab.pane)) return; + if (found.length >= MAX_ENTRIES || !shown(section, tab.pane)) return; const head = section.querySelector(':scope > .section-title'); const sectionName = clean(head?.firstElementChild?.textContent); if (!head || !sectionName) return; + const where = `${tabName}${SEP}${sectionName}`; const place = norm(`${sectionName} ${tabName}`); const id = section.dataset.section || sectionId(sectionName); const nth = sections.get(id) || 0; sections.set(id, nth + 1); const base = `${tab.id}|${id}|${nth}`; - const add = (entry: Omit, prop: string): void => { - const made: Entry = { ...entry, group: base, tab: tab.id, tabName, sectionName, words: { name: norm(entry.name), prop: norm(prop), place } }; - found.push(made); - entries.set(made.key, made); + const add = (entry: Omit, prop: string, words = place): void => { + if (found.length < MAX_ENTRIES) found.push({ ...entry, group: base, words: { name: norm(entry.name), prop: norm(prop), place: words } }); }; - add({ key: `${base}|`, isSection: true, name: sectionName, css: '', target: head, off: false }, ''); + const mine = (root: HTMLElement, selector: string, owner: HTMLElement | null): T[] => + Array.from(root.querySelectorAll(selector)).filter(node => node.closest('.inspector-section') === section && node.closest(OWNER) === owner && shown(node, section)); + const choices = (parent: string, field: string, off: boolean, groups: HTMLElement[], selects: HTMLSelectElement[]): void => { + const at = field ? `${where}${SEP}${field}` : where; + const words = norm(`${field} ${sectionName} ${tabName}`); + const seen = new Map(); + const one = (name: string, value: string, disabled: boolean): void => { + if (!name) return; + const slug = `${parent}|c|${norm(value || name)}`; + const n = seen.get(slug) || 0; + seen.set(slug, n + 1); + add({ key: `${slug}|${n}`, kind: 'choice', parent, name, place: at, css: '', off: off || disabled }, value, words); + }; + for (const group of groups) { + Array.from(group.querySelectorAll('.fw-seg-btn')).slice(0, MAX_CHOICES).forEach(button => { + if (shown(button, group)) one(clean(button.textContent || button.getAttribute('aria-label')), clean(button.dataset.value), button.disabled); + }); + } + for (const select of selects) { + Array.from(select.options).slice(0, MAX_CHOICES).forEach(option => { + if (option.value && !option.hidden) one(clean(option.text), clean(option.value), select.disabled || option.disabled); + }); + } + }; + add({ key: `${base}|`, kind: 'section', parent: '', name: sectionName, place: where, css: '', off: false }, ''); const counts = new Map(); const done = new Map(); section.querySelectorAll(FIELDS).forEach(node => { @@ -169,7 +189,14 @@ export function installInspectorSearch(options: SearchOptions): InspectorSearch const seen = counts.get(slug) || 0; counts.set(slug, seen + 1); const control = controlOf(node) as (HTMLElement & { disabled?: boolean }) | null; - add({ key: `${base}|${slug}|${seen}`, isSection: false, name, css, target: node, off: !!control?.disabled }, prop); + const key = `${base}|${slug}|${seen}`; + const off = !!control?.disabled; + add({ key, kind: 'field', parent: '', name, place: where, css, off }, prop); + if (node.tagName !== 'BUTTON') choices(key, name, off, mine(node, '.fw-seg', node), mine(node, 'select[data-style]', node)); + }); + mine(section, '.fw-seg', null).forEach((group, at) => { + const head = group.previousElementSibling; + choices(`${base}|set|${at}`, head?.matches('.field-label') ? clean(head.textContent) : '', false, [group], []); }); }); } @@ -178,62 +205,47 @@ export function installInspectorSearch(options: SearchOptions): InspectorSearch function score(entry: Entry, tokens: string[]): number { let total = 0; + let own = entry.kind !== 'choice'; for (const token of tokens) { const best = rank(entry, token); if (best < 0) return -1; + if (best < 5) own = true; total += best; } - return total; + return own ? total : -1; } - function createRow(row: Row): HTMLElement { - if (row.heading !== undefined) { - const head = element('div', 'inspector-results-group'); - head.setAttribute('role', 'presentation'); - head.dataset.noI18n = ''; - return head; - } + function createRow(): HTMLElement { const node = element('div', 'inspector-result'); - node.setAttribute('role', 'option'); - node.id = `inspector-result-${++serial}`; + node.setAttribute('role', 'listitem'); + const words = element('span', 'inspector-result-text'); + words.dataset.noI18n = ''; const name = element('span', 'inspector-result-name'); - name.dataset.noI18n = ''; + const dot = element('span', 'inspector-result-dot'); + text(dot, ' · '); + const place = element('span', 'inspector-result-place'); + words.append(name, dot, place); const css = element('span', 'inspector-result-css'); css.dataset.noI18n = ''; const off = element('span', 'inspector-result-off'); label(off, 'Unavailable'); off.hidden = true; - node.append(name, css, off); - node.addEventListener('pointerdown', event => event.preventDefault()); - node.addEventListener('click', () => { const entry = entries.get(node.dataset.key || ''); if (entry) pick(entry); }); + node.append(words, css, off); return node; } function updateRow(node: HTMLElement, row: Row): void { - if (row.heading !== undefined) { text(node, row.heading); return; } - const entry = row.entry!; - const [name, css, off] = Array.from(node.children) as HTMLElement[]; + const entry = row.entry; + const [words, css, off] = Array.from(node.children) as HTMLElement[]; + const [name, , place] = Array.from(words.children) as HTMLElement[]; text(name, entry.name); + text(place, entry.place); text(css, entry.css); if (off.hidden === entry.off) off.hidden = !entry.off; - node.classList.toggle('is-off', entry.off); - node.classList.toggle('is-section', entry.isSection); - node.setAttribute('aria-label', `${entry.tabName}, ${entry.sectionName}${entry.isSection ? '' : `, ${entry.name}`}`); - if (entry.off) labelAttr(node, 'title', 'Not available for the current selection'); else node.removeAttribute('title'); - } - - function mark(scrollTo: boolean): void { - let current: HTMLElement | null = null; - Array.from(list.children).forEach(child => { - const node = child as HTMLElement; - if (node.dataset.key === activeKey) current = node; - const on = node.dataset.key === activeKey; - if (node.classList.contains('is-active') !== on) node.classList.toggle('is-active', on); - if (node.getAttribute('role') === 'option') node.setAttribute('aria-selected', String(on)); - }); - const node = current as HTMLElement | null; - if (node) input.setAttribute('aria-activedescendant', node.id); else input.removeAttribute('aria-activedescendant'); - if (node && scrollTo) node.scrollIntoView({ block: 'nearest' }); + if (node.classList.contains('is-off') !== entry.off) node.classList.toggle('is-off', entry.off); + if (node.classList.contains('is-section') !== (entry.kind === 'section')) node.classList.toggle('is-section', entry.kind === 'section'); + if (node.classList.contains('is-choice') !== (entry.kind === 'choice')) node.classList.toggle('is-choice', entry.kind === 'choice'); + if (entry.off) labelAttr(node, 'title', 'Not available for the current selection'); else if (node.hasAttribute('title')) node.removeAttribute('title'); } function refresh(): void { @@ -245,67 +257,35 @@ export function installInspectorSearch(options: SearchOptions): InspectorSearch if (options.scroll.hidden !== on) options.scroll.hidden = on; if (!on && open) options.scroll.scrollTop = savedTop; open = on; - input.setAttribute('aria-expanded', String(on)); - if (!on) { picks = []; return; } + if (!on) return; if (dirty) { index = build(); dirty = false; } - const scored = index.map((entry, order) => ({ entry, order, value: score(entry, tokens) })).filter(item => item.value >= 0); - const groups = new Map(); + const scored: Row[] = []; + const values = new Map(); + index.forEach((entry, order) => { + const value = score(entry, tokens); + if (value < 0) return; + scored.push({ key: entry.key, entry, value, order }); + values.set(entry.key, value); + }); + const groups = new Map(); for (const item of scored) { + const parent = values.get(item.entry.parent); + if (parent !== undefined && parent > item.value) item.value = parent; const id = item.entry.group; const group = groups.get(id); if (group) { group.best = Math.min(group.best, item.value); group.items.push(item); } else groups.set(id, { best: item.value, order: item.order, items: [item] }); } const rows: Row[] = []; - picks = []; - Array.from(groups.entries()).sort((a, b) => a[1].best - b[1].best || a[1].order - b[1].order).forEach(([id, group]) => { + Array.from(groups.values()).sort((a, b) => a.best - b.best || a.order - b.order).forEach(group => { if (rows.length >= MAX_ROWS) return; - const first = group.items[0].entry; - rows.push({ key: `g|${id}`, heading: `${first.tabName} > ${first.sectionName}` }); - group.items.sort((a, b) => a.value - b.value || a.order - b.order).forEach(item => { - if (rows.length >= MAX_ROWS) return; - rows.push({ key: item.entry.key, entry: item.entry }); - picks.push(item.entry); - }); + group.items.sort((a, b) => a.value - b.value || a.order - b.order); + rows.push(...group.items.slice(0, MAX_ROWS - rows.length)); }); keyed(list, rows, row => row.key, createRow, updateRow); if (empty.hidden !== rows.length > 0) empty.hidden = rows.length > 0; - const capped = groups.size + scored.length > MAX_ROWS; + const capped = scored.length > MAX_ROWS; if (more.hidden === capped) more.hidden = !capped; - if (!picks.some(entry => entry.key === activeKey)) activeKey = picks[0]?.key || ''; - mark(false); - } - - function move(step: number): void { - if (!picks.length) return; - const at = picks.findIndex(entry => entry.key === activeKey); - activeKey = picks[(at + step + picks.length) % picks.length].key; - mark(true); - } - - function pulse(target: HTMLElement): void { - if (pulsing) pulsing.classList.remove('fw-search-hit'); - clearTimeout(pulseTimer); - void target.offsetWidth; - target.classList.add('fw-search-hit'); - pulsing = target; - pulseTimer = window.setTimeout(() => { target.classList.remove('fw-search-hit'); if (pulsing === target) pulsing = null; }, PULSE_MS); - } - - function pick(chosen: Entry): void { - input.value = ''; - refresh(); - if (dirty) { index = build(); dirty = false; } - const entry = entries.get(chosen.key); - if (!entry || !entry.target.isConnected) return; - options.select(entry.tab); - for (let at = entry.target.closest('.inspector-section'); at; at = at.parentElement?.closest('.inspector-section') || null) { - if (at.classList.contains('is-collapsed')) at.querySelector(':scope > .section-title')?.click(); - } - entry.target.scrollIntoView({ block: entry.isSection ? 'start' : 'center' }); - const control = entry.isSection ? entry.target : controlOf(entry.target); - if (control && !(control as HTMLButtonElement).disabled) control.focus({ preventScroll: true }); - pulse(entry.isSection ? entry.target.parentElement || entry.target : entry.target); } function clear(): void { @@ -313,19 +293,17 @@ export function installInspectorSearch(options: SearchOptions): InspectorSearch refresh(); } - input.addEventListener('input', () => { activeKey = ''; refresh(); }); + input.addEventListener('input', refresh); input.addEventListener('keydown', event => { - if (event.isComposing) return; - if (event.key === 'ArrowDown') { event.preventDefault(); move(1); } - else if (event.key === 'ArrowUp') { event.preventDefault(); move(-1); } - else if (event.key === 'Enter') { - const entry = picks.find(item => item.key === activeKey); - if (entry) { event.preventDefault(); pick(entry); } - } else if (event.key === 'Escape') { - event.preventDefault(); - event.stopPropagation(); - if (input.value) clear(); else input.blur(); - } + if (event.isComposing || event.key !== 'Escape') return; + event.preventDefault(); + event.stopPropagation(); + if (input.value) { clear(); return; } + const tab = options.tabs.find(item => !item.pane.hidden && item.button.getClientRects().length); + if (tab) tab.button.focus({ preventScroll: true }); else input.blur(); + }); + results.addEventListener('mousedown', event => { + if (event.target !== results || (event.offsetX < results.clientWidth && event.offsetY < results.clientHeight)) event.preventDefault(); }); clearButton.addEventListener('click', () => { clear(); input.focus(); }); diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 138ee320..e3885261 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -515,7 +515,7 @@ inspectorScroll.append(designPane, motionPane, contentPane, pagePane); const scriptPanes = installScriptPanes([designPane, motionPane]); inspector.append(inspectorIdentity, inspectorTabs, inspectorScroll, dockStrip('right', [{ command: 'window.design', label: 'Design', icon: 'sliders' }, { command: 'window.content', label: 'Content', icon: 'text' }, { command: 'page.settings', label: 'Page', icon: 'page' }], { command: 'window.toggle-right', label: 'Expand right panel', icon: 'chevronsLeft' })); const inspectorSearch = installInspectorSearch({ - after: inspectorTabs, scroll: inspectorScroll, select: setInspector, + after: inspectorTabs, scroll: inspectorScroll, tabs: Object.entries({ design: designPane, motion: motionPane, content: contentPane, page: pagePane }).map(([id, pane]) => ({ id, pane, button: inspectorTabButtons.get(id)! })) }); const rail = new Rail([ diff --git a/frontend/src/styles/inspector-search.css b/frontend/src/styles/inspector-search.css index 47350122..ead7a1d1 100644 --- a/frontend/src/styles/inspector-search.css +++ b/frontend/src/styles/inspector-search.css @@ -6,22 +6,14 @@ .inspector-search-clear:hover { color: var(--text-primary); } .inspector-results { flex: 1 1 0; min-height: 0; overflow: auto; padding: var(--space-2); } .inspector-results-list { display: flex; flex-direction: column; gap: var(--space-1); } -.inspector-results-group { padding: var(--space-3) var(--space-2) var(--space-1); overflow: hidden; color: var(--text-muted); font-size: var(--fs-10); text-overflow: ellipsis; white-space: nowrap; } -.inspector-result { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); min-height: var(--ctl-md); padding: 0 var(--space-2); border-radius: var(--radius-md); color: var(--text-primary); font-size: var(--fs-12); cursor: pointer; } -.inspector-result:hover, .inspector-result.is-active { background: var(--accent-soft); } +.inspector-results-note { margin: 0 0 var(--space-2); padding: 0 var(--space-2); color: var(--text-muted); font-size: var(--fs-10); line-height: 1.4; } +.inspector-result { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-2); min-height: var(--ctl-md); padding: var(--space-1) var(--space-2); color: var(--text-primary); font-size: var(--fs-12); line-height: 1.4; cursor: default; user-select: none; } .inspector-result.is-off { color: var(--text-muted); } .inspector-result.is-section .inspector-result-name { font-weight: 600; } -.inspector-result-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.inspector-result-text { min-width: 0; overflow-wrap: anywhere; } +.inspector-result-dot, .inspector-result-place { color: var(--text-muted); } .inspector-result-css, .inspector-result-off { flex: none; color: var(--text-muted); font-size: var(--fs-10); } .inspector-result-css { font-family: var(--font-mono); } .inspector-result-css:empty { display: none; } .inspector-results-more { display: flex; align-items: center; height: var(--ctl-md); margin: 0; padding: 0 var(--space-2); overflow: hidden; color: var(--text-muted); font-size: var(--fs-10); line-height: 1.3; cursor: default; } .inspector-results-empty { margin: 0; padding: var(--space-4) var(--space-2); color: var(--text-muted); } -.fw-search-hit { border-radius: var(--radius-sm); outline: 2px solid var(--accent-color); outline-offset: var(--space-1); animation: fw-search-pulse 1.4s ease-out 1; } -@keyframes fw-search-pulse { - 0% { outline-color: var(--accent-color); background-color: var(--accent-wash); } - 100% { outline-color: transparent; background-color: transparent; } -} -@media (prefers-reduced-motion: reduce) { - .fw-search-hit { animation: none; } -} From 428580146641701a30c4cf601bb2ced021802902 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 17:08:18 -0500 Subject: [PATCH 09/38] i18n: the changed sentence under the audit marker switch and the sentence above the search results, in all 23 languages --- frontend/src/i18n/keys.ts | 3 ++- frontend/src/i18n/locales/cs.ts | 3 ++- frontend/src/i18n/locales/da.ts | 3 ++- frontend/src/i18n/locales/de.ts | 3 ++- frontend/src/i18n/locales/es.ts | 3 ++- frontend/src/i18n/locales/fi.ts | 3 ++- frontend/src/i18n/locales/fr.ts | 3 ++- frontend/src/i18n/locales/hu.ts | 3 ++- frontend/src/i18n/locales/id.ts | 3 ++- frontend/src/i18n/locales/it.ts | 3 ++- frontend/src/i18n/locales/ja.ts | 3 ++- frontend/src/i18n/locales/ko.ts | 3 ++- frontend/src/i18n/locales/nb.ts | 3 ++- frontend/src/i18n/locales/nl.ts | 3 ++- frontend/src/i18n/locales/pl.ts | 3 ++- frontend/src/i18n/locales/pt-BR.ts | 3 ++- frontend/src/i18n/locales/ru.ts | 3 ++- frontend/src/i18n/locales/sv.ts | 3 ++- frontend/src/i18n/locales/th.ts | 3 ++- frontend/src/i18n/locales/tr.ts | 3 ++- frontend/src/i18n/locales/uk.ts | 3 ++- frontend/src/i18n/locales/vi.ts | 3 ++- frontend/src/i18n/locales/zh-CN.ts | 3 ++- frontend/src/i18n/locales/zh-TW.ts | 3 ++- 24 files changed, 48 insertions(+), 24 deletions(-) diff --git a/frontend/src/i18n/keys.ts b/frontend/src/i18n/keys.ts index 18f88550..33ebe266 100644 --- a/frontend/src/i18n/keys.ts +++ b/frontend/src/i18n/keys.ts @@ -3030,7 +3030,7 @@ export const KEYS: readonly string[] = [ "The change was refused.", "Show audit markers", "Show audit markers on the page", - "Puts a small marker on each element of this page that has an issue. Click a marker to select the element.", + "Puts a small marker on each element of this page that has an issue. Markers show on the page when this dialog is closed. Click a marker to select the element.", "1 issue has no element, so it has no marker.", "{0} issues have no element, so they have no marker.", "Markers are drawn on the first {0} of {1} elements with issues on this page.", @@ -3083,4 +3083,5 @@ export const KEYS: readonly string[] = [ "1 font or registered property from the page's stylesheet was left out because the site already uses its name.", "{0} fonts or registered properties from the page's stylesheet were left out because the site already uses their names.", "Exported {0} file.", + "Each result shows where to find it. Open that tab and section to use it.", ]; diff --git a/frontend/src/i18n/locales/cs.ts b/frontend/src/i18n/locales/cs.ts index ad47bf59..f06be485 100644 --- a/frontend/src/i18n/locales/cs.ts +++ b/frontend/src/i18n/locales/cs.ts @@ -3030,7 +3030,7 @@ export default [ "Změna byla odmítnuta.", "Zobrazit značky auditu", "Zobrazovat značky auditu na stránce", - "Umístí malou značku na každý prvek této stránky, který má problém. Kliknutím na značku prvek vyberete.", + "Umístí malou značku na každý prvek této stránky, který má problém. Značky se na stránce zobrazí, když je tento dialog zavřený. Kliknutím na značku prvek vyberete.", "1 problém nemá prvek, proto nemá značku.", "Problémy bez prvku: {0}, proto nemají značku.", "Značky se kreslí na prvních {0} z {1} prvků s problémy na této stránce.", @@ -3083,4 +3083,5 @@ export default [ "Vynecháno 1 písmo nebo registrovaná vlastnost ze stylů stránky, protože web už používá jeho název.", "Vynechaná písma nebo registrované vlastnosti ze stylů stránky: {0}, protože web už používá jejich názvy.", "Exportováno souborů: {0}.", + "Každý výsledek ukazuje, kde ho najdete. Otevřete tuto kartu a sekci, abyste ho mohli použít.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/da.ts b/frontend/src/i18n/locales/da.ts index 37bb1698..2914a694 100644 --- a/frontend/src/i18n/locales/da.ts +++ b/frontend/src/i18n/locales/da.ts @@ -3030,7 +3030,7 @@ export default [ "Ændringen blev afvist.", "Vis auditmarkører", "Vis auditmarkører på siden", - "Sætter en lille markør på hvert element på denne side, der har et problem. Klik på en markør for at vælge elementet.", + "Sætter en lille markør på hvert element på denne side, der har et problem. Markørerne vises på siden, når denne dialog er lukket. Klik på en markør for at vælge elementet.", "1 problem har intet element, så det har ingen markør.", "{0} problemer har intet element, så de har ingen markør.", "Markører tegnes på de første {0} af {1} elementer med problemer på denne side.", @@ -3083,4 +3083,5 @@ export default [ "1 skrifttype eller registreret egenskab fra sidens stylesheet blev udeladt, fordi webstedet allerede bruger navnet.", "{0} skrifttyper eller registrerede egenskaber fra sidens stylesheet blev udeladt, fordi webstedet allerede bruger navnene.", "{0} fil eksporteret.", + "Hvert resultat viser, hvor det findes. Åbn den fane og sektion for at bruge det.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/de.ts b/frontend/src/i18n/locales/de.ts index b85d971f..ddd2c37e 100644 --- a/frontend/src/i18n/locales/de.ts +++ b/frontend/src/i18n/locales/de.ts @@ -3030,7 +3030,7 @@ export default [ "Die Änderung wurde abgelehnt.", "Audit-Markierungen anzeigen", "Audit-Markierungen auf der Seite anzeigen", - "Setzt eine kleine Markierung auf jedes Element dieser Seite, das ein Problem hat. Klicke auf eine Markierung, um das Element auszuwählen.", + "Setzt eine kleine Markierung auf jedes Element dieser Seite, das ein Problem hat. Die Markierungen erscheinen auf der Seite, wenn dieser Dialog geschlossen ist. Klicke auf eine Markierung, um das Element auszuwählen.", "1 Problem hat kein Element und daher keine Markierung.", "{0} Probleme haben kein Element und daher keine Markierung.", "Markierungen werden an den ersten {0} von {1} Elementen mit Problemen auf dieser Seite gezeichnet.", @@ -3083,4 +3083,5 @@ export default [ "1 Schrift oder registrierte Eigenschaft aus dem Stylesheet der Seite wurde weggelassen, weil die Website ihren Namen schon verwendet.", "{0} Schriften oder registrierte Eigenschaften aus dem Stylesheet der Seite wurden weggelassen, weil die Website ihre Namen schon verwendet.", "{0} Datei exportiert.", + "Jedes Ergebnis zeigt, wo es zu finden ist. Öffne diesen Tab und Abschnitt, um es zu verwenden.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/es.ts b/frontend/src/i18n/locales/es.ts index 306082c1..ee1f6ec7 100644 --- a/frontend/src/i18n/locales/es.ts +++ b/frontend/src/i18n/locales/es.ts @@ -3030,7 +3030,7 @@ export default [ "Se rechazó el cambio.", "Mostrar marcadores de auditoría", "Mostrar marcadores de auditoría en la página", - "Pone un pequeño marcador en cada elemento de esta página que tiene un problema. Haz clic en un marcador para seleccionar el elemento.", + "Pone un pequeño marcador en cada elemento de esta página que tiene un problema. Los marcadores se ven en la página cuando este diálogo está cerrado. Haz clic en un marcador para seleccionar el elemento.", "1 problema no tiene elemento, así que no tiene marcador.", "{0} problemas no tienen elemento, así que no tienen marcador.", "Los marcadores se dibujan en los primeros {0} de {1} elementos con problemas de esta página.", @@ -3083,4 +3083,5 @@ export default [ "Se omitió 1 fuente o propiedad registrada de la hoja de estilo de la página porque el sitio ya usa su nombre.", "Se omitieron {0} fuentes o propiedades registradas de la hoja de estilo de la página porque el sitio ya usa sus nombres.", "Se exportó {0} archivo.", + "Cada resultado indica dónde encontrarlo. Abre esa pestaña y esa sección para usarlo.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/fi.ts b/frontend/src/i18n/locales/fi.ts index aa276fc5..dfa9dc91 100644 --- a/frontend/src/i18n/locales/fi.ts +++ b/frontend/src/i18n/locales/fi.ts @@ -3030,7 +3030,7 @@ export default [ "Muutos hylättiin.", "Näytä auditointimerkit", "Näytä auditointimerkit sivulla", - "Lisää pienen merkin jokaiseen tämän sivun elementtiin, jossa on ongelma. Valitse elementti napsauttamalla merkkiä.", + "Lisää pienen merkin jokaiseen tämän sivun elementtiin, jossa on ongelma. Merkit näkyvät sivulla, kun tämä valintaikkuna on suljettu. Valitse elementti napsauttamalla merkkiä.", "1 ongelmalla ei ole elementtiä, joten sillä ei ole merkkiä.", "Ongelmia ilman elementtiä: {0}, joten niillä ei ole merkkiä.", "Merkit piirretään tämän sivun {1} ongelmallisesta elementistä ensimmäisiin {0}.", @@ -3083,4 +3083,5 @@ export default [ "1 fontti tai rekisteröity ominaisuus jätettiin pois sivun tyylitiedostosta, koska sivusto käyttää jo sen nimeä.", "{0} fonttia tai rekisteröityä ominaisuutta jätettiin pois sivun tyylitiedostosta, koska sivusto käyttää jo niiden nimiä.", "Viety {0} tiedosto.", + "Jokainen tulos näyttää, mistä sen löytää. Avaa kyseinen välilehti ja osio käyttääksesi sitä.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/fr.ts b/frontend/src/i18n/locales/fr.ts index 18b405ec..e45f4fed 100644 --- a/frontend/src/i18n/locales/fr.ts +++ b/frontend/src/i18n/locales/fr.ts @@ -3030,7 +3030,7 @@ export default [ "La modification a été refusée.", "Afficher les marqueurs d’audit", "Afficher les marqueurs d’audit sur la page", - "Place un petit marqueur sur chaque élément de cette page qui a un problème. Cliquez sur un marqueur pour sélectionner l’élément.", + "Place un petit marqueur sur chaque élément de cette page qui a un problème. Les marqueurs s’affichent sur la page quand cette boîte de dialogue est fermée. Cliquez sur un marqueur pour sélectionner l’élément.", "1 problème n’a pas d’élément, il n’a donc pas de marqueur.", "{0} problèmes n’ont pas d’élément, ils n’ont donc pas de marqueur.", "Les marqueurs sont dessinés sur les {0} premiers des {1} éléments ayant des problèmes sur cette page.", @@ -3083,4 +3083,5 @@ export default [ "1 police ou propriété enregistrée de la feuille de style de la page a été laissée de côté, car le site utilise déjà son nom.", "{0} polices ou propriétés enregistrées de la feuille de style de la page ont été laissées de côté, car le site utilise déjà leurs noms.", "{0} fichier exporté.", + "Chaque résultat indique où le trouver. Ouvrez cet onglet et cette section pour l’utiliser.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/hu.ts b/frontend/src/i18n/locales/hu.ts index 550c7716..f9431ae0 100644 --- a/frontend/src/i18n/locales/hu.ts +++ b/frontend/src/i18n/locales/hu.ts @@ -3030,7 +3030,7 @@ export default [ "A módosítást elutasították.", "Auditjelölők megjelenítése", "Auditjelölők megjelenítése az oldalon", - "Kis jelölőt tesz az oldal minden olyan elemére, amelynek problémája van. Kattints egy jelölőre az elem kijelöléséhez.", + "Kis jelölőt tesz az oldal minden olyan elemére, amelynek problémája van. A jelölők akkor látszanak az oldalon, amikor ez a párbeszédpanel be van zárva. Kattints egy jelölőre az elem kijelöléséhez.", "1 problémához nem tartozik elem, ezért nincs jelölője.", "{0} problémához nem tartozik elem, ezért nincs jelölőjük.", "A jelölők az oldal {1} problémás eleméből az első {0} elemen jelennek meg.", @@ -3083,4 +3083,5 @@ export default [ "Az oldal stíluslapjáról 1 betűtípus vagy regisztrált tulajdonság kimaradt, mert a webhely már használja a nevét.", "Az oldal stíluslapjáról {0} betűtípus vagy regisztrált tulajdonság kimaradt, mert a webhely már használja a nevüket.", "{0} fájl exportálva.", + "Minden találat megmutatja, hol található. A használatához nyissa meg azt a lapot és szakaszt.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/id.ts b/frontend/src/i18n/locales/id.ts index b9f6e376..e2109b96 100644 --- a/frontend/src/i18n/locales/id.ts +++ b/frontend/src/i18n/locales/id.ts @@ -3030,7 +3030,7 @@ export default [ "Perubahan ditolak.", "Tampilkan penanda audit", "Tampilkan penanda audit di halaman", - "Memasang penanda kecil pada setiap elemen di halaman ini yang memiliki masalah. Klik penanda untuk memilih elemennya.", + "Memasang penanda kecil pada setiap elemen di halaman ini yang memiliki masalah. Penanda tampil di halaman saat dialog ini ditutup. Klik penanda untuk memilih elemennya.", "1 masalah tidak memiliki elemen, jadi tidak memiliki penanda.", "{0} masalah tidak memiliki elemen, jadi tidak memiliki penanda.", "Penanda digambar pada {0} elemen pertama dari {1} elemen bermasalah di halaman ini.", @@ -3083,4 +3083,5 @@ export default [ "1 font atau properti terdaftar dari lembar gaya halaman ditinggalkan karena situs sudah memakai namanya.", "{0} font atau properti terdaftar dari lembar gaya halaman ditinggalkan karena situs sudah memakai namanya.", "{0} file diekspor.", + "Setiap hasil menunjukkan tempat menemukannya. Buka tab dan bagian itu untuk menggunakannya.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/it.ts b/frontend/src/i18n/locales/it.ts index 52bf9759..dcb6c7f8 100644 --- a/frontend/src/i18n/locales/it.ts +++ b/frontend/src/i18n/locales/it.ts @@ -3030,7 +3030,7 @@ export default [ "La modifica è stata rifiutata.", "Mostra indicatori dell’audit", "Mostra indicatori dell’audit sulla pagina", - "Mette un piccolo indicatore su ogni elemento di questa pagina che ha un problema. Fai clic su un indicatore per selezionare l’elemento.", + "Mette un piccolo indicatore su ogni elemento di questa pagina che ha un problema. Gli indicatori compaiono sulla pagina quando questa finestra di dialogo è chiusa. Fai clic su un indicatore per selezionare l’elemento.", "1 problema non ha un elemento, quindi non ha un indicatore.", "{0} problemi non hanno un elemento, quindi non hanno un indicatore.", "Gli indicatori sono disegnati sui primi {0} di {1} elementi con problemi in questa pagina.", @@ -3083,4 +3083,5 @@ export default [ "1 font o proprietà registrata del foglio di stile della pagina è stato escluso perché il sito usa già il suo nome.", "{0} font o proprietà registrate del foglio di stile della pagina sono stati esclusi perché il sito usa già i loro nomi.", "Esportato {0} file.", + "Ogni risultato indica dove trovarlo. Apri quella scheda e quella sezione per usarlo.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ja.ts b/frontend/src/i18n/locales/ja.ts index 75cfb20d..45eda4c3 100644 --- a/frontend/src/i18n/locales/ja.ts +++ b/frontend/src/i18n/locales/ja.ts @@ -3030,7 +3030,7 @@ export default [ "変更は拒否されました。", "監査マーカーを表示", "ページに監査マーカーを表示", - "このページで問題のある各要素に小さなマーカーを付けます。マーカーをクリックすると要素を選択します。", + "このページで問題のある各要素に小さなマーカーを付けます。マーカーはこのダイアログを閉じるとページに表示されます。マーカーをクリックすると要素を選択します。", "1 件の問題には要素がないため、マーカーはありません。", "{0} 件の問題には要素がないため、マーカーはありません。", "マーカーは、このページで問題のある {1} 個の要素のうち最初の {0} 個に描かれます。", @@ -3083,4 +3083,5 @@ export default [ "ページのスタイルシートのフォントまたは登録済みプロパティ 1 個を省きました: サイトですでにその名前が使われています。", "ページのスタイルシートのフォントまたは登録済みプロパティ {0} 個を省きました: サイトですでにその名前が使われています。", "{0} 個のファイルを書き出しました。", + "各結果にはその場所が表示されます。使うには、そのタブとセクションを開きます。", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ko.ts b/frontend/src/i18n/locales/ko.ts index f8e5ed00..2a6f60b7 100644 --- a/frontend/src/i18n/locales/ko.ts +++ b/frontend/src/i18n/locales/ko.ts @@ -3030,7 +3030,7 @@ export default [ "변경이 거부되었습니다.", "감사 마커 표시", "페이지에 감사 마커 표시", - "이 페이지에서 문제가 있는 각 요소에 작은 마커를 표시합니다. 마커를 클릭하면 요소를 선택합니다.", + "이 페이지에서 문제가 있는 각 요소에 작은 마커를 표시합니다. 마커는 이 대화상자를 닫으면 페이지에 나타납니다. 마커를 클릭하면 요소를 선택합니다.", "문제 1개에 요소가 없어 마커가 없습니다.", "문제 {0}개에 요소가 없어 마커가 없습니다.", "마커는 이 페이지에서 문제가 있는 요소 {1}개 중 처음 {0}개에 그려집니다.", @@ -3083,4 +3083,5 @@ export default [ "사이트에서 이미 그 이름을 쓰고 있으므로 페이지 스타일시트의 글꼴 또는 등록된 속성 1개를 뺐습니다.", "사이트에서 이미 그 이름들을 쓰고 있으므로 페이지 스타일시트의 글꼴 또는 등록된 속성 {0}개를 뺐습니다.", "파일 {0}개를 내보냈습니다.", + "각 결과에는 찾을 수 있는 위치가 표시됩니다. 사용하려면 해당 탭과 섹션을 여세요.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/nb.ts b/frontend/src/i18n/locales/nb.ts index f6091740..814a51b0 100644 --- a/frontend/src/i18n/locales/nb.ts +++ b/frontend/src/i18n/locales/nb.ts @@ -3030,7 +3030,7 @@ export default [ "Endringen ble avvist.", "Vis revisjonsmarkører", "Vis revisjonsmarkører på siden", - "Setter en liten markør på hvert element på denne siden som har et problem. Klikk på en markør for å velge elementet.", + "Setter en liten markør på hvert element på denne siden som har et problem. Markørene vises på siden når denne dialogen er lukket. Klikk på en markør for å velge elementet.", "1 problem har ikke noe element, så det har ingen markør.", "{0} problemer har ikke noe element, så de har ingen markør.", "Markører tegnes på de første {0} av {1} elementer med problemer på denne siden.", @@ -3083,4 +3083,5 @@ export default [ "1 skrift eller registrert egenskap fra sidens stilark ble utelatt fordi nettstedet allerede bruker navnet.", "{0} skrifter eller registrerte egenskaper fra sidens stilark ble utelatt fordi nettstedet allerede bruker navnene.", "Eksporterte {0} fil.", + "Hvert resultat viser hvor det finnes. Åpne den fanen og seksjonen for å bruke det.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/nl.ts b/frontend/src/i18n/locales/nl.ts index 9984fdce..ce863cee 100644 --- a/frontend/src/i18n/locales/nl.ts +++ b/frontend/src/i18n/locales/nl.ts @@ -3030,7 +3030,7 @@ export default [ "De wijziging is geweigerd.", "Auditmarkeringen tonen", "Auditmarkeringen op de pagina tonen", - "Zet een kleine markering op elk element van deze pagina dat een probleem heeft. Klik op een markering om het element te selecteren.", + "Zet een kleine markering op elk element van deze pagina dat een probleem heeft. De markeringen verschijnen op de pagina als dit dialoogvenster gesloten is. Klik op een markering om het element te selecteren.", "1 probleem heeft geen element, dus het heeft geen markering.", "{0} problemen hebben geen element, dus ze hebben geen markering.", "Markeringen worden getekend op de eerste {0} van {1} elementen met problemen op deze pagina.", @@ -3083,4 +3083,5 @@ export default [ "1 lettertype of geregistreerde eigenschap uit de stylesheet van de pagina is weggelaten omdat de site die naam al gebruikt.", "{0} lettertypen of geregistreerde eigenschappen uit de stylesheet van de pagina zijn weggelaten omdat de site die namen al gebruikt.", "{0} bestand geëxporteerd.", + "Elk resultaat laat zien waar het staat. Open dat tabblad en die sectie om het te gebruiken.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/pl.ts b/frontend/src/i18n/locales/pl.ts index 36567b00..93fcb4a8 100644 --- a/frontend/src/i18n/locales/pl.ts +++ b/frontend/src/i18n/locales/pl.ts @@ -3030,7 +3030,7 @@ export default [ "Zmiana została odrzucona.", "Pokaż znaczniki audytu", "Pokazuj znaczniki audytu na stronie", - "Umieszcza mały znacznik na każdym elemencie tej strony, który ma problem. Kliknij znacznik, aby zaznaczyć element.", + "Umieszcza mały znacznik na każdym elemencie tej strony, który ma problem. Znaczniki pojawiają się na stronie, gdy to okno dialogowe jest zamknięte. Kliknij znacznik, aby zaznaczyć element.", "1 problem nie ma elementu, więc nie ma znacznika.", "Problemy bez elementu: {0}, więc nie mają znaczników.", "Znaczniki są rysowane na pierwszych {0} z {1} elementów z problemami na tej stronie.", @@ -3083,4 +3083,5 @@ export default [ "Pominięto 1 czcionkę lub zarejestrowaną właściwość z arkusza stylów strony, bo witryna już używa jej nazwy.", "Pominięte czcionki lub zarejestrowane właściwości z arkusza stylów strony: {0}, bo witryna już używa ich nazw.", "Wyeksportowano plików: {0}.", + "Każdy wynik pokazuje, gdzie go znaleźć. Otwórz tę kartę i sekcję, aby go użyć.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/pt-BR.ts b/frontend/src/i18n/locales/pt-BR.ts index b37d7dd4..73226e7c 100644 --- a/frontend/src/i18n/locales/pt-BR.ts +++ b/frontend/src/i18n/locales/pt-BR.ts @@ -3030,7 +3030,7 @@ export default [ "A alteração foi recusada.", "Mostrar marcadores de auditoria", "Mostrar marcadores de auditoria na página", - "Coloca um pequeno marcador em cada elemento desta página que tem um problema. Clique em um marcador para selecionar o elemento.", + "Coloca um pequeno marcador em cada elemento desta página que tem um problema. Os marcadores aparecem na página quando esta caixa de diálogo está fechada. Clique em um marcador para selecionar o elemento.", "1 problema não tem elemento, então não tem marcador.", "{0} problemas não têm elemento, então não têm marcador.", "Os marcadores são desenhados nos primeiros {0} de {1} elementos com problemas desta página.", @@ -3083,4 +3083,5 @@ export default [ "1 fonte ou propriedade registrada da folha de estilo da página foi deixada de fora porque o site já usa o nome dela.", "{0} fontes ou propriedades registradas da folha de estilo da página foram deixadas de fora porque o site já usa os nomes delas.", "{0} arquivo exportado.", + "Cada resultado mostra onde encontrá-lo. Abra essa aba e essa seção para usá-lo.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ru.ts b/frontend/src/i18n/locales/ru.ts index ab8df5e2..f977bb47 100644 --- a/frontend/src/i18n/locales/ru.ts +++ b/frontend/src/i18n/locales/ru.ts @@ -3030,7 +3030,7 @@ export default [ "Изменение отклонено.", "Показать маркеры аудита", "Показывать маркеры аудита на странице", - "Ставит небольшой маркер на каждый элемент этой страницы, у которого есть проблема. Нажмите на маркер, чтобы выбрать элемент.", + "Ставит небольшой маркер на каждый элемент этой страницы, у которого есть проблема. Маркеры видны на странице, когда этот диалог закрыт. Нажмите на маркер, чтобы выбрать элемент.", "У 1 проблемы нет элемента, поэтому у неё нет маркера.", "Проблем без элемента: {0}, поэтому у них нет маркеров.", "Маркеры нарисованы на первых {0} из {1} элементов с проблемами на этой странице.", @@ -3083,4 +3083,5 @@ export default [ "Шрифт или зарегистрированное свойство из таблицы стилей страницы пропущено, потому что сайт уже использует это имя.", "Пропущено шрифтов или зарегистрированных свойств из таблицы стилей страницы: {0}, потому что сайт уже использует эти имена.", "Экспортировано файлов: {0}.", + "Каждый результат показывает, где его найти. Откройте эту вкладку и раздел, чтобы им воспользоваться.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/sv.ts b/frontend/src/i18n/locales/sv.ts index 2da66bb9..795b4995 100644 --- a/frontend/src/i18n/locales/sv.ts +++ b/frontend/src/i18n/locales/sv.ts @@ -3030,7 +3030,7 @@ export default [ "Ändringen avvisades.", "Visa granskningsmarkörer", "Visa granskningsmarkörer på sidan", - "Sätter en liten markör på varje element på den här sidan som har ett problem. Klicka på en markör för att markera elementet.", + "Sätter en liten markör på varje element på den här sidan som har ett problem. Markörerna visas på sidan när den här dialogrutan är stängd. Klicka på en markör för att markera elementet.", "1 problem har inget element, så det har ingen markör.", "{0} problem har inget element, så de har ingen markör.", "Markörer ritas på de första {0} av {1} element med problem på den här sidan.", @@ -3083,4 +3083,5 @@ export default [ "1 typsnitt eller registrerad egenskap från sidans formatmall utelämnades eftersom webbplatsen redan använder namnet.", "{0} typsnitt eller registrerade egenskaper från sidans formatmall utelämnades eftersom webbplatsen redan använder namnen.", "{0} fil exporterades.", + "Varje resultat visar var det finns. Öppna den fliken och sektionen för att använda det.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/th.ts b/frontend/src/i18n/locales/th.ts index 0628c7f7..b62b3a3a 100644 --- a/frontend/src/i18n/locales/th.ts +++ b/frontend/src/i18n/locales/th.ts @@ -3030,7 +3030,7 @@ export default [ "การเปลี่ยนแปลงถูกปฏิเสธ", "แสดงเครื่องหมายการตรวจสอบ", "แสดงเครื่องหมายการตรวจสอบบนหน้า", - "ใส่เครื่องหมายเล็กๆ บนแต่ละองค์ประกอบของหน้านี้ที่มีปัญหา คลิกเครื่องหมายเพื่อเลือกองค์ประกอบนั้น", + "ใส่เครื่องหมายเล็กๆ บนแต่ละองค์ประกอบของหน้านี้ที่มีปัญหา เครื่องหมายจะแสดงบนหน้าเมื่อปิดกล่องโต้ตอบนี้ คลิกเครื่องหมายเพื่อเลือกองค์ประกอบนั้น", "ปัญหา 1 รายการไม่มีองค์ประกอบ จึงไม่มีเครื่องหมาย", "ปัญหา {0} รายการไม่มีองค์ประกอบ จึงไม่มีเครื่องหมาย", "เครื่องหมายแสดงบน {0} องค์ประกอบแรกจาก {1} องค์ประกอบที่มีปัญหาในหน้านี้", @@ -3083,4 +3083,5 @@ export default [ "ละฟอนต์หรือคุณสมบัติที่ลงทะเบียน 1 รายการจากสไตล์ชีตของหน้า เพราะไซต์ใช้ชื่อนั้นอยู่แล้ว", "ละฟอนต์หรือคุณสมบัติที่ลงทะเบียน {0} รายการจากสไตล์ชีตของหน้า เพราะไซต์ใช้ชื่อเหล่านั้นอยู่แล้ว", "ส่งออกแล้ว {0} ไฟล์", + "ผลลัพธ์แต่ละรายการบอกตำแหน่งที่จะพบ เปิดแท็บและส่วนนั้นเพื่อใช้งาน", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/tr.ts b/frontend/src/i18n/locales/tr.ts index 07be2c3f..90c27f1c 100644 --- a/frontend/src/i18n/locales/tr.ts +++ b/frontend/src/i18n/locales/tr.ts @@ -3030,7 +3030,7 @@ export default [ "Değişiklik reddedildi.", "Denetim işaretçilerini göster", "Denetim işaretçilerini sayfada göster", - "Bu sayfada sorunu olan her öğeye küçük bir işaretçi koyar. Öğeyi seçmek için bir işaretçiye tıklayın.", + "Bu sayfada sorunu olan her öğeye küçük bir işaretçi koyar. İşaretçiler, bu iletişim kutusu kapalıyken sayfada görünür. Öğeyi seçmek için bir işaretçiye tıklayın.", "1 sorunun öğesi yok, bu yüzden işaretçisi de yok.", "{0} sorunun öğesi yok, bu yüzden işaretçileri de yok.", "İşaretçiler, bu sayfada sorunu olan {1} öğenin ilk {0} tanesine çizilir.", @@ -3083,4 +3083,5 @@ export default [ "Sayfanın stil sayfasındaki 1 yazı tipi veya kayıtlı özellik, site adını zaten kullandığı için dışarıda bırakıldı.", "Sayfanın stil sayfasındaki {0} yazı tipi veya kayıtlı özellik, site adlarını zaten kullandığı için dışarıda bırakıldı.", "{0} dosya dışa aktarıldı.", + "Her sonuç nerede bulunacağını gösterir. Kullanmak için o sekmeyi ve bölümü açın.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/uk.ts b/frontend/src/i18n/locales/uk.ts index c9ef14aa..9dc57fa6 100644 --- a/frontend/src/i18n/locales/uk.ts +++ b/frontend/src/i18n/locales/uk.ts @@ -3030,7 +3030,7 @@ export default [ "Зміну відхилено.", "Показати маркери аудиту", "Показувати маркери аудиту на сторінці", - "Ставить невеликий маркер на кожен елемент цієї сторінки, який має проблему. Натисніть маркер, щоб вибрати елемент.", + "Ставить невеликий маркер на кожен елемент цієї сторінки, який має проблему. Маркери видно на сторінці, коли цей діалог закрито. Натисніть маркер, щоб вибрати елемент.", "1 проблема не має елемента, тому не має маркера.", "Проблем без елемента: {0}, тому вони не мають маркерів.", "Маркери намальовано на перших {0} з {1} елементів із проблемами на цій сторінці.", @@ -3083,4 +3083,5 @@ export default [ "Шрифт або зареєстровану властивість із таблиці стилів сторінки пропущено, бо сайт уже використовує цю назву.", "Пропущено шрифтів або зареєстрованих властивостей із таблиці стилів сторінки: {0}, бо сайт уже використовує ці назви.", "Експортовано файлів: {0}.", + "Кожен результат показує, де його знайти. Відкрийте цю вкладку й розділ, щоб ним скористатися.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/vi.ts b/frontend/src/i18n/locales/vi.ts index fde8fcb1..ff60ee99 100644 --- a/frontend/src/i18n/locales/vi.ts +++ b/frontend/src/i18n/locales/vi.ts @@ -3030,7 +3030,7 @@ export default [ "Thay đổi đã bị từ chối.", "Hiện điểm đánh dấu kiểm toán", "Hiện điểm đánh dấu kiểm toán trên trang", - "Đặt một điểm đánh dấu nhỏ lên mỗi phần tử của trang này có vấn đề. Nhấp vào một điểm đánh dấu để chọn phần tử đó.", + "Đặt một điểm đánh dấu nhỏ lên mỗi phần tử của trang này có vấn đề. Điểm đánh dấu hiện trên trang khi hộp thoại này đóng. Nhấp vào một điểm đánh dấu để chọn phần tử đó.", "1 vấn đề không có phần tử, nên không có điểm đánh dấu.", "{0} vấn đề không có phần tử, nên không có điểm đánh dấu.", "Điểm đánh dấu được vẽ trên {0} phần tử đầu tiên trong số {1} phần tử có vấn đề trên trang này.", @@ -3083,4 +3083,5 @@ export default [ "Đã bỏ 1 phông chữ hoặc thuộc tính đã đăng ký từ biểu định kiểu của trang, vì trang web đã dùng tên đó.", "Đã bỏ {0} phông chữ hoặc thuộc tính đã đăng ký từ biểu định kiểu của trang, vì trang web đã dùng các tên đó.", "Đã xuất {0} tệp.", + "Mỗi kết quả cho biết nơi tìm thấy nó. Mở tab và phần đó để dùng.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index e676f2d4..08b26884 100644 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3030,7 +3030,7 @@ export default [ "更改被拒绝。", "显示审计标记", "在页面上显示审计标记", - "在此页面上每个有问题的元素上放一个小标记。点击标记即可选择该元素。", + "在此页面上每个有问题的元素上放一个小标记。关闭此对话框后,标记会显示在页面上。点击标记即可选择该元素。", "1 个问题没有对应元素,因此没有标记。", "{0} 个问题没有对应元素,因此没有标记。", "此页面上有问题的元素共 {1} 个,标记只画在前 {0} 个上。", @@ -3083,4 +3083,5 @@ export default [ "页面样式表中的 1 个字体或注册属性被省略了,因为网站已在使用它的名称。", "页面样式表中的 {0} 个字体或注册属性被省略了,因为网站已在使用它们的名称。", "已导出 {0} 个文件。", + "每个结果都会显示它所在的位置。打开对应的标签页和版块即可使用。", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index e1fc126d..73a925af 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -3030,7 +3030,7 @@ export default [ "變更遭到拒絕。", "顯示稽核標記", "在頁面上顯示稽核標記", - "在此頁面上每個有問題的元素上放一個小標記。按一下標記即可選取該元素。", + "在此頁面上每個有問題的元素上放一個小標記。關閉此對話框後,標記會顯示在頁面上。按一下標記即可選取該元素。", "1 個問題沒有對應元素,因此沒有標記。", "{0} 個問題沒有對應元素,因此沒有標記。", "此頁面上有問題的元素共 {1} 個,標記只畫在前 {0} 個上。", @@ -3083,4 +3083,5 @@ export default [ "頁面樣式表中的 1 個字型或註冊屬性被省略了,因為網站已在使用它的名稱。", "頁面樣式表中的 {0} 個字型或註冊屬性被省略了,因為網站已在使用它們的名稱。", "已匯出 {0} 個檔案。", + "每個結果都會顯示它所在的位置。開啟對應的分頁和區塊即可使用。", ] as readonly string[]; From 9813bc57a3cf5bc78bbc531ddd0c5bbb3d11b71e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 17:27:01 -0500 Subject: [PATCH 10/38] fix(editor): closing a dialog whose opener is gone, as after a menu command, moves the focus to the active inspector tab even when it was still on a button inside the dialog, so Backspace no longer removes the selected element --- docs/guide/images/panel-search-jump.webp | Bin 4594 -> 0 bytes frontend/src/main.ts | 3 ++- 2 files changed, 2 insertions(+), 1 deletion(-) delete mode 100644 docs/guide/images/panel-search-jump.webp diff --git a/docs/guide/images/panel-search-jump.webp b/docs/guide/images/panel-search-jump.webp deleted file mode 100644 index dfad537c7cb3a72750f9b08a529982dfe6b900b3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4594 zcmVDj@;B06sAoibJ9yp%N(-03ZVd zv$t@zFno+n)PIiUp6MBo@CTfKF8`|aqy9tsKeRu#?^1v79bx>yexiP}d(!`4^=;?@ z`pxN8>}UFc>@E9&=}Y??@O}Gb`N;9-T(jQFZ=)TUy>f$KR*8J{}25i zz%TM|=l|<}zkizlv;H&x|NSqy&tiYH9>t%l-+$y%#y$Ey(;%^a*@!srtgojd2m&ba z^|gc9+OWDlfHrMoy=&m|#C1jDkG0oKg2nr4SjWFdx?~mYsd`wQ1n{&Cm}K>3(eTb!Q$O zt1a^4Z8`%^4}@dCDD2M2a26jm@+C>pSZfykeD)U%a;u28R}i!K@cC5=5Rb&?UF@8HlS22waefLQgMeV6ADo53Frq(Pa%OIMybJ`Gq=Nx*I*H$0e= zps6O`Jsh*NpC3jM2)L8pzlFr-S*6J8$EdO=vt*%Qay=j_knfWX^2Kk@sKIGfqB-9y{ROaRZxgel(w{0$_!CE z6IAm1WOYqbi6;m-J0&$G2`BK|-yWi>J~FyFjcQVH0s2->^hD-sQ(sSL{cu7T;wMC? zOm_L8ul#m4`-8g#r{zT11y$!vtv(Pms3nJfUh~e5fHLF2^fOZ^W%=#rif_T_N&^n{ zA`^(MJyFj>*dI$KkWIgk^lZ1)nE7`1|JG7y7*pMvh%TwDzO*Gw$XWGU`v=(CcY0Dd zuYQMk?!VqFVET^AE;LYhsu6uamPegR^Nw@7Q||(wp)4b)BYir;2$Z(8`xaz1$({Im*W;-5{yd$sdpdJMr=o|snsv5|I42t7g_!OxD1Ko0sWcPUe$Uz^2^12M_#wxu1h87vf^Emc+RK{ z^SYnMqime5pr}N!QGnE$Y!idPCPXEtl}A2m5;;1HVhkClPZTa9axc%FU=A87QGi6_JbXcv0HNE2})2u@s+ z+!Ta{(Hr>gF#Lv&Q*Ml+m^4JIiK}RX81w>3coF)K6NF52-R zeX|=F%`I<7jwB*x2HYwjjm4KKVFiEOgeY<~3k!N(dC_j1_4q)aO%a@gcq2*EbGq%K zl1>)W>=1&5NIlil1*5!^Z5>mj4F_aGW@2%f7#-q6z)8pid>P9A2^0XaAFT*xJv8ehxIv$8Sw0uk#yU{HL)iDaN`L|S5M@2Xn+YvsHILn&Ls59T5Q zNd>qoS9oRB2oHF^o@VuI+0}am;!BNA^(LYSrq-u_a1T&mwlMa{AoL%7qa5x5!9n_0 z{#Yx~!1fu9kX24`C^lOE6Ta>wu;2k^Yf3!1&^M9<-_y^*FY@M@lIZ{v;CA5tf((!sC^RdsKx* z%LOkSv)l^ScKRfl3kfd0RH*=<5Hx=_jp5wSW6ziy=35r}o@qVild`{RwTpDOPx%`~ z2ETvx;5DL>1(LEbDT?>Qq1D}l7lB)Tzp?oF--foweL@MaQR%IJ-oQ z#Rk(W{iCpsCxY@Z*Miz8&-^e5H?Bd4;+C`eEM*RDB*M(G-P8q9YCPHQa8%khKC|Dvf1dPlUDEFV|irOb!ApZWOIPz2Fu*KF_Bk5hHsd-)sm5P8W^R*9i4{QeW19OR&&V z*5bGIM1`a_zFDeUjN9pbubYy`Wq;IF`%27(MzU?=nmTkHwtpL67e8Mxil3%O9U}TT za^(5UqEi{u>el{13ije6;|0qa&OkJ`pVG78BvDlzA?ed88DUv~12{Kn<$ee5+_d%U z4B|C;cH_(5|Ff>?$<~Mft-vsd4<70-6W~U44rH}fv_bZ|otc@`E(8HZd&e0}dCl+j z*rb@WNUQy}!J}OpIFIMvEb-a>1&L%}RBC)4e#cFFKo)S_a~%s_aCDyu{u2fkS;o}) zN$tA}KmmDc*W_<@=q96DQ}wP&T;>8hp`eV|e8>#9d8h6$s?nO`d4j-}eI*rTzm`o& z8BFy_sCd!-{w{-M)pup|zKm2hO-AIFXWyj0eAu{-l$f!P4*dhtg_~)uWsL2%58(q2jMzA#VUp4=a z_ywHlRjIAw*aa&O0530Ww|?t>$)dLzx6=DxH!Qp!L2Fct)y1rQOXo6dyulpdnM94z zu-e7}eYf&HSVz1ph+`8?_30CJ6H$~`CWR;P2yT0$~>03;v6nvU;9lecvB^P?MfHm2%zmjHI!5IosAE3lvDTsT(UiG?FijfTI3cd-s@*Ai}tib zfa83oN>v{1w5jwpAxTWQSAZ7Bev*PXD{_}=a?gKL?T`7JspTlv>;vPTzG0(-bKc7^ z@!bm*U+z7KC$wNXqALT1a67JQGU)58l&_D#e1s-w4subiu9Hp(t1aN0MsVmXUpaf(`ug9rqj+ zP|lXli?cI#GL$x?NFaV@^;`qa53I>PA5kYx_IYM!t)XG@vgezD(+W_KK~|LcH>L6* zQ1*{IV9EaNx0@kyn*Ap-?xdYpMh82o5lr00j>aTG8hzUrCd5yJSdiCr_OA1tknOiT zC(H7P7eI>()Q{m%I4-~<>H$QRd+$oGbYba-d&7E|my0u>bm#|$js=?dP*+Kh`VqE9 zO7|Z*cCM0gKcafL+|$g$YD&;T)xSRlY^`SkfM9K-LVxbINRIu*P28X>PF(_;pGM1r zt}`s8(=k9dAd0ht4K zJd(kC?3%jyZ^xNoCCE$5-aAmAn%T?CM!o+I_g{$}3zztlv%PaL&x$yqik`zyqV{YcEEGN$yKG#|J9BwFPg^@5wH^_+`?o>mtaYi0mBs4oY->m>VFjfCpY>z6>~hiJ-#Yu*bz<>!HcyvM+387&bNI5^xfSFvz6Xysq_7%U z4UDh+?t9x{Aj;gguf1ugr*Eb6bXX_m0mGUnXEv5sy@J1)e>6k!ZpZMu2GdMlNqmr< zLr%S&4!I9?=gxb=>p^7ya)}h+a-O|ht!~X6e{hr&ZLG?IDF3UdNM5u#XpcfO-nG!a ze4!a)-E-N6nH%&6#J5|N0h0RhQbUMS?vG;LZIrhD;AyYrujV@oXPp*#S$0+q7XtNn zc^Y`nW1+xSBBl&wsILj-U7-N5o4goVs4{&iKi6yi3;nvaNX#}U46sx|t=pmRZ3QU+ zK$fGWHo%qM0bDJ6r=p^9Ypu^$5J#ozpc67ZPRfS0sKmEutFdJ0hXx4T?pwBdDKcG!i zhvD=vFV@>NR*=oh%4g<@Dp}l63cH4$|8;Fd$v-&-Sgxq z>AI#6*-oWs6g6vi07ktDPNW7}&e0Uf@=z3vjIg|PSe71^;tAWPL?+*km%w~2gwqL!5 zGQVx0Qqw>&S+lYmS~mCVQ{x%;o{=V=B9X#I)?10!R|@pdLNf)t({3-U?QttNirKu zcl~RkgH$w#_H>6|VX|1N_?|z>-*Z0AW1Y=C;fn~SUJ%V^du|5(K2w3e$E;+-I`+7S chcVjFziDPN4Cva`*-kV{g?0s`w8{Vg00gWK8~^|S diff --git a/frontend/src/main.ts b/frontend/src/main.ts index e3885261..3f48bb7c 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -1907,7 +1907,8 @@ function closeDialog(): void { scrim.hidden = true; dialogMode = ''; lastFocus?.focus(); - if (document.activeElement === document.body) { + const active = document.activeElement; + if (!active || active === document.body || scrim.contains(active)) { const tab = inspectorTabs.querySelector('button.active'); (tab?.getClientRects().length ? tab : auditButton).focus({ preventScroll: true }); } From 5f9f9b8c9e42afaa3432f4073fc19b3687c3b372 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 17:27:01 -0500 Subject: [PATCH 11/38] ci(window): the window tests are built once and run as eight parts side by side, each with a limit of 7 minutes --- .github/workflows/ci.yml | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 840e4283..4de3b37d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,9 +84,9 @@ jobs: working-directory: backend run: python -m pytest tests -q -p no:cacheprovider - window: + window-build: runs-on: ubuntu-latest - timeout-minutes: 45 + timeout-minutes: 7 steps: - name: Apt mirror fallback if: runner.os == 'Linux' @@ -119,9 +119,39 @@ jobs: run: | npm ci npm run build + - name: Pack the engine binary and the window + run: tar -cf window-build.tar native/target/release/formweb-core frontend/dist + - uses: actions/upload-artifact@v4 + with: + name: window-build + path: window-build.tar + retention-days: 1 + + window: + needs: window-build + runs-on: ubuntu-latest + timeout-minutes: 7 + strategy: + fail-fast: false + matrix: + part: [1, 2, 3, 4, 5, 6, 7, 8] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + cache: pip + cache-dependency-path: backend/requirements.txt + - uses: actions/download-artifact@v4 + with: + name: window-build + - name: Unpack the engine binary and the window + run: tar -xf window-build.tar - name: Engine, pytest and Playwright run: | pip install -r backend/requirements.txt pytest==9.1.1 playwright==1.63.0 python -m playwright install --with-deps chromium - - name: Window smoke (F7) - run: python -m pytest frontend/tests/window -q -p no:cacheprovider + - name: Window smoke (F7), part ${{ matrix.part }} of 8 + run: | + files=$(grep -c "def test_" frontend/tests/window/test_*.py | sort -t: -k2,2nr -k1,1 | awk -F: -v k=${{ matrix.part }} 'NR % 8 == k % 8 {print $1}') + python -m pytest $files -q -p no:cacheprovider From 33a956544a9d50271bd58f0c47c922823a093c96 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 17:27:01 -0500 Subject: [PATCH 12/38] test(service): the import review's outside list, its hosts read the way a browser reads them, the cap of 20 with the count of the rest, and the warnings the list already covers --- backend/tests/hostile/test_outside_hosts.py | 170 +++++++++++++ .../tests/site_import/test_outside_files.py | 235 ++++++++++++++++++ 2 files changed, 405 insertions(+) create mode 100644 backend/tests/hostile/test_outside_hosts.py create mode 100644 backend/tests/site_import/test_outside_files.py diff --git a/backend/tests/hostile/test_outside_hosts.py b/backend/tests/hostile/test_outside_hosts.py new file mode 100644 index 00000000..1fba9835 --- /dev/null +++ b/backend/tests/hostile/test_outside_hosts.py @@ -0,0 +1,170 @@ +import json + +import pytest + +from site_zips import answered_within, page, zip_of + +REVIEW = "/api/library/import-site/review" +BOUND = 30 +CONTROL = "https://control.example.net/c.js" + +# (reference, the host a browser loads it from), read by hand from the WHATWG URL rules: for http and https a +# backslash is a slash, any run of slashes after the scheme is skipped, the last @ before the end of the authority +# ends the credentials, and the authority ends at the first /, \, ? or #. +LISTED = [ + ("https://tracker.example\\@cdn.example.net/x.js", "tracker.example"), + ("https://c.example\\@a.example/x.js", "c.example"), + ("https:\\\\evil.example\\x.css", "evil.example"), + ("\\\\evil.example/y.js", "evil.example"), + ("/\\evil.example/z.js", "evil.example"), + ("\\/evil.example/w.js", "evil.example"), + ("HTTP:\\\\CDN.example.net\\x.js", "cdn.example.net"), + ("https://good.example@evil.example/x.js", "evil.example"), + ("https://a@b@c.example.net/x.js", "c.example.net"), + ("https://good.example#@evil.example/x.js", "good.example"), + ("https://good.example?@evil.example/x.js", "good.example"), + ("https://cdn.example.net\\path\\x.js?q=a\\b", "cdn.example.net"), + ("https://user:secret@cred.example.net/a.js", "cred.example.net"), + ("https://cdn.example.net:443/x.js", "cdn.example.net"), + ("http://cdn.example.net:80/x.js", "cdn.example.net"), + ("https://cdn.example.net:8443/x.js", "cdn.example.net:8443"), + ("https://bücher.example/x.js", "xn--bcher-kva.example"), +] + +# A browser loads these from the given host; the review may name that host or leave the file out, never another. +LISTED_OR_LEFT_OUT = [ + ("https:///evil.example/x.js", "evil.example"), + ("\\\\\\evil.example/x.js", "evil.example"), + ("https://0x7f.1/a.js", "127.0.0.1"), + ("http://2130706433/a.js", "127.0.0.1"), + ("https://0177.0.0.1/a.js", "127.0.0.1"), + ("https://1.2.3/a.js", "1.2.0.3"), + ("https://0x/a.js", "0.0.0.0"), + ("https://faß.example/x.js", "xn--fa-hia.example"), + ("https://ς.example/x.js", "xn--3xa.example"), + ("https://CDN.example.net/x.js", "cdn.example.net"), + ("https://cdn。example。net/x.js", "cdn.example.net"), + ("https://%63dn.example.net/x.js", "cdn.example.net"), + ("https://cdn.example.net:0080/x.js", "cdn.example.net:80"), + ("http://cdn.example.net:0080/x.js", "cdn.example.net"), + ("//cdn.example.net:8080/x.js", "cdn.example.net:8080"), + ("https://xn--bcher-kva.example/x.js", "xn--bcher-kva.example"), + (" \t https://cdn.example.net/a\nb.js ", "cdn.example.net"), + ("https://cdn.exa\tmple.net/x.js", "cdn.example.net"), + ("ht\ttps://cdn.example.net/x.js", "cdn.example.net"), +] + +LEFT_OUT = { + "a host of five thousand characters": "https://" + "a" * 4996 + ".net/x.js", + "a host of 255 characters in labels of 63": "https://" + ".".join(["b" * 63] * 4) + "/x.js", + "a host with an underscore": "https://under_score.example.net/x.js", + "an ipv6 literal": "https://[::1]/x.js", + "an ipv6 literal with a port": "http://[2001:db8::1]:8080/x.js", + "a javascript address": "javascript:alert(1)", + "a data address": "data:text/javascript,alert(1)", + "a blob address": "blob:https://cdn.example.net/1f2e3d", + "an ftp address": "ftp://cdn.example.net/x.js", + "a port over 65535": "https://cdn.example.net:99999/x.js", + "five numbers": "https://1.2.3.4.5/x.js", + "a number over 255": "https://256.1.1.1/x.js", + "a space in the host": "https://cdn .example.net/x.js", + "an empty host": "https:///", + "a scheme with one slash, whose host depends on the page": "https:/evil.example/x.js", + "a scheme with no slash, whose host depends on the page": "https:evil.example/x.js", + "a protocol-relative https port, whose meaning depends on the page": "//cdn.example.net:443/x.js", +} + + +@pytest.fixture() +def blank(client): + r = client.post("/api/new", json={"name": "Blank", "blank": True}) + assert r.status_code == 200, r.text + return r.json() + + +def listed_for(client, head): + r = client.post(REVIEW, json={"files": [{"name": "index.html", "html": page("Hostile", "

x

", head)}]}) + assert r.status_code == 200, r.text[:400] + found = r.json()["pages"][0] + assert "outside" in found, f"the review has no outside list: {sorted(found)}" + return found["outside"] + + +def one_with_control(client, tag): + listed = listed_for(client, tag + f'') + assert listed[-1:] and listed[-1]["host"] == "control.example.net", f"the control script was not listed, so the page was not read: {listed}" + return listed[:-1] + + +def url_host(url): + assert url.startswith(("https://", "http://", "//")), f"the listed address is not absolute or protocol-relative: {url!r}" + authority = url.split("//", 1)[1] + for end in "/?#": + authority = authority.split(end, 1)[0] + assert "\\" not in authority and "@" not in authority, f"a browser would read another host out of the listed address {url!r}" + return authority + + +@pytest.mark.parametrize("reference, host", LISTED) +@pytest.mark.parametrize("kind", ["script", "stylesheet"]) +def test_an_outside_file_is_named_with_the_host_a_browser_loads_it_from(client, blank, reference, host, kind): + tag = f'' if kind == "script" else f'' + listed = one_with_control(client, tag) + assert [(item["kind"], item["host"]) for item in listed] == [(kind, host)], f"{reference!r} loads from {host}, the review named {listed}" + assert url_host(listed[0]["url"]) == host, f"the listed address {listed[0]['url']!r} does not lead to {host}" + + +@pytest.mark.parametrize("reference, host", LISTED_OR_LEFT_OUT) +def test_an_outside_file_is_named_with_the_host_a_browser_loads_it_from_or_not_at_all(client, blank, reference, host): + listed = one_with_control(client, f'') + assert listed == [] or [item["host"] for item in listed] == [host], f"{reference!r} loads from {host}, the review named {listed}" + assert all(url_host(item["url"]) == host for item in listed), listed + + +@pytest.mark.parametrize("case", list(LEFT_OUT)) +def test_an_address_that_does_not_name_one_outside_host_is_not_listed(client, blank, case): + reference = LEFT_OUT[case] + listed = one_with_control(client, f'') + assert listed == [], f"{case} was listed: {listed}" + + +def test_the_spoofed_host_is_named_as_the_real_one_inside_a_zip_too(client, blank): + sample = page("Spoof", "

x

", '') + r = client.post(REVIEW, content=zip_of({"index.html": sample})) + assert r.status_code == 200, r.text[:400] + listed = r.json()["pages"][0]["outside"] + assert [(item["kind"], item["host"]) for item in listed] == [("script", "tracker.example"), ("stylesheet", "evil.example")] + assert [url_host(item["url"]) for item in listed] == ["tracker.example", "evil.example"], listed + + +@pytest.mark.parametrize("reference", [ + "https://user:secret@cred.example.net/a.js", + "https://user@cred.example.net/a.js", + "//user:secret@cred.example.net/a.js", + "https://user:secret@cred.example.net:8443/a.js", + "https:\\\\user:secret@cred.example.net\\a.js", +]) +def test_credentials_in_an_address_never_appear_in_the_listed_host_or_address(client, blank, reference): + listed = one_with_control(client, f'') + assert [item["host"].split(":")[0] for item in listed] == ["cred.example.net"], listed + for item in listed: + assert "user" not in item["host"] + item["url"] and "secret" not in item["host"] + item["url"], item + assert "@" not in item["url"].split("/")[2], item + + +def test_an_international_host_is_listed_in_its_ascii_form_and_the_list_is_plain_json(client, blank): + listed = one_with_control(client, '') + assert [item["host"] for item in listed] == ["xn--bcher-kva.example", "cdn.example.net"] + assert all(item["host"].isascii() for item in listed) + assert json.loads(json.dumps(listed, ensure_ascii=True)) == listed + assert all(set(item) == {"kind", "host", "url"} and all(isinstance(v, str) for v in item.values()) for item in listed) + + +def test_a_stylesheet_with_an_unterminated_import_of_96_kib_is_reviewed_within_the_bound(client, blank): + stalling = "h1{color:#123456}\n@import " + "a" * (96 * 1024) + data = zip_of({"index.html": page("Stall", "

x

", ''), "css/site.css": stalling}) + r = answered_within(BOUND, lambda: client.post(REVIEW, content=data)) + assert r.status_code == 200, r.text[:400] + found = r.json()["pages"][0] + assert [item["host"] for item in found["outside"]] == ["cdn.example.net"] + assert client.get("/api/health").status_code == 200 diff --git a/backend/tests/site_import/test_outside_files.py b/backend/tests/site_import/test_outside_files.py new file mode 100644 index 00000000..f2c8222c --- /dev/null +++ b/backend/tests/site_import/test_outside_files.py @@ -0,0 +1,235 @@ +import pytest + +from site_zips import page, zip_of + +REVIEW = "/api/library/import-site/review" +PASTE = "/api/library/import-html" +EARLIER_PAGE_FIELDS = {"file", "name", "title", "description", "route", "newRoute", "replaces", "bytes", "warnings"} +EARLIER_REVIEW_FIELDS = {"pages", "assets", "supportFiles", "skipped", "ignored", "canReplace", "replaceNote", "notes", "revision"} +EARLIER_PASTE_FIELDS = {"canRedo", "canUndo", "revision", "site", "root", "warnings"} + + +@pytest.fixture() +def blank(client): + r = client.post("/api/new", json={"name": "Blank", "blank": True}) + assert r.status_code == 200, r.text + return r.json() + + +def zipped(client, files): + r = client.post(REVIEW, content=zip_of(files)) + assert r.status_code == 200, r.text[:400] + return r.json() + + +def loose(client, files): + r = client.post(REVIEW, json={"files": [{"name": name, "html": html} for name, html in files.items()]}) + assert r.status_code == 200, r.text[:400] + return r.json() + + +def page_of(review, file): + return next(p for p in review["pages"] if p["file"] == file) + + +def outside(review, file="index.html"): + found = page_of(review, file) + assert "outside" in found, f"the review of {file} has no outside list: {sorted(found)}" + return found["outside"] + + +def entries(listed): + return [(item["kind"], item["host"], item["url"]) for item in listed] + + +def link(href, rel="stylesheet"): + return f'' + + +def script(src): + return f'' + + +MIXED = page( + "Stopwatch", + "

Lap times

" + script("https://code.example.org/late.js") + link("https://cdn.example.net/print.css"), + link("https://cdn.example.net/look.css") + script("https://code.example.org/tick.js") + link("https://fonts.example.com/face.css"), +) +MIXED_LIST = [ + ("stylesheet", "cdn.example.net", "https://cdn.example.net/look.css"), + ("script", "code.example.org", "https://code.example.org/tick.js"), + ("stylesheet", "fonts.example.com", "https://fonts.example.com/face.css"), + ("script", "code.example.org", "https://code.example.org/late.js"), + ("stylesheet", "cdn.example.net", "https://cdn.example.net/print.css"), +] + + +def test_a_page_names_each_outside_stylesheet_and_script_with_its_kind_host_and_address_in_document_order(client, blank): + assert entries(outside(zipped(client, {"index.html": MIXED}))) == MIXED_LIST + + +def test_the_same_page_picked_as_a_loose_file_names_the_same_outside_files_as_inside_a_zip(client, blank): + as_zip = outside(zipped(client, {"index.html": MIXED})) + as_file = outside(loose(client, {"index.html": MIXED})) + assert as_file == as_zip + assert entries(as_file) == MIXED_LIST + + +def test_an_outside_file_the_page_names_twice_is_listed_once(client, blank): + twice = page("Twice", script("https://code.example.org/a.js"), link("https://cdn.example.net/a.css") + script("https://code.example.org/a.js") + link("https://cdn.example.net/a.css")) + assert entries(outside(loose(client, {"index.html": twice}))) == [ + ("stylesheet", "cdn.example.net", "https://cdn.example.net/a.css"), + ("script", "code.example.org", "https://code.example.org/a.js"), + ] + + +@pytest.mark.parametrize("count, kind, tag", [(21, "script", script), (25, "script", script), (300, "stylesheet", link)]) +def test_a_page_with_more_than_twenty_outside_files_lists_the_first_twenty_and_counts_the_rest(client, blank, count, kind, tag): + many = page("Many", "

many

", "".join(tag(f"https://cdn.example.net/f{i}.{'js' if kind == 'script' else 'css'}") for i in range(count))) + for review in (loose(client, {"index.html": many}), zipped(client, {"index.html": many})): + found = page_of(review, "index.html") + assert [item["url"] for item in outside(review)] == [f"https://cdn.example.net/f{i}.{'js' if kind == 'script' else 'css'}" for i in range(20)] + assert {item["kind"] for item in found["outside"]} == {kind} + assert found["outsideMore"] == count - 20 + + +def test_a_page_with_twenty_outside_files_lists_all_of_them_and_counts_none_more(client, blank): + twenty = page("Twenty", "

twenty

", "".join(script(f"https://code.example.org/f{i}.js") for i in range(20))) + found = page_of(loose(client, {"index.html": twenty}), "index.html") + assert len(found["outside"]) == 20 + assert found["outsideMore"] == 0 + + +def test_a_page_with_no_outside_files_gets_an_empty_list_and_every_earlier_field_as_written(client, blank): + plain = page("Opening hours", '

Open daily

', link("css/site.css"), "When we are open") + review = zipped(client, {"hours.html": plain, "css/site.css": "h1{color:#123456}", "js/app.js": "document.title = 'x';"}) + assert set(review) == EARLIER_REVIEW_FIELDS + found = page_of(review, "hours.html") + assert set(found) == EARLIER_PAGE_FIELDS | {"outside", "outsideMore", "outsideWarnings"} + assert (found["outside"], found["outsideMore"], found["outsideWarnings"]) == ([], 0, []) + assert (found["name"], found["title"], found["description"], found["newRoute"], found["warnings"]) == ("Opening hours", "Opening hours", "When we are open", "/hours", []) + assert found["bytes"] == len(plain.encode("utf-8")) + + +def test_naming_outside_files_changes_none_of_the_pages_other_fields_but_its_size_and_warnings(client, blank): + body = "

Lap times

" + without = page("Stopwatch", body, "", "Time your laps") + with_outside = page("Stopwatch", body, link("https://cdn.example.net/look.css") + script("https://code.example.org/tick.js"), "Time your laps") + plain = page_of(zipped(client, {"index.html": without}), "index.html") + loading = page_of(zipped(client, {"index.html": with_outside}), "index.html") + assert plain["outside"] == [] and len(loading["outside"]) == 2 + kept = EARLIER_PAGE_FIELDS - {"bytes", "warnings"} + assert {k: loading[k] for k in kept} == {k: plain[k] for k in kept} + assert plain["warnings"] == [] + assert any("https://code.example.org/tick.js" in w for w in loading["warnings"]), loading["warnings"] + assert any("https://cdn.example.net/look.css" in w for w in loading["warnings"]), loading["warnings"] + + +@pytest.mark.parametrize("reference", ["data:text/javascript,document.title='x'", "blob:https://cdn.example.net/1f2e3d", "DATA:text/css,body{}"]) +def test_data_and_blob_addresses_are_not_outside_files(client, blank, reference): + sample = page("Inline", "

x

", script(reference) + link(reference) + script("https://control.example.net/c.js")) + assert entries(outside(loose(client, {"index.html": sample}))) == [("script", "control.example.net", "https://control.example.net/c.js")] + + +@pytest.mark.parametrize("rel", ["preconnect", "icon", "dns-prefetch", "shortcut icon"]) +def test_a_link_that_is_not_a_stylesheet_is_not_an_outside_stylesheet(client, blank, rel): + sample = page("Links", "

x

", link("https://hints.example.net/x", rel) + link("https://cdn.example.net/look.css")) + assert entries(outside(loose(client, {"index.html": sample}))) == [("stylesheet", "cdn.example.net", "https://cdn.example.net/look.css")] + + +def test_a_script_and_a_stylesheet_inside_the_archive_are_local_and_not_listed(client, blank): + sample = page("Local", script("js/app.js") + script("/js/more.js"), link("css/site.css") + link("./css/print.css") + script("https://code.example.org/tick.js")) + review = zipped(client, {"index.html": sample, "css/site.css": "h1{color:red}", "css/print.css": "h1{color:blue}", "js/app.js": "1;", "js/more.js": "2;"}) + assert entries(outside(review)) == [("script", "code.example.org", "https://code.example.org/tick.js")] + + +def test_a_protocol_relative_address_is_an_outside_file_of_its_host(client, blank): + sample = page("Relative", script("//code.example.org/tick.js"), link("//cdn.example.net/look.css")) + listed = outside(loose(client, {"index.html": sample})) + assert [(item["kind"], item["host"]) for item in listed] == [("stylesheet", "cdn.example.net"), ("script", "code.example.org")] + assert [item["url"].split("/")[2] for item in listed] == ["cdn.example.net", "code.example.org"] + + +def test_an_upper_case_scheme_and_host_are_listed_in_lower_case(client, blank): + sample = page("Upper", "

x

", link("HTTPS://CDN.EXAMPLE.NET/Look.css") + script("Http://Code.Example.ORG/Tick.js")) + listed = outside(loose(client, {"index.html": sample})) + assert [item["host"] for item in listed] == ["cdn.example.net", "code.example.org"] + assert [item["url"].split("/")[2] for item in listed] == ["cdn.example.net", "code.example.org"] + assert [item["url"].split(":")[0] for item in listed] == ["https", "http"] + + +def test_an_import_of_an_outside_stylesheet_counts_as_a_stylesheet_from_that_host_from_a_local_stylesheet_and_from_a_style_block(client, blank): + sample = page("Imports", "

x

", link("css/site.css") + '') + review = zipped(client, { + "index.html": sample, + "css/site.css": '@import url(https://fonts.example.com/face.css);\n@import "base.css";\nh1{color:red}', + "css/base.css": "@import 'https://deep.example.net/deep.css';\nh2{color:blue}", + }) + assert entries(outside(review)) == [ + ("stylesheet", "fonts.example.com", "https://fonts.example.com/face.css"), + ("stylesheet", "deep.example.net", "https://deep.example.net/deep.css"), + ("stylesheet", "style.example.org", "https://style.example.org/block.css"), + ] + + +def test_five_files_from_one_host_are_five_entries_of_that_host_and_a_repeated_file_is_not_a_sixth(client, blank): + five = page("Five", "

x

", "".join(script(f"https://five.example.net/s{i}.js") for i in range(5)) + script("https://five.example.net/s2.js")) + listed = outside(loose(client, {"index.html": five})) + assert [item["host"] for item in listed] == ["five.example.net"] * 5 + assert [item["url"] for item in listed] == [f"https://five.example.net/s{i}.js" for i in range(5)] + + +def test_in_a_zip_of_three_pages_only_the_page_that_loads_outside_files_names_them(client, blank): + review = zipped(client, { + "index.html": page("Home", "

Home

", link("css/site.css")), + "about.html": page("About", "

About

", link("https://cdn.example.net/look.css") + script("https://code.example.org/tick.js")), + "contact.html": page("Contact", "

Contact

"), + "css/site.css": "h1{color:red}", + }) + named = {p["file"]: [item["host"] for item in p["outside"]] for p in review["pages"]} + assert named == {"index.html": [], "about.html": ["cdn.example.net", "code.example.org"], "contact.html": []} + + +def test_the_paste_route_answers_with_the_pages_outside_files_beside_its_earlier_fields(client, blank): + pasted = page("Stopwatch", "

Lap times

", link("https://cdn.example.net/look.css") + script("//code.example.org/tick.js")) + r = client.post(PASTE, json={"html": pasted}) + assert r.status_code == 200, r.text[:400] + answer = r.json() + assert set(answer) == EARLIER_PASTE_FIELDS | {"outside", "outsideMore"} + assert [(item["kind"], item["host"]) for item in answer["outside"]] == [("stylesheet", "cdn.example.net"), ("script", "code.example.org")] + assert answer["outsideMore"] == 0 + section = answer["site"]["extensions"]["code"]["sections"][answer["root"]] + assert section["html"] == "

Lap times

" + assert answer["revision"] == client.get("/api/state").json()["revision"] + + +def covered_warnings(found): + assert "outsideWarnings" in found, f"the review has no outsideWarnings: {sorted(found)}" + assert all(isinstance(i, int) and 0 <= i < len(found["warnings"]) for i in found["outsideWarnings"]), found + return [found["warnings"][i] for i in found["outsideWarnings"]] + + +def test_the_warnings_that_the_outside_list_names_in_full_are_pointed_at_and_the_warnings_stay_as_they_were(client, blank): + head = link("https://cdn.example.net/look.css") + script("https://code.example.org/tick.js") + '' + found = page_of(loose(client, {"index.html": page("Stopwatch", "

x

", head)}), "index.html") + covered = covered_warnings(found) + assert len(covered) == 2, found + script_line = next(w for w in covered if "script" in w) + sheet_line = next(w for w in covered if "stylesheet" in w) + assert "https://code.example.org/tick.js" in script_line and "cdn.example.net" not in script_line + assert "https://cdn.example.net/look.css" in sheet_line and "code.example.org" not in sheet_line + left = [w for i, w in enumerate(found["warnings"]) if i not in found["outsideWarnings"]] + assert len(left) == 1 and "https://style.example.org/block.css" in left[0], "the @import warning says more than the list and must not be pointed at" + + +@pytest.mark.parametrize("case, head", [ + ("a data script beside an outside one", script("data:text/javascript,1") + script("https://code.example.org/tick.js")), + ("a refused host beside a good one", script("https://under_score.example.net/x.js") + script("https://code.example.org/tick.js")), + ("twenty-one outside scripts", "".join(script(f"https://code.example.org/f{i}.js") for i in range(21))), +]) +def test_a_script_warning_that_counts_a_file_the_list_does_not_name_is_not_pointed_at(client, blank, case, head): + found = page_of(loose(client, {"index.html": page("Partly named", "

x

", head)}), "index.html") + assert found["outside"], f"{case}: nothing was listed, so the page was not read" + script_lines = [i for i, w in enumerate(found["warnings"]) if "external script" in w] + assert len(script_lines) == 1, found["warnings"] + assert script_lines[0] not in covered_warnings(found) and script_lines[0] not in found["outsideWarnings"], f"{case}: {found}" From 98a0e32942e8badec7d33c67cf1de97b30de5508 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 17:27:02 -0500 Subject: [PATCH 13/38] test(editor): the rules kept for a script after a conversion, where exports are saved on the page side, and Search properties as a list that goes nowhere --- .../tests/unit/convert/kept-rules.test.ts | 180 ++++++++++++++++++ frontend/tests/unit/inspector/search.test.ts | 28 ++- frontend/tests/unit/ui/export-folder.test.ts | 154 +++++++++++++++ 3 files changed, 346 insertions(+), 16 deletions(-) create mode 100644 frontend/tests/unit/convert/kept-rules.test.ts create mode 100644 frontend/tests/unit/ui/export-folder.test.ts diff --git a/frontend/tests/unit/convert/kept-rules.test.ts b/frontend/tests/unit/convert/kept-rules.test.ts new file mode 100644 index 00000000..0b42cf9a --- /dev/null +++ b/frontend/tests/unit/convert/kept-rules.test.ts @@ -0,0 +1,180 @@ +import { describe, expect, it } from 'vitest'; +import { bodyQualified, emptyOutcome, guardSelector, scriptWords, selectorList, subjectClasses, summary } from '../../../src/features/convert/rules'; +import { t, tn } from '../../../src/i18n'; + +const GUARD = ':where(:not([data-fw-node]))'; + +function board(): HTMLElement { + const root = document.createElement('section'); + root.setAttribute('data-fw-node', 'root'); + root.innerHTML = '

Converted

Built

Card
'; + document.body.replaceChildren(root); + return root; +} + +const ids = (root: Element, selector: string): string[] => Array.from(root.querySelectorAll(selector)).map(e => e.id); + +describe('a selector list splits where CSS splits it', () => { + it('at top-level commas only', () => { + expect(selectorList('h1, .card > p,li')).toEqual(['h1', '.card > p', 'li']); + expect(selectorList(' main .card:hover ')).toEqual(['main .card:hover']); + }); + + it('not at the commas inside :is(), :not() or an :nth-child( of ) list', () => { + expect(selectorList(':is(.a, .b) > p, :not(.c, .d), li:nth-child(2n+1 of .x, .y)')).toEqual([':is(.a, .b) > p', ':not(.c, .d)', 'li:nth-child(2n+1 of .x, .y)']); + }); + + it('not at a comma inside an attribute value, quoted either way, or an escaped comma in a class name', () => { + expect(selectorList('a[title="x, y"], b[data-k=\'p,q\'], .one\\,two, c')).toEqual(['a[title="x, y"]', 'b[data-k=\'p,q\']', '.one\\,two', 'c']); + }); + + it('a closing style tag inside a quoted attribute value stays part of its selector', () => { + expect(selectorList('a[title=", y"], b')).toEqual(['a[title=", y"]', 'b']); + }); +}); + +describe('the classes the subject of a selector requires', () => { + it('are those of the compound after the last combinator', () => { + expect(subjectClasses('.list .item.open')).toEqual(['item', 'open']); + expect(subjectClasses('.a > .b + .c ~ .d')).toEqual(['d']); + expect(subjectClasses('.card p')).toEqual([]); + }); + + it('include a class before a pseudo-class or pseudo-element, with one or two colons', () => { + expect(subjectClasses('#top .card:hover')).toEqual(['card']); + expect(subjectClasses('.pill::before')).toEqual(['pill']); + expect(subjectClasses('.pill:after')).toEqual(['pill']); + }); + + it('leave out classes inside :not() and :is(), which a matching element need not carry', () => { + expect(subjectClasses('div:not(.hidden)')).toEqual([]); + expect(subjectClasses('.card:is(.a, .b)')).toEqual(['card']); + }); + + it('read a dot or a space inside an attribute value as part of the value', () => { + expect(subjectClasses('.tag[title=".fake other"]')).toEqual(['tag']); + }); + + it('read an escaped character as part of the class name', () => { + expect(subjectClasses('.md\\:wide')).toEqual(['md:wide']); + }); +}); + +describe('a guarded selector reaches what the script builds and never a converted element', () => { + it('a type or id selector, guarded, matches the built paragraph and not the converted one', () => { + const root = board(); + expect(ids(root, 'p')).toEqual(['converted', 'built']); + expect(ids(root, guardSelector('p', GUARD))).toEqual(['built']); + expect(ids(root, guardSelector('[data-fw-node="deck"] > #built', GUARD))).toEqual(['built']); + }); + + it('a rule written against the converted elements own attribute matches nothing once guarded', () => { + const root = board(); + expect(ids(root, '[data-fw-node]').length).toBeGreaterThan(0); + expect(ids(root, guardSelector('[data-fw-node]', GUARD))).toEqual([]); + }); + + it('a class subject is left able to match a converted element the script gives that class', () => { + const root = board(); + const converted = root.querySelector('#converted')!; + expect(converted.matches(guardSelector('.card', GUARD))).toBe(false); + converted.classList.add('card'); + expect(converted.matches(guardSelector('.card', GUARD))).toBe(true); + }); + + it('the guard goes in front of a pseudo-element, so the selector still names it', () => { + const root = board(); + const guarded = guardSelector('p::before', GUARD); + expect(guarded.endsWith('::before')).toBe(true); + expect(ids(root, guarded.slice(0, -'::before'.length))).toEqual(['built']); + }); +}); + +describe('a selector that asks more of the body than being the body', () => { + it('is one with a class, id, pseudo-class or attribute on body, after an optional html or :root', () => { + expect(bodyQualified('body.dark .card')).toBe(true); + expect(bodyQualified('BODY#main p')).toBe(true); + expect(bodyQualified('html > body:has(.open) p')).toBe(true); + expect(bodyQualified(':root body[data-theme] p')).toBe(true); + }); + + it('is not plain body, a custom element whose name starts with body, or a class named body', () => { + expect(bodyQualified('body .card')).toBe(false); + expect(bodyQualified('body')).toBe(false); + expect(bodyQualified('body-wrap .card')).toBe(false); + expect(bodyQualified('main.body p')).toBe(false); + }); +}); + +describe('the words a script is written with', () => { + it('are names and the words inside its strings, with hyphens and underscores kept', () => { + const words = new Set(); + scriptWords('el.classList.add(\'is-open\'); node.className = "card_2 pill";', words); + for (const word of ['el', 'classList', 'add', 'is-open', 'node', 'className', 'card_2', 'pill']) expect(words.has(word)).toBe(true); + expect(words.has('is')).toBe(false); + }); + + it('stop at the limit given', () => { + const words = new Set(); + scriptWords('alpha beta gamma delta epsilon', words, 3); + expect(words.size).toBe(3); + }); +}); + +describe('the result sentence about kept rules', () => { + it('says how many style rules were kept for what the script builds, in the singular for one', () => { + expect(summary({ ...emptyOutcome(), converted: 20, parts: { script: 1 }, kept: 14 }, t, tn)).toBe('Converted 20 elements. 1 part stayed as code: a script. Kept 14 style rules for the content the page\'s script builds.'); + expect(summary({ ...emptyOutcome(), converted: 2, kept: 1 }, t, tn)).toBe('Converted 2 elements. Kept 1 style rule for the content the page\'s script builds.'); + }); + + it('says when checking took too long and every rule was kept, without also claiming they were checked', () => { + const said = summary({ ...emptyOutcome(), converted: 3, kept: 40, keptAll: 40 }, t, tn); + expect(said).toBe('Converted 3 elements. Kept 40 style rules for the content the page\'s script builds without checking which ones the converted elements use: checking took too long, so every rule was kept.'); + }); + + it('names the rules left out past the bounds of 3000 rules and 192 KiB', () => { + const said = summary({ ...emptyOutcome(), converted: 1, kept: 3000, keptOver: 17000 }, t, tn); + expect(said).toContain('Kept 3000 style rules for the content the page\'s script builds.'); + expect(said).toContain('17000 more style rules were left out: at most 3000 rules and 192 KiB are kept for a script.'); + }); + + it('says when the kept rules were left out because the page code would be too large, and when names clashed with the site', () => { + expect(summary({ ...emptyOutcome(), converted: 4, keptDropped: 30 }, t, tn)).toBe('Converted 4 elements. The 30 style rules kept for the content the page\'s script builds were left out because the page\'s code would be too large.'); + expect(summary({ ...emptyOutcome(), converted: 4, kept: 5, keptClash: 2 }, t, tn)).toContain('2 fonts or registered properties from the page\'s stylesheet were left out because the site already uses their names.'); + }); + + it('says nothing about style rules when none were kept', () => { + const said = summary({ ...emptyOutcome(), converted: 20, parts: { script: 1 } }, t, tn); + expect(said).toBe('Converted 20 elements. 1 part stayed as code: a script.'); + expect(said).not.toContain('style rule'); + }); +}); + +describe('hostile selectors and scripts', () => { + const long = '.a '.repeat(66_667); + + it('a 200,000 character selector splits, gives its subject and is guarded without throwing', () => { + expect(long.length).toBeGreaterThanOrEqual(200_000); + expect(selectorList(long)).toHaveLength(1); + expect(subjectClasses(long.trim())).toEqual(['a']); + expect(guardSelector(long.trim() + ' p', GUARD).endsWith(`p${GUARD}`)).toBe(true); + expect(bodyQualified(long)).toBe(false); + }); + + it('unbalanced brackets and an unclosed quote do not split the rest of the list or throw', () => { + const open = 'a(' + 'b, '.repeat(70_000); + expect(selectorList(open)).toEqual([open.trim()]); + const quoted = 'a[title="' + 'x, '.repeat(70_000); + expect(selectorList(quoted)).toEqual([quoted.trim()]); + expect(() => subjectClasses(')))]]] .ok' + '['.repeat(100_000))).not.toThrow(); + expect(subjectClasses(')))]]] .ok')).toEqual(['ok']); + expect(() => guardSelector('"'.repeat(200_001), GUARD)).not.toThrow(); + }); + + it('a script of a million characters gives its words within the limit', () => { + const words = new Set(); + scriptWords('w'.repeat(500) + ' x-1;'.repeat(100_000) + 'y'.repeat(400_000), words); + expect(words.has('x-1')).toBe(true); + expect(words.has('w'.repeat(500))).toBe(false); + }); +}); diff --git a/frontend/tests/unit/inspector/search.test.ts b/frontend/tests/unit/inspector/search.test.ts index 1c256e37..5d6a8661 100644 --- a/frontend/tests/unit/inspector/search.test.ts +++ b/frontend/tests/unit/inspector/search.test.ts @@ -49,11 +49,9 @@ function tab(id: string, name: string, sections: HTMLElement[]): SearchTab { let search: InspectorSearch; let input: HTMLInputElement; let scroll: HTMLElement; -let picked: string[]; beforeEach(() => { document.body.replaceChildren(); - picked = []; const tabs = [ tab('design', 'Design', [ section('Appearance', [{ label: 'Background', style: 'background' }, { label: 'Radius', style: 'border-radius' }, { label: 'Shadow', style: 'box-shadow' }, { label: 'Object fit', style: 'object-fit', hidden: true }]), @@ -73,7 +71,7 @@ beforeEach(() => { scroll = document.createElement('div'); scroll.append(...tabs.map(entry => entry.pane)); document.body.append(head, ...tabs.map(entry => entry.button), scroll); - search = installInspectorSearch({ after: head, scroll, tabs, select: id => { picked.push(id); } }); + search = installInspectorSearch({ after: head, scroll, tabs }); input = document.querySelector('.inspector-search-input')!; }); @@ -83,7 +81,7 @@ function query(value: string): void { input.dispatchEvent(new Event('input', { bubbles: true })); } const names = (): string[] => Array.from(document.querySelectorAll('.inspector-result')).map(row => row.querySelector('.inspector-result-name')!.textContent || ''); -const groups = (): string[] => Array.from(document.querySelectorAll('.inspector-results-group')).map(row => row.textContent || ''); +const groups = (): string[] => Array.from(document.querySelectorAll('.inspector-result-place')).map(row => row.textContent || ''); function key(name: string): void { input.dispatchEvent(new KeyboardEvent('keydown', { key: name, bubbles: true, cancelable: true })); } @@ -200,22 +198,20 @@ describe('what a query never lists', () => { }); describe('going to a result and back', () => { - it('Enter on a result switches to its tab, opens its folded section and focuses the field', () => { + it('Enter, the arrow keys and a click on a result go nowhere: the folded section stays folded and focus stays in the box', () => { query('alternative'); - key('Enter'); - expect(picked).toEqual(['content']); + expect(names()).toContain('Alternative text'); const target = document.querySelector('[data-attr="alt"]')!; - expect(target.closest('.inspector-section')!.classList.contains('is-collapsed')).toBe(false); - expect(document.activeElement).toBe(target); - }); - - it('Down then Enter goes to the second result', () => { - query('spacing'); - const second = names()[1]; + const folded = target.closest('.inspector-section')!; + expect(folded.classList.contains('is-collapsed')).toBe(true); + const before = document.body.innerHTML; + key('Enter'); key('ArrowDown'); key('Enter'); - const label = document.activeElement?.closest('.field')?.querySelector('.field-label')?.textContent || ''; - expect(label.startsWith(second)).toBe(true); + document.querySelector('.inspector-result')!.click(); + expect(folded.classList.contains('is-collapsed')).toBe(true); + expect(document.activeElement).toBe(input); + expect(document.body.innerHTML).toBe(before); }); it('Escape clears the search and shows the panel again at the same scroll position', () => { diff --git a/frontend/tests/unit/ui/export-folder.test.ts b/frontend/tests/unit/ui/export-folder.test.ts new file mode 100644 index 00000000..fdc13008 --- /dev/null +++ b/frontend/tests/unit/ui/export-folder.test.ts @@ -0,0 +1,154 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +type Folder = typeof import('../../../src/features/export-folder'); +type Downloads = typeof import('../../../src/ui/downloads'); +type Answer = unknown | ((args: Record | undefined) => unknown); + +const KEY = 'formweb.export-folder'; +const WORDS = { desktop: 'Saved {0} to your Downloads folder.', placed: 'Saved {0} to {1}.', browser: 'Downloaded {0}. Your browser lists it with its downloads.' }; + +let calls: Array<[string, Record | undefined]>; +let answers: Record; + +function shell(): void { + (window as unknown as { __TAURI__?: unknown }).__TAURI__ = { + core: { + invoke(command: string, args?: Record): Promise { + calls.push([command, args]); + const answer = answers[command]; + if (answer instanceof Error) return Promise.reject(answer); + return Promise.resolve(typeof answer === 'function' ? (answer as (a: typeof args) => unknown)(args) : answer); + }, + }, + }; +} + +async function load(stored: string | null, desktop = true): Promise<{ folder: Folder; downloads: Downloads }> { + if (stored === null) localStorage.removeItem(KEY); + else localStorage.setItem(KEY, stored); + if (desktop) shell(); + vi.resetModules(); + const folder = await import('../../../src/features/export-folder'); + const downloads = await import('../../../src/ui/downloads'); + return { folder, downloads }; +} + +function notice(): { show: (message: string) => void; said: string[] } { + const said: string[] = []; + return { said, show: (message: string) => { said.push(message); } }; +} + +beforeEach(() => { + calls = []; + answers = { set_export_place: (args: Record | undefined) => ({ mode: args?.mode, folder: args?.path }) }; + localStorage.clear(); +}); + +afterEach(() => { + delete (window as unknown as { __TAURI__?: unknown }).__TAURI__; + localStorage.clear(); +}); + +describe('the stored choice of where exports are saved', () => { + it('means the Downloads folder for every malformed stored value', async () => { + const malformed = ['{not json', 'null', '[]', '"ask"', '42', '{"mode":"folder"}', '{"mode":"folder","path":""}', '{"mode":"folder","path":7}', '{"mode":"elsewhere","path":"/home/me/Exports"}', '{"mode":"ASK","path":""}', JSON.stringify({ mode: 'folder', path: '/' + 'a'.repeat(5000) })]; + for (const value of malformed) { + const { folder } = await load(value); + expect(folder.exportChoice(), `stored ${value.slice(0, 40)}`).toEqual({ mode: 'downloads', path: '' }); + } + }); + + it('keeps a well formed ask or folder choice, so a malformed one really is refused', async () => { + expect((await load('{"mode":"ask","path":""}')).folder.exportChoice()).toEqual({ mode: 'ask', path: '' }); + expect((await load('{"mode":"folder","path":"/home/me/Exports/café sites/"}')).folder.exportChoice()).toEqual({ mode: 'folder', path: '/home/me/Exports/café sites/' }); + }); + + it('is handed to the shell once when the page loads', async () => { + await load('{"mode":"folder","path":"/home/me/Exports"}'); + expect(calls).toEqual([['set_export_place', { mode: 'folder', path: '/home/me/Exports', forget: false }]]); + }); + + it('falls back to Downloads and forgets the stored folder when the shell answers it has no such folder', async () => { + answers.set_export_place = { mode: 'downloads', folder: '' }; + const { folder } = await load('{"mode":"folder","path":"C:\\\\Users\\\\me\\\\Startup"}'); + await vi.waitFor(() => expect(folder.exportChoice()).toEqual({ mode: 'downloads', path: '' })); + expect(localStorage.getItem(KEY)).toBeNull(); + }); + + it('after Reset All Preferences is Downloads again and the shell is told to forget its folder', async () => { + const { folder } = await load('{"mode":"folder","path":"/home/me/Exports"}'); + expect(localStorage.getItem(KEY)).not.toBeNull(); + calls = []; + folder.resetExportFolder(); + expect(folder.exportChoice()).toEqual({ mode: 'downloads', path: '' }); + expect(localStorage.getItem(KEY)).toBeNull(); + expect(calls).toEqual([['set_export_place', { mode: 'downloads', path: '', forget: true }]]); + }); +}); + +describe('asking the shell before a download', () => { + it('goes on without asking in Downloads mode and in folder mode', async () => { + answers.ask_export_place = false; + expect(await (await load(null)).folder.beforeDownload('site.zip')).toBe(true); + expect(await (await load('{"mode":"folder","path":"/home/me/Exports"}')).folder.beforeDownload('site.zip')).toBe(true); + expect(calls.filter(([command]) => command === 'ask_export_place')).toEqual([]); + }); + + it('in ask mode goes on only when the shell answers yes, and asks with the file name', async () => { + const { folder } = await load('{"mode":"ask","path":""}'); + answers.ask_export_place = true; + expect(await folder.beforeDownload('harbour-site.zip')).toBe(true); + expect(calls.at(-1)).toEqual(['ask_export_place', { name: 'harbour-site.zip' }]); + for (const no of [false, null, 'true', 1, {}]) { + answers.ask_export_place = no; + expect(await folder.beforeDownload('harbour-site.zip'), `shell answered ${JSON.stringify(no)}`).toBe(false); + } + }); + + it('in ask mode treats an error from the shell as no', async () => { + const { folder } = await load('{"mode":"ask","path":""}'); + answers.ask_export_place = new Error('the dialog could not open'); + expect(await folder.beforeDownload('harbour-site.zip')).toBe(false); + }); + + it('in a browser goes on without asking, whatever is stored', async () => { + const { folder } = await load('{"mode":"ask","path":""}', false); + expect(await folder.beforeDownload('harbour-site.zip')).toBe(true); + expect(calls).toEqual([]); + }); +}); + +describe('delivering a download', () => { + it('in ask mode returns the cancelled value and never fetches when the shell answers no or fails', async () => { + for (const no of [false, new Error('the dialog could not open')]) { + const { downloads } = await load('{"mode":"ask","path":""}'); + answers.ask_export_place = no; + const fetch = vi.fn(() => Promise.resolve(new Headers())); + const done = await downloads.deliver('harbour-site.zip', WORDS, notice() as never, fetch); + expect(done).toBeNull(); + expect(fetch).not.toHaveBeenCalled(); + } + }); + + it('in ask mode fetches exactly once after a yes and returns the headers', async () => { + const { downloads } = await load('{"mode":"ask","path":""}'); + const order: string[] = []; + answers.ask_export_place = () => { order.push('asked'); return true; }; + const headers = new Headers({ 'X-Probe': 'one' }); + const fetch = vi.fn(() => { order.push('fetched'); return Promise.resolve(headers); }); + const done = await downloads.deliver('harbour-site.zip', WORDS, notice() as never, fetch); + expect(done?.get('X-Probe')).toBe('one'); + expect(order).toEqual(['asked', 'fetched']); + }); + + it('through deliverFile says Nothing was saved. after a cancel and reports false', async () => { + const { downloads } = await load('{"mode":"ask","path":""}'); + answers.ask_export_place = false; + const shown = notice(); + downloads.useNotice(shown as never); + const fetch = vi.fn(() => Promise.resolve(new Headers())); + expect(await downloads.deliverFile('qr-home.png', fetch)).toBe(false); + expect(fetch).not.toHaveBeenCalled(); + expect(shown.said).toEqual(['Nothing was saved.']); + }); +}); From 4f8df4d2cd2792691b0cd1db7a157767f034b320 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 17:27:02 -0500 Subject: [PATCH 14/38] test(window): audit markers, where exports are saved with a stand-in for the desktop app, the import review's outside files, a converted page that keeps its script's style rules, and search results that show their place and cannot be picked --- frontend/tests/window/test_audit_markers.py | 878 ++++++++++++++++++ .../tests/window/test_convert_kept_rules.py | 525 +++++++++++ frontend/tests/window/test_export_folder.py | 458 +++++++++ frontend/tests/window/test_import_outside.py | 358 +++++++ frontend/tests/window/test_property_search.py | 36 +- 5 files changed, 2243 insertions(+), 12 deletions(-) create mode 100644 frontend/tests/window/test_audit_markers.py create mode 100644 frontend/tests/window/test_convert_kept_rules.py create mode 100644 frontend/tests/window/test_export_folder.py create mode 100644 frontend/tests/window/test_import_outside.py diff --git a/frontend/tests/window/test_audit_markers.py b/frontend/tests/window/test_audit_markers.py new file mode 100644 index 00000000..a21e88ce --- /dev/null +++ b/frontend/tests/window/test_audit_markers.py @@ -0,0 +1,878 @@ +import hashlib +import io +import json +import re +import urllib.request +import zipfile + +import pytest +from playwright.sync_api import expect + +MARK = re.compile(r"^\d+ issues? on ") +AUDIT = re.compile(r"/api/audit$") +OWN_CHANGE = re.compile(r"/api/(command|batch)$") +SWITCH = "Show audit markers on the page" +ABOUT = "Puts a small marker on each element of this page that has an issue." +WHEN_CLOSED = "Markers show on the page when this dialog is closed." +ON = "Audit markers are on: each element of this page with an issue shows a marker." +OFF = "Audit markers are off." +FAILED = "The audit could not be run, so the audit markers are hidden." +CAP = 200 +QUIET = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(done))))" +ELEMENT_BOX = """(id) => { + const frame = document.querySelector('iframe[title="Website canvas"]'); + const outer = frame.getBoundingClientRect(); + const scale = outer.width / frame.offsetWidth; + const left = outer.left + frame.clientLeft * scale, top = outer.top + frame.clientTop * scale; + for (const node of frame.contentDocument.querySelectorAll(`[data-fw-id="${CSS.escape(id)}"]`)) { + const box = node.getBoundingClientRect(); + if (!box.width && !box.height) continue; + return { left: left + box.left * scale, top: top + box.top * scale, right: left + box.right * scale, bottom: top + box.bottom * scale }; + } + return null; +}""" +SEEN_AREA = """() => { + const frame = document.querySelector('iframe[title="Website canvas"]').getBoundingClientRect(); + const stage = document.querySelector('.stage').getBoundingClientRect(); + return { left: Math.max(frame.left, stage.left), top: Math.max(frame.top, stage.top), right: Math.min(frame.right, stage.right), bottom: Math.min(frame.bottom, stage.bottom) }; +}""" +FIELD_BOXES = """() => [...document.querySelectorAll('.inspector .field, .toolbar button, .toolbar select, .toolbar input')].filter(node => node.getClientRects().length).map(node => { + const box = node.getBoundingClientRect(); + return [box.x, box.y, box.width, box.height].map(Math.round).join(','); +})""" +CANVAS_DOCUMENT = """() => { + const doc = document.querySelector('iframe[title="Website canvas"]').contentDocument; + return [doc.querySelectorAll('*').length, doc.head.children.length, doc.documentElement.outerHTML]; +}""" +AFTER_RESIZE = """(spots) => { + const elementBox = """ + ELEMENT_BOX + """; + window.__afterResize = []; + const look = () => { + let off = 0, shown = 0; + for (const [label, id] of Object.entries(spots)) { + const dot = [...document.querySelectorAll('button[aria-label]')].find(node => node.getAttribute('aria-label') === label); + if (!dot || !dot.checkVisibility()) continue; + const box = elementBox(id), at = dot.getBoundingClientRect(); + if (!box) continue; + shown += 1; + off = Math.max(off, Math.abs(at.left + at.width / 2 - box.right), Math.abs(at.top + at.height / 2 - box.top)); + } + window.__afterResize.push({ width: innerWidth, shown, off: Math.round(off * 10) / 10 }); + }; + addEventListener('resize', () => requestAnimationFrame(() => setTimeout(look))); +}""" +RECORD_STATUS = """() => { + window.__said = []; + const line = document.querySelector('footer.statusbar .status-message'); + new MutationObserver(() => window.__said.push(line.textContent)).observe(line, { childList: true, characterData: true, subtree: true }); +}""" +FOCUSED = "() => { const at = document.activeElement; return { body: at === document.body || at === null, shown: !!at && at.getClientRects().length > 0, label: at ? (at.getAttribute('aria-label') || at.textContent.trim()).slice(0, 60) : '' }; }" + +ISSUES = [ + {"command": "node.update", "params": {"id": "hero-b1", "patch": {"attrs": {"href": "#", "src": "https://example.org/picture.png"}, "interactions": [{"trigger": "hover", "action": "toggle-class", "className": "lit"}]}}}, + {"command": "node.update", "params": {"id": "hero-b2", "patch": {"attrs": {"href": ""}}}}, + {"command": "node.update", "params": {"id": "board-link", "patch": {"attrs": {"href": "#"}}}}, + {"command": "page.update", "params": {"id": "home", "patch": {"seo": {"description": ""}}}}, +] + + +class Requests: + def __init__(self, editor, pattern): + self.editor = editor + self.sent = [] + self.done = [] + editor.page.on("request", lambda r: self.sent.append(r) if pattern.search(r.url) else None) + editor.page.on("requestfinished", lambda r: self.done.append(r) if pattern.search(r.url) else None) + editor.page.on("requestfailed", lambda r: self.done.append(r) if pattern.search(r.url) else None) + + def answered(self): + self.editor.eventually(lambda: len(self.done) == len(self.sent), "every request the window sent to be answered") + + +def quiet(editor, audits): + """Moves the window's clock past every wait the markers may make before asking again (600 ms at most), then waits until + a request sent after that is seen, so every audit request the window made by then has been counted, and answered.""" + editor.page.clock.run_for(3000) + seen = [] + editor.page.on("request", lambda r: seen.append(r) if "after-the-wait" in r.url else None) + editor.page.evaluate("() => fetch('/api/health?after-the-wait')") + editor.eventually(lambda: seen, "the request sent after the wait to be seen") + audits.answered() + + +def audit_answer(editor): + with urllib.request.urlopen(editor.base + "/api/audit", timeout=30) as reply: + return json.loads(reply.read()) + + +def subtree(site, page_id): + page = next(p for p in site["pages"] if p["id"] == page_id) + seen, stack = [], [page["root"]] + while stack: + node = stack.pop() + if node in seen or node not in site["nodes"]: + continue + seen.append(node) + stack.extend(reversed(site["nodes"][node]["children"])) + return seen + + +def label_for(name, count): + return f"1 issue on {name}" if count == 1 else f"{count} issues on {name}" + + +def expected_markers(editor, page_id="home"): + """The marker names a person should see: one per element of the page named in the audit route's own answer.""" + site = editor.site()["site"] + nodes = subtree(site, page_id) + messages = {} + for issue in audit_answer(editor)["issues"]: + if issue.get("node") in nodes: + messages.setdefault(issue["node"], []).append(issue["message"]) + return {label_for(site["nodes"][node]["name"], len(lines)): node for node, lines in messages.items()}, messages + + +def markers(editor): + return editor.page.get_by_role("button", name=MARK) + + +def every_marker(editor): + return editor.page.get_by_role("button", name=MARK, include_hidden=True) + + +def marker(editor, name): + return editor.page.get_by_role("button", name=name, exact=True, include_hidden=True) + + +def names(locator): + return sorted(locator.evaluate_all("nodes => nodes.map(node => node.getAttribute('aria-label'))")) + + +def audit_dialog(editor): + return editor.page.get_by_role("dialog", name="SEO & accessibility audit") + + +def run_audit(editor): + editor.page.locator('[data-cmd="page.audit"]').click() + dialog = audit_dialog(editor) + expect(dialog.locator(".empty-note:visible").first).to_contain_text("found") + return dialog + + +def close_audit(editor): + audit_dialog(editor).get_by_role("button", name="Close", exact=True).click() + expect(audit_dialog(editor)).to_be_hidden() + + +def open_menu(editor, menu, command): + editor.page.locator(f'[data-menu="{menu}"]').click() + return editor.page.locator(f'[role="menu"]:visible [data-command="{command}"]') + + +def view_item(editor): + return open_menu(editor, "View", "view.audit-markers") + + +def make_issues(editor, commands=ISSUES): + before = editor.site()["site"] + editor.command("", commands, batch=True) + editor.changed_from(before) + + +def turn_on(editor): + item = view_item(editor) + expect(item).to_have_attribute("aria-checked", "false") + item.click() + expect(editor.status).to_have_text(ON) + + +def marked(editor): + """Issues on three elements of Home (one of them far down the page) and one on the page itself, markers on.""" + make_issues(editor) + turn_on(editor) + shown, _ = expected_markers(editor) + expect(marker(editor, "3 issues on Hero b1")).to_be_visible() + expect(every_marker(editor)).to_have_count(len(shown)) + return shown + + +def in_view(editor, node): + box, area = editor.page.evaluate(ELEMENT_BOX, node), editor.page.evaluate(SEEN_AREA) + return box is not None and area["top"] <= box["top"] and box["top"] + 24 <= area["bottom"] and area["left"] <= box["left"] and box["right"] <= area["right"] + + +def misplaced(editor, shown): + """Every visible marker whose centre is not on its element's top right corner within 1 px, whose corner is outside the + visible canvas, or which reaches out of the stage.""" + area = editor.page.evaluate(SEEN_AREA) + stage = editor.page.locator(".stage").bounding_box() + wrong = [] + for name in names(markers(editor)): + dot = marker(editor, name).bounding_box() + box = editor.page.evaluate(ELEMENT_BOX, shown[name]) + if dot is None or box is None: + wrong.append((name, dot, box)) + continue + centre = (dot["x"] + dot["width"] / 2, dot["y"] + dot["height"] / 2) + on_corner = abs(centre[0] - box["right"]) <= 1 and abs(centre[1] - box["top"]) <= 1 + corner_seen = area["left"] <= box["right"] <= area["right"] and area["top"] <= box["top"] <= area["bottom"] + in_stage = stage["x"] <= dot["x"] and dot["x"] + dot["width"] <= stage["x"] + stage["width"] + 0.5 and stage["y"] <= dot["y"] and dot["y"] + dot["height"] <= stage["y"] + stage["height"] + 0.5 + if not (on_corner and corner_seen and in_stage): + wrong.append({"marker": name, "centre": centre, "corner": (box["right"], box["top"]), "corner seen": corner_seen, "in stage": in_stage}) + return wrong + + +def placed_at_corners(editor, shown, what): + try: + editor.eventually(lambda: markers(editor).count() and not misplaced(editor, shown), f"every marker at its element's top right corner {what}") + except AssertionError: + raise AssertionError(f"not every marker is centred on its element's top right corner {what}: {misplaced(editor, shown)} (markers shown: {names(markers(editor))})") from None + + +def scroll_canvas(editor, until, what): + frame = editor.page.locator('iframe[title="Website canvas"]').bounding_box() + stage = editor.page.locator(".stage").bounding_box() + editor.page.mouse.move(frame["x"] + frame["width"] / 2, max(frame["y"], stage["y"]) + 200) + for _ in range(40): + if until(): + return + editor.page.mouse.wheel(0, 150) + editor.page.evaluate(QUIET) + assert until(), f"the canvas never scrolled {what}" + + +def select(editor, node): + editor.layer_row(node).click() + expect(editor.layer_row(node)).to_have_attribute("aria-selected", "true") + + +def deleting_from_layers_removes_only(editor, changes, node, start): + """The ordering check behind every 'this key removed nothing': a Delete pressed on a Layers row afterwards must be the + first and only change the window sends, and it removes the element.""" + select(editor, node) + expect(editor.layer_row(node)).to_be_focused() + editor.page.keyboard.press("Delete") + editor.until(lambda site: node not in site["nodes"], f"{node} to be deleted from the Layers row") + changes.answered() + assert len(changes.sent) == 1, f"the window sent {len(changes.sent)} changes, so a key pressed earlier removed something: {[r.post_data for r in changes.sent]}" + editor.undo() + editor.restored_to(start) + + +def design_tab(editor): + return editor.page.locator("aside.inspector").get_by_role("button", name="Design", exact=True).and_(editor.page.locator(":not([data-command])")) + + +def export_files(editor): + with urllib.request.urlopen(editor.base + "/api/export", timeout=60) as reply: + archive = zipfile.ZipFile(io.BytesIO(reply.read())) + return {name: hashlib.sha256(archive.read(name)).hexdigest() for name in archive.namelist()} + + +def test_on_a_fresh_profile_no_marker_shows_before_or_after_an_audit_and_the_view_item_has_no_check(harbour): + make_issues(harbour) + expect(view_item(harbour)).to_have_attribute("aria-checked", "false") + harbour.page.keyboard.press("Escape") + assert markers(harbour).count() == 0 + dialog = run_audit(harbour) + expect(dialog.get_by_role("checkbox", name=SWITCH)).not_to_be_checked() + close_audit(harbour) + harbour.page.evaluate(QUIET) + assert markers(harbour).count() == 0, f"markers show on a fresh profile: {names(markers(harbour))}" + shown, _ = expected_markers(harbour) + turn_on(harbour) + expect(every_marker(harbour)).to_have_count(len(shown)) + + +def test_the_audit_dialog_switch_says_what_it_does_and_after_close_an_element_with_three_issues_has_one_marker_reading_3(harbour): + make_issues(harbour) + _, messages = expected_markers(harbour) + assert len(messages["hero-b1"]) == 3 + dialog = run_audit(harbour) + switch = dialog.get_by_role("checkbox", name=SWITCH) + expect(switch).to_be_visible() + expect(dialog).to_contain_text(ABOUT) + expect(dialog).to_contain_text(WHEN_CLOSED) + switch.check() + expect(harbour.status).to_have_text(ON) + assert markers(harbour).count() == 0, "markers show while the audit dialog covers the editor" + close_audit(harbour) + three = marker(harbour, "3 issues on Hero b1") + expect(three).to_be_visible() + expect(three).to_have_count(1) + expect(three).to_have_text("3") + expect(view_item(harbour)).to_have_attribute("aria-checked", "true") + + +def test_the_markers_of_a_page_are_exactly_the_elements_of_that_page_in_the_audit_answer_with_their_counts(harbour): + shown = marked(harbour) + assert len(shown) == 3, shown + assert names(every_marker(harbour)) == sorted(shown) + for name in names(markers(harbour)): + count = int(name.split(" ")[0]) + expect(marker(harbour, name)).to_have_text(str(count)) + + +def test_a_marker_sits_at_its_elements_top_right_corner_through_scroll_window_size_zoom_and_breakpoint(harbour): + shown = marked(harbour) + placed_at_corners(harbour, shown, "at first") + scroll_canvas(harbour, lambda: harbour.page.evaluate(ELEMENT_BOX, "hero-b1")["top"] < harbour.page.evaluate(SEEN_AREA)["top"] + 300, "the hero up") + placed_at_corners(harbour, shown, "after scrolling the canvas") + harbour.page.set_viewport_size({"width": 900, "height": 800}) + placed_at_corners(harbour, shown, "in a 900 px window") + harbour.page.set_viewport_size({"width": 1440, "height": 900}) + width = harbour.page.get_by_role("spinbutton", name="Canvas viewport width in pixels") + width.fill("1920") + width.press("Enter") + harbour.eventually(lambda: harbour.page.locator('iframe[title="Website canvas"]').evaluate("f => f.getBoundingClientRect().width < f.offsetWidth - 1"), "the canvas to be drawn smaller than its width") + placed_at_corners(harbour, shown, "at 1920 px drawn smaller") + harbour.page.locator('[data-cmd="view.tablet"]').click() + expect(harbour.page.get_by_role("combobox", name="Responsive breakpoint")).to_have_value("tablet") + placed_at_corners(harbour, shown, "under the tablet breakpoint") + + +def test_on_a_window_resize_the_first_frame_painted_after_it_already_shows_every_marker_on_its_corner(harbour): + shown = marked(harbour) + placed_at_corners(harbour, shown, "at first") + harbour.page.evaluate(AFTER_RESIZE, shown) + for width in [1300, 1100, 900, 1200, 1440]: + count = len(harbour.page.evaluate("() => window.__afterResize")) + harbour.page.set_viewport_size({"width": width, "height": 900}) + harbour.eventually(lambda: len(harbour.page.evaluate("() => window.__afterResize")) > count, f"a frame to be painted after the resize to {width} px") + placed_at_corners(harbour, shown, f"at {width} px") + frames = harbour.page.evaluate("() => window.__afterResize") + assert any(frame["shown"] for frame in frames), "no marker was shown in any frame after a resize" + off = [frame for frame in frames if frame["off"] > 1] + assert off == [], f"in {len(off)} of {len(frames)} frames painted right after a resize a marker was away from its corner: {off[:5]}" + + +def test_a_marker_whose_element_is_scrolled_out_of_view_is_hidden_not_kept_at_the_edge(harbour): + shown = marked(harbour) + expect(marker(harbour, "1 issue on Board link")).to_be_hidden() + scroll_canvas(harbour, lambda: in_view(harbour, "board-link") and harbour.page.evaluate(ELEMENT_BOX, "hero-b1")["bottom"] < harbour.page.evaluate(SEEN_AREA)["top"], "board-link into view and the hero out") + expect(marker(harbour, "1 issue on Board link")).to_be_visible() + expect(marker(harbour, "3 issues on Hero b1")).to_be_hidden() + expect(marker(harbour, "1 issue on Hero b2")).to_be_hidden() + placed_at_corners(harbour, shown, "after scrolling the hero away") + + +def test_turning_markers_on_and_off_moves_no_field_or_toolbar_item_and_adds_nothing_to_the_canvas_document(harbour): + make_issues(harbour) + select(harbour, "hero-k") + harbour.page.evaluate(QUIET) + fields, page = harbour.page.evaluate(FIELD_BOXES), harbour.page.evaluate(CANVAS_DOCUMENT) + assert len(fields) > 20 + turn_on(harbour) + expect(marker(harbour, "3 issues on Hero b1")).to_be_visible() + harbour.page.evaluate(QUIET) + assert harbour.page.evaluate(FIELD_BOXES) == fields, "a field or toolbar item moved when the markers came on" + assert harbour.page.evaluate(CANVAS_DOCUMENT) == page, "the canvas document changed when the markers came on" + view_item(harbour).click() + expect(harbour.status).to_have_text(OFF) + harbour.page.evaluate(QUIET) + assert harbour.page.evaluate(FIELD_BOXES) == fields, "a field or toolbar item moved when the markers went off" + assert harbour.page.evaluate(CANVAS_DOCUMENT) == page, "the canvas document changed when the markers went off" + + +def test_a_click_on_a_marker_selects_its_element_names_the_issue_and_lists_every_sentence_without_writing(harbour): + marked(harbour) + _, messages = expected_markers(harbour) + select(harbour, "hero-k") + before = harbour.site() + marker(harbour, "3 issues on Hero b1").click() + expect(harbour.layer_row("hero-b1")).to_have_attribute("aria-selected", "true") + expect(harbour.status).to_contain_text(f"Selected Hero b1: {messages['hero-b1'][0]}") + listing = harbour.page.get_by_role("group", name="Issues on Hero b1") + expect(listing).to_be_visible() + expect(listing.get_by_role("listitem")).to_have_text(messages["hero-b1"]) + expect(audit_dialog(harbour)).to_be_hidden() + assert harbour.site() == before + + +def test_enter_and_space_on_a_focused_marker_select_its_element(harbour): + marked(harbour) + select(harbour, "hero-k") + before = harbour.site() + two = marker(harbour, "1 issue on Hero b2") + two.focus() + harbour.page.keyboard.press("Enter") + expect(harbour.layer_row("hero-b2")).to_have_attribute("aria-selected", "true") + three = marker(harbour, "3 issues on Hero b1") + three.focus() + harbour.page.keyboard.press(" ") + expect(harbour.layer_row("hero-b1")).to_have_attribute("aria-selected", "true") + expect(harbour.page.get_by_role("group", name="Issues on Hero b1")).to_be_visible() + assert harbour.site() == before + + +def test_pointing_at_a_marker_shows_its_sentences_and_changes_neither_selection_nor_page_nor_revision(harbour): + marked(harbour) + _, messages = expected_markers(harbour) + select(harbour, "hero-k") + changes = Requests(harbour, OWN_CHANGE) + before = harbour.site() + three = marker(harbour, "3 issues on Hero b1") + box = three.bounding_box() + harbour.page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2, steps=8) + tip = three.get_attribute("title") + for line in messages["hero-b1"]: + assert line in tip, f"the tooltip {tip!r} misses {line!r}" + harbour.page.evaluate(QUIET) + expect(harbour.layer_row("hero-k")).to_have_attribute("aria-selected", "true") + expect(harbour.page_row("home")).to_have_attribute("aria-current", "page") + expect(harbour.page.get_by_role("group", name="Issues on Hero b1")).to_be_hidden() + assert changes.sent == [] and harbour.site() == before + + +def test_an_issue_fixed_from_outside_loses_its_marker_without_running_the_audit(harbour): + marked(harbour) + before = harbour.site()["site"] + harbour.command("node.update", {"id": "hero-b2", "patch": {"attrs": {"href": "/routes"}}}) + harbour.changed_from(before) + assert "hero-b2" not in [i.get("node") for i in audit_answer(harbour)["issues"]] + expect(marker(harbour, "1 issue on Hero b2")).to_have_count(0) + expect(marker(harbour, "3 issues on Hero b1")).to_be_visible() + expect(audit_dialog(harbour)).to_be_hidden() + + +def test_a_new_issue_made_from_outside_brings_a_marker_without_running_the_audit(harbour): + marked(harbour) + expect(marker(harbour, "1 issue on H nav fares")).to_have_count(0) + before = harbour.site()["site"] + harbour.command("node.update", {"id": "h-nav-fares", "patch": {"attrs": {"href": "#"}}}) + harbour.changed_from(before) + shown, _ = expected_markers(harbour) + assert "1 issue on H nav fares" in shown + expect(marker(harbour, "1 issue on H nav fares")).to_be_visible() + expect(every_marker(harbour)).to_have_count(len(shown)) + expect(audit_dialog(harbour)).to_be_hidden() + + +def test_another_page_shows_only_its_own_markers_also_when_the_earlier_pages_answer_arrives_late(harbour): + make_issues(harbour, ISSUES + [{"command": "node.update", "params": {"id": "f-nav-routes", "patch": {"attrs": {"href": "#"}}}}]) + turn_on(harbour) + expect(marker(harbour, "3 issues on Hero b1")).to_be_visible() + audits = Requests(harbour, AUDIT) + held, holding = [], [True] + harbour.page.route(AUDIT, lambda route: held.append(route) if holding else route.continue_()) + before = harbour.site()["site"] + harbour.command("node.update", {"id": "hero-k", "patch": {"text": "Every crossing, every day"}}) + harbour.changed_from(before) + harbour.eventually(lambda: held, "the markers to ask the audit again after the change") + harbour.page_row("p-fares").click() + expect(harbour.page_row("p-fares")).to_have_attribute("aria-current", "page") + holding.clear() + for route in held: + route.continue_() + harbour.eventually(lambda: len(audits.sent) >= 2, "the markers to ask again for the page now shown") + audits.answered() + shown, _ = expected_markers(harbour, "p-fares") + assert sorted(shown) == ["1 issue on F nav routes"] + expect(every_marker(harbour)).to_have_count(1) + expect(marker(harbour, "1 issue on F nav routes")).to_be_visible() + + +def test_an_audit_answer_that_arrives_after_the_site_changed_leaves_no_stale_marker(harbour): + marked(harbour) + audits = Requests(harbour, AUDIT) + held = [] + harbour.page.route(AUDIT, lambda route: held.append(route) if not held else route.continue_()) + harbour.page.locator('[data-cmd="page.audit"]').click() + harbour.eventually(lambda: held, "the audit asked by the Audit button to be held") + before = harbour.site()["site"] + harbour.command("node.update", {"id": "hero-b2", "patch": {"attrs": {"href": "/routes"}}}) + harbour.changed_from(before) + expect(marker(harbour, "1 issue on Hero b2")).to_have_count(0) + held[0].continue_() + expect(audit_dialog(harbour)).to_be_visible() + harbour.page.evaluate(QUIET) + audits.answered() + close_audit(harbour) + shown, _ = expected_markers(harbour) + assert "1 issue on Hero b2" not in shown + harbour.page.evaluate(QUIET) + assert names(every_marker(harbour)) == sorted(shown), f"stale markers after the late answer: {names(every_marker(harbour))}" + + +def live_preview(editor): + open_menu(editor, "View", "view.preview").click() + expect(editor.page.get_by_role("button", name="Back to design")).to_be_visible() + yield + editor.page.get_by_role("button", name="Back to design").click() + expect(editor.page.get_by_role("button", name="Back to design")).to_be_hidden() + + +def full_preview(editor): + editor.page.locator('[data-cmd="view.preview-full"]').click() + dialog = editor.page.get_by_role("dialog", name="Preview as published") + expect(dialog).to_be_visible() + yield + dialog.get_by_role("button", name="Close").click() + expect(dialog).to_be_hidden() + + +def preferences(editor): + open_menu(editor, "Edit", "edit.settings").click() + dialog = editor.page.get_by_role("dialog", name="Preferences") + expect(dialog).to_be_visible() + yield + editor.page.keyboard.press("Escape") + expect(dialog).to_be_hidden() + + +def trial(editor): + select(editor, "hero-h") + editor.page.get_by_role("group", name="Text alignment", exact=True).get_by_role("button", name="Center", exact=True).click() + bar = editor.page.locator("[data-try-bar]") + expect(bar).to_contain_text("Trying: Center") + yield + bar.get_by_role("button", name=re.compile(r"^Revert\b")).click() + expect(bar).to_be_hidden() + + +def text_editing(editor): + editor.canvas.locator('[data-fw-id="hero-h"]').dblclick() + expect(editor.canvas.locator('[data-fw-text="hero-h"][contenteditable="true"]')).to_be_visible() + yield + editor.layer_row("hero-k").click() + expect(editor.canvas.locator('[contenteditable="true"]')).to_have_count(0) + + +def canvas_drag(editor): + editor.canvas.locator('[data-fw-id="hero-h"]').click() + expect(editor.layer_row("hero-h")).to_have_attribute("aria-selected", "true") + box = editor.canvas.locator('[data-fw-id="hero-h"]').bounding_box() + below = editor.canvas.locator('[data-fw-id="hero-p"]').bounding_box() + pointer = editor.canvas_pointer() + pointer.move(box["x"] + 20, box["y"] + box["height"] / 2) + pointer.down() + pointer.move(box["x"] + 20, below["y"] + below["height"] - 3, steps=15, held=True) + expect(editor.page.locator("body")).to_have_class(re.compile(r"\bfw-canvas-dragging\b")) + yield + editor.page.keyboard.press("Escape") + pointer.up() + expect(editor.status).to_have_text("Drag cancelled. Nothing moved.") + + +@pytest.mark.parametrize("state", [live_preview, full_preview, preferences, trial, text_editing, canvas_drag], ids=["live-preview", "full-preview", "dialog", "trial", "text-editing", "canvas-drag"]) +def test_markers_hide_while_the_page_is_previewed_dragged_tried_edited_or_covered_and_come_back_after(harbour, state): + marked(harbour) + count = markers(harbour).count() + assert count == 2 + steps = state(harbour) + next(steps) + expect(markers(harbour)).to_have_count(0) + with pytest.raises(StopIteration): + next(steps) + expect(markers(harbour)).to_have_count(count) + expect(marker(harbour, "3 issues on Hero b1")).to_be_visible() + + +def test_the_view_menu_turns_every_marker_off_at_once_and_back_on_and_the_status_line_says_each(harbour): + marked(harbour) + item = view_item(harbour) + expect(item).to_have_attribute("aria-checked", "true") + item.click() + expect(harbour.status).to_have_text(OFF) + expect(markers(harbour)).to_have_count(0) + expect(view_item(harbour)).to_have_attribute("aria-checked", "false") + harbour.page.keyboard.press("Escape") + dialog = run_audit(harbour) + expect(dialog.get_by_role("checkbox", name=SWITCH)).not_to_be_checked() + close_audit(harbour) + view_item(harbour).click() + expect(harbour.status).to_have_text(ON) + expect(marker(harbour, "3 issues on Hero b1")).to_be_visible() + + +def test_the_choice_survives_a_reload_and_is_kept_in_neither_the_site_nor_the_export(harbour): + make_issues(harbour) + before = harbour.site() + files = export_files(harbour) + turn_on(harbour) + expect(marker(harbour, "3 issues on Hero b1")).to_be_visible() + assert harbour.site() == before + assert export_files(harbour) == files + assert "audit-markers" not in json.dumps(before) + harbour.page.reload() + harbour.page.get_by_role("button", name="Back to Editor").click() + harbour.page_row("home").wait_for() + shown, _ = expected_markers(harbour) + expect(marker(harbour, "3 issues on Hero b1")).to_be_visible() + expect(every_marker(harbour)).to_have_count(len(shown)) + expect(view_item(harbour)).to_have_attribute("aria-checked", "true") + + +def test_reset_all_preferences_turns_the_markers_off(harbour): + marked(harbour) + open_menu(harbour, "Edit", "edit.settings").click() + dialog = harbour.page.get_by_role("dialog", name="Preferences") + dialog.get_by_role("tab", name="General").click() + dialog.get_by_role("button", name="Reset All Preferences...").click() + with harbour.page.expect_navigation(): + dialog.get_by_role("button", name="Reset", exact=True).click() + harbour.page.get_by_role("button", name="Back to Editor").click() + harbour.page_row("home").wait_for() + harbour.canvas.locator('[data-fw-id="hero-b1"]').wait_for() + expect(view_item(harbour)).to_have_attribute("aria-checked", "false") + harbour.page.keyboard.press("Escape") + dialog = run_audit(harbour) + expect(dialog.get_by_role("checkbox", name=SWITCH)).not_to_be_checked() + close_audit(harbour) + harbour.page.evaluate(QUIET) + assert markers(harbour).count() == 0, f"markers show after Reset All Preferences: {names(markers(harbour))}" + + +def test_with_markers_off_a_change_to_the_site_sends_no_audit_request(harbour): + harbour.page.clock.install() + marked(harbour) + audits = Requests(harbour, AUDIT) + before = harbour.site()["site"] + harbour.command("node.update", {"id": "hero-b2", "patch": {"attrs": {"href": "/routes"}}}) + harbour.changed_from(before) + quiet(harbour, audits) + assert len(audits.sent) == 1, f"with markers on, one change sent {len(audits.sent)} audit requests" + view_item(harbour).click() + expect(harbour.status).to_have_text(OFF) + before = harbour.site()["site"] + harbour.command("node.update", {"id": "hero-b2", "patch": {"attrs": {"href": ""}}}) + harbour.changed_from(before) + quiet(harbour, audits) + assert len(audits.sent) == 1, f"with markers off, a change sent {len(audits.sent) - 1} audit requests" + assert markers(harbour).count() == 0 + + +def failing(editor): + editor.page.route(AUDIT, lambda route: route.fulfill(status=500, content_type="application/json", body='{"detail": "the audit failed"}')) + + +def outside_rename(editor, name): + before = editor.site()["site"] + editor.command("node.update", {"id": "hero-k", "patch": {"name": name}}) + editor.changed_from(before) + + +def test_a_failed_audit_hides_the_markers_says_so_once_and_does_not_ask_in_a_loop(harbour): + harbour.page.clock.install() + marked(harbour) + audits = Requests(harbour, AUDIT) + harbour.page.evaluate(RECORD_STATUS) + failing(harbour) + outside_rename(harbour, "Kicker one") + expect(markers(harbour)).to_have_count(0) + expect(harbour.status).to_have_text(FAILED) + quiet(harbour, audits) + assert len(audits.sent) == 1 + open_menu(harbour, "View", "view.design-controls").click() + expect(harbour.status).not_to_have_text(FAILED) + open_menu(harbour, "View", "view.design-controls").click() + outside_rename(harbour, "Kicker two") + quiet(harbour, audits) + assert len(audits.sent) == 2, f"two changes with a failing audit sent {len(audits.sent)} audit requests" + assert harbour.page.evaluate("() => window.__said").count(FAILED) == 1, "the failure was said more than once" + expect(markers(harbour)).to_have_count(0) + select(harbour, "hero-p") + harbour.page.unroute(AUDIT) + outside_rename(harbour, "Kicker three") + expect(marker(harbour, "3 issues on Hero b1")).to_be_visible() + + +def test_after_a_failed_audit_selection_clicks_ask_nothing_and_the_next_site_change_asks_exactly_once(harbour): + harbour.page.clock.install() + marked(harbour) + audits = Requests(harbour, AUDIT) + failing(harbour) + outside_rename(harbour, "Kicker one") + expect(markers(harbour)).to_have_count(0) + quiet(harbour, audits) + assert len(audits.sent) == 1 + for node in ["hero-h", "hero-p", "hero-k", "hero-h", "hero-p", "status-line", "hero-k", "hero-h"]: + harbour.canvas.locator(f'[data-fw-id="{node}"]').click() + expect(harbour.layer_row(node)).to_have_attribute("aria-selected", "true") + quiet(harbour, audits) + assert len(audits.sent) == 1, f"selection clicks after a failure sent {len(audits.sent) - 1} audit requests" + outside_rename(harbour, "Kicker two") + quiet(harbour, audits) + assert len(audits.sent) == 2, f"one site change after a failure sent {len(audits.sent) - 1} audit requests" + + +def test_an_element_removed_from_outside_while_its_marker_has_focus_loses_the_marker_and_focus_goes_to_the_inspector_tab(harbour): + errors = [] + harbour.page.on("pageerror", lambda error: errors.append(str(error))) + marked(harbour) + two = marker(harbour, "1 issue on Hero b2") + two.focus() + expect(two).to_be_focused() + before = harbour.site()["site"] + harbour.command("node.remove", {"id": "hero-b2"}) + harbour.changed_from(before) + expect(marker(harbour, "1 issue on Hero b2")).to_have_count(0) + expect(design_tab(harbour)).to_be_focused() + expect(marker(harbour, "3 issues on Hero b1")).to_be_visible() + assert errors == [] + + +def test_when_the_element_of_a_clicked_marker_is_removed_from_outside_nothing_is_left_saying_it_is_selected(harbour): + errors = [] + harbour.page.on("pageerror", lambda error: errors.append(str(error))) + marked(harbour) + marker(harbour, "1 issue on Hero b2").click() + expect(harbour.status).to_contain_text("Selected Hero b2:") + notice = harbour.page.locator(".fw-notice") + expect(notice).to_contain_text("Selected Hero b2:") + before = harbour.site()["site"] + harbour.command("node.remove", {"id": "hero-b2"}) + harbour.changed_from(before) + expect(marker(harbour, "1 issue on Hero b2")).to_have_count(0) + expect(harbour.status).not_to_contain_text("Hero b2") + expect(notice.filter(has_text="Hero b2")).to_be_hidden() + expect(marker(harbour, "3 issues on Hero b1")).to_be_visible() + assert errors == [] + + +def test_deleting_the_selected_element_removes_its_marker_and_undo_brings_it_back(harbour): + marked(harbour) + start = harbour.site()["site"] + marker(harbour, "1 issue on Hero b2").click() + select(harbour, "hero-b2") + harbour.page.keyboard.press("Delete") + harbour.until(lambda site: "hero-b2" not in site["nodes"], "hero-b2 to be deleted") + expect(marker(harbour, "1 issue on Hero b2")).to_have_count(0) + harbour.undo() + harbour.restored_to(start) + expect(marker(harbour, "1 issue on Hero b2")).to_be_visible() + + +def test_delete_and_backspace_on_a_focused_marker_remove_nothing(harbour): + marked(harbour) + start = harbour.site()["site"] + three = marker(harbour, "3 issues on Hero b1") + three.click() + expect(harbour.layer_row("hero-b1")).to_have_attribute("aria-selected", "true") + expect(three).to_be_focused() + changes = Requests(harbour, OWN_CHANGE) + harbour.page.keyboard.press("Delete") + harbour.page.keyboard.press("Backspace") + expect(three).to_be_visible() + deleting_from_layers_removes_only(harbour, changes, "hero-b1", start) + + +@pytest.mark.parametrize("dock", ["open", "collapsed"]) +@pytest.mark.parametrize("hide", ["scrolled-away", "fixed-from-outside"]) +def test_when_a_focused_marker_hides_focus_lands_on_a_shown_control_and_backspace_removes_nothing(harbour, dock, hide): + marked(harbour) + design = design_tab(harbour) + if dock == "collapsed": + harbour.page.keyboard.press("Control+BracketRight") + expect(design).to_be_hidden() + select(harbour, "hero-k") + start = harbour.site()["site"] + three = marker(harbour, "3 issues on Hero b1") + three.focus() + expect(three).to_be_focused() + changes = Requests(harbour, OWN_CHANGE) + if hide == "scrolled-away": + scroll_canvas(harbour, lambda: harbour.page.evaluate(ELEMENT_BOX, "hero-b1")["bottom"] < harbour.page.evaluate(SEEN_AREA)["top"], "the hero out of view") + expect(three).to_be_hidden() + else: + harbour.command("node.update", {"id": "hero-b1", "patch": {"attrs": {"href": "/fares", "src": None}, "interactions": []}}) + start = harbour.changed_from(start) + expect(three).to_have_count(0) + focus = harbour.page.evaluate(FOCUSED) + assert not focus["body"] and focus["shown"], f"focus went to {focus} when the focused marker hid" + if dock == "open": + expect(design).to_be_focused() + harbour.page.keyboard.press("Backspace") + harbour.page.keyboard.press("Delete") + expect(harbour.layer_row("hero-k")).to_be_visible() + deleting_from_layers_removes_only(harbour, changes, "hero-k", start) + + +def test_issues_without_an_element_are_counted_in_the_dialog_and_get_no_marker(harbour): + make_issues(harbour, ISSUES + [{"command": "page.update", "params": {"id": "p-fares", "patch": {"seo": {"description": ""}}}}]) + loose = [i for i in audit_answer(harbour)["issues"] if not i.get("node")] + assert len(loose) == 2, loose + dialog = run_audit(harbour) + dialog.get_by_role("checkbox", name=SWITCH).check() + expect(dialog).to_contain_text("2 issues have no element, so they have no marker.") + close_audit(harbour) + shown, _ = expected_markers(harbour) + expect(every_marker(harbour)).to_have_count(len(shown)) + expect(harbour.page.get_by_role("button", name=re.compile(r"issues? on Home$"), include_hidden=True)).to_have_count(0) + + +def test_with_more_than_200_elements_with_issues_200_markers_are_drawn_and_the_dialog_says_so(harbour): + links = [{"command": "node.add", "params": {"parent": "root", "node": {"id": f"dead-{i}", "tag": "a", "name": f"Dead {i}", "text": "Dead link", "children": [], "attrs": {"href": "#"}, "styles": {}, "breakpoints": {}}}} for i in range(240)] + make_issues(harbour, ISSUES + links) + shown, _ = expected_markers(harbour) + assert len(shown) > CAP + turn_on(harbour) + expect(marker(harbour, "3 issues on Hero b1")).to_be_visible() + expect(every_marker(harbour)).to_have_count(CAP) + dialog = run_audit(harbour) + expect(dialog).to_contain_text(f"Markers are drawn on the first {CAP} of {len(shown)} elements with issues on this page.") + + +def test_an_element_repeated_by_a_collection_has_one_marker_on_its_first_copy(editor): + editor.open_demo("wenlow-type-day", "speakers") + make_issues(editor, [ + {"command": "node.update", "params": {"id": "hm-spk-card", "patch": {"binding": {"collection": "speakers"}}}}, + {"command": "node.update", "params": {"id": "hm-spk-img", "patch": {"attrs": {"alt": None}}}}, + ]) + copies = editor.canvas.locator('img[data-fw-id="hm-spk-img"]') + expect(copies).not_to_have_count(0) + assert copies.count() > 1 + shown, messages = expected_markers(editor) + assert list(messages) == ["hm-spk-img"] + turn_on(editor) + one = marker(editor, "1 issue on Hm spk img") + expect(one).to_have_count(1) + scroll_canvas(editor, lambda: in_view(editor, "hm-spk-img"), "the first speaker picture into view") + expect(one).to_be_visible() + placed_at_corners(editor, shown, "on the first copy") + + +@pytest.mark.parametrize("command", ["view.tablet", "file.export"]) +def test_after_a_click_on_a_toolbar_button_delete_and_backspace_remove_nothing(harbour, command): + select(harbour, "hero-k") + start = harbour.site()["site"] + proof = Requests(harbour, OWN_CHANGE) + deleting_from_layers_removes_only(harbour, proof, "hero-k", start) + select(harbour, "hero-k") + toolbar_button = harbour.page.locator(f'.toolbar [data-cmd="{command}"]') + if command == "file.export": + with harbour.page.expect_download(): + toolbar_button.click() + expect(harbour.status).to_contain_text("Static site exported") + else: + toolbar_button.click() + expect(harbour.page.get_by_role("combobox", name="Responsive breakpoint")).to_have_value("tablet") + changes = Requests(harbour, OWN_CHANGE) + harbour.page.keyboard.press("Backspace") + harbour.page.keyboard.press("Delete") + expect(harbour.layer_row("hero-k")).to_be_visible() + deleting_from_layers_removes_only(harbour, changes, "hero-k", start) + + +def test_with_a_layers_row_focused_delete_removes_the_selected_element_in_one_undo_step(harbour): + select(harbour, "hero-p") + start = harbour.site()["site"] + changes = Requests(harbour, OWN_CHANGE) + deleting_from_layers_removes_only(harbour, changes, "hero-p", start) + expect(harbour.layer_row("hero-p")).to_be_visible() + + +def test_after_select_in_the_audit_opened_from_the_page_menu_backspace_removes_nothing(harbour): + make_issues(harbour) + start = harbour.site()["site"] + open_menu(harbour, "Page", "page.audit").click() + dialog = audit_dialog(harbour) + expect(dialog.locator(".empty-note:visible").first).to_contain_text("found") + dialog.locator('.audit-row[data-node="hero-b2"]').get_by_role("button", name="Select").click() + expect(dialog).to_be_hidden() + expect(harbour.layer_row("hero-b2")).to_have_attribute("aria-selected", "true") + changes = Requests(harbour, OWN_CHANGE) + harbour.page.keyboard.press("Backspace") + harbour.page.keyboard.press("Delete") + expect(harbour.layer_row("hero-b2")).to_be_visible() + deleting_from_layers_removes_only(harbour, changes, "hero-b2", start) diff --git a/frontend/tests/window/test_convert_kept_rules.py b/frontend/tests/window/test_convert_kept_rules.py new file mode 100644 index 00000000..766ea057 --- /dev/null +++ b/frontend/tests/window/test_convert_kept_rules.py @@ -0,0 +1,525 @@ +import io +import json +import re +import urllib.error +import urllib.request +import zipfile +from urllib.parse import urlsplit + +from playwright.sync_api import expect + +OUTSIDE = "styles.outside.example" + +CARD = { + "background-color": "rgb(24, 32, 48)", + "border-top-width": "3px", + "border-top-style": "solid", + "border-top-color": "rgb(200, 100, 50)", + "padding-top": "14px", + "padding-left": "14px", + "border-top-left-radius": "9px", + "font-size": "19px", + "font-weight": "700", + "color": "rgb(255, 255, 255)", + "letter-spacing": "2px", +} + +BOARD = """Card board +

Card board

+

Waiting

+
+ +""" + +STYLE_RULES = 9 +FOR_BUILT_CONTENT = 4 +AIMED_AT_CONVERTED_ELEMENTS = 1 + +LOOK = "(e, names) => { const s = getComputedStyle(e); return Object.fromEntries(names.map(n => [n, s.getPropertyValue(n)])); }" +MEASURED = ["color", "font-size", "font-weight", "letter-spacing", "margin-top", "outline-style", "background-color", "padding-top", "display", "column-gap", "border-top-style"] + + +def code_sections(site): + return (site.get("extensions", {}).get("code") or {}).get("sections") or {} + + +def nodes_with(site, tag, text): + return [n for n in site["nodes"].values() if n["tag"] == tag and n["text"] == text] + + +def by_attr_id(site, value): + return next(n for n in site["nodes"].values() if n["attrs"].get("id") == value) + + +def written(tmp_path, name, html): + path = tmp_path / name + path.write_text(html, "utf-8") + return path + + +def pick(editor, *paths, command="file.import-html"): + with editor.page.expect_file_chooser() as chooser: + editor.page.evaluate(f"window.formweb.run('{command}')") + chooser.value.set_files([str(p) for p in paths]) + view = editor.page.locator(".fw-lib-site") + expect(view.locator(".fw-lib-site-review .fw-lib-site-item")).to_have_count(len(paths)) + return view + + +def import_as_elements(editor, path, section=False, wait=60_000): + view = pick(editor, path) + if section: + view.get_by_role("radio", name="As a section of this page").click() + view.locator('[data-bring="elements"]').click() + expect(view.locator('[data-bring="elements"]')).to_have_attribute("aria-checked", "true") + view.locator(".fw-lib-insert:not([disabled])").click() + note = view.locator(".fw-lib-note") + expect(note).to_contain_text("Converted", timeout=wait) + return note.inner_text() + + +def import_as_code(editor, *paths): + before = code_sections(editor.site()["site"]) + view = pick(editor, *paths) + view.locator('[data-bring="code"]').click() + view.locator(".fw-lib-insert:not([disabled])").click() + site = editor.until(lambda s: len(code_sections(s)) == len(before) + len(paths), "the pages to arrive as code sections") + return site, [key for key in code_sections(site) if key not in before] + + +def kept_count(sentence): + found = re.search(r"Kept (\d+) style rules? for the content the page's script builds\.", sentence) + assert found, f"the result sentence does not say how many style rules were kept: {sentence!r}" + return int(found.group(1)) + + +def preview(editor): + editor.page.locator('[data-cmd="view.preview-full"]').click() + overlay = editor.page.get_by_role("dialog", name="Preview as published") + expect(overlay.locator("iframe.fw-fp-frame:visible")).to_have_count(1) + return overlay.frame_locator("iframe.fw-fp-frame:visible") + + +def close_preview(editor): + editor.page.keyboard.press("Escape") + expect(editor.page.get_by_role("dialog", name="Preview as published")).to_be_hidden() + + +def exported(editor, folder): + with urllib.request.urlopen(editor.base + "/api/export", timeout=60) as reply: + zipfile.ZipFile(io.BytesIO(reply.read())).extractall(folder) + return folder + + +def published(chromium, file, scripts=True): + context = chromium.new_context(viewport={"width": 1440, "height": 900}, java_script_enabled=scripts) + page = context.new_page() + page.goto(file.as_uri()) + return context, page + + +def look(locator, names): + return locator.evaluate(LOOK, names) + + +def expect_styled_cards(frame, where): + cards = frame.locator("article.card") + expect(cards).to_have_count(3) + for index in range(3): + shown = look(cards.nth(index), list(CARD)) + assert shown == CARD, f"{where}, script-built card {index + 1} does not have the page stylesheet's look: {shown}" + + +def outside_requests(context): + seen = [] + context.on("request", lambda request: seen.append(request.url) if urlsplit(request.url).hostname == OUTSIDE else None) + return seen + + +def test_cards_the_kept_script_builds_are_styled_in_preview_as_the_page_stylesheet_says(editor, tmp_path): + asked = outside_requests(editor.page.context) + import_as_elements(editor, written(tmp_path, "board.html", BOARD)) + frame = preview(editor) + expect_styled_cards(frame, "in Preview") + expect(frame.locator("#status")).to_have_text("Ready") + expect(frame.locator("#status")).to_have_css("color", "rgb(0, 128, 0)") + expect(frame.locator(".spinner").first).to_have_css("animation-name", "cardspin") + assert asked == [], f"a request went to the host of the page's @import: {asked}" + + +def test_cards_the_kept_script_builds_are_styled_in_the_exported_site(editor, chromium, tmp_path): + import_as_elements(editor, written(tmp_path, "board.html", BOARD)) + folder = exported(editor, tmp_path / "export") + context, page = published(chromium, folder / "board" / "index.html") + asked = outside_requests(context) + try: + expect(page.locator("#status")).to_have_text("Ready") + expect_styled_cards(page, "in the export") + expect(page.locator("#status")).to_have_css("color", "rgb(0, 128, 0)") + expect(page.locator(".spinner").first).to_have_css("animation-name", "cardspin") + families = page.evaluate("() => document.fonts.ready.then(() => [...document.fonts].map(f => f.family.replace(/[\"']/g, '')))") + assert "Boardface" in families, f"the font face a kept rule uses is missing from the export: {families}" + assert "Neverface" not in families, f"the font face no kept rule uses came along: {families}" + assert asked == [], f"the exported page asked the host of the page's @import: {asked}" + finally: + context.close() + + +def test_the_result_sentence_says_how_many_style_rules_were_kept_for_the_script(editor, tmp_path): + sentence = import_as_elements(editor, written(tmp_path, "board.html", BOARD)) + count = kept_count(sentence) + low, high = FOR_BUILT_CONTENT, FOR_BUILT_CONTENT + AIMED_AT_CONVERTED_ELEMENTS + assert low <= count <= high < STYLE_RULES, f"of the page's {STYLE_RULES} style rules {low} match only what the script builds and {AIMED_AT_CONVERTED_ELEMENTS} only the converted elements' own attribute, but the sentence says {count} were kept: {sentence!r}" + + +def test_the_kept_css_holds_no_import_only_the_keyframes_and_faces_kept_rules_use_and_a_media_block_with_only_its_kept_rule(editor, tmp_path): + import_as_elements(editor, written(tmp_path, "board.html", BOARD)) + site = editor.site()["site"] + kept = [record["css"] for record in code_sections(site).values() if record.get("js") and record.get("css")] + assert len(kept) == 1, f"expected the kept script's code section to carry the kept rules: {code_sections(site)}" + rules = editor.page.evaluate("""css => { const sheet = new CSSStyleSheet(); sheet.replaceSync(css); + return [...sheet.cssRules].map(r => ({type: r.constructor.name, name: r.name || '', family: r.style ? r.style.getPropertyValue('font-family').replace(/["']/g, '') : '', + inner: r.cssRules && r.constructor.name === 'CSSMediaRule' ? [...r.cssRules].map(x => x.selectorText) : []})); }""", kept[0]) + assert OUTSIDE not in kept[0] and "@import" not in kept[0], f"the outside @import was kept: {kept[0][:400]!r}" + assert {r["name"] for r in rules if r["type"] == "CSSKeyframesRule"} == {"cardspin"}, f"kept keyframes: {rules}" + assert {r["family"] for r in rules if r["type"] == "CSSFontFaceRule"} == {"Boardface"}, f"kept font faces: {rules}" + media = [r["inner"] for r in rules if r["type"] == "CSSMediaRule"] + assert len(media) == 1 and len(media[0]) == 1 and media[0][0].split(":where")[0].rstrip().endswith(".card") and "h1" not in media[0][0], f"the @media block should keep only its .card rule: {media}" + + +def test_converted_heading_and_container_look_as_on_the_original_page_on_the_canvas_and_in_the_export_with_scripts_off(editor, chromium, tmp_path): + source = written(tmp_path, "board.html", BOARD) + context, original = published(chromium, source, scripts=False) + want = {name: look(original.locator(selector), MEASURED) for name, selector in (("heading", "#title"), ("container", "#board"))} + context.close() + assert want["heading"]["outline-style"] == "none" and want["container"]["background-color"] == "rgb(230, 235, 240)" + import_as_elements(editor, source) + site = editor.site()["site"] + keys = {"heading": by_attr_id(site, "title")["id"], "container": by_attr_id(site, "board")["id"]} + for name, key in keys.items(): + on_canvas = look(editor.canvas.locator(f'[data-fw-id="{key}"]'), MEASURED) + assert on_canvas == want[name], f"on the canvas the converted {name} differs from the original page: {on_canvas} against {want[name]}" + folder = exported(editor, tmp_path / "export") + context, page = published(chromium, folder / "board" / "index.html", scripts=False) + try: + for name, key in keys.items(): + shown = look(page.locator(f'[data-fw-node="{key}"]'), MEASURED) + assert shown == want[name], f"in the export with scripts off the converted {name} differs from the original page: {shown} against {want[name]}" + finally: + context.close() + context, page = published(chromium, folder / "board" / "index.html") + try: + expect_styled_cards(page, "in the same export with scripts on") + finally: + context.close() + + +def convert_in_dialog(editor, host, keep): + editor.canvas.locator(f'[data-fw-id="{host}"]').click(button="right") + editor.menu().get_by_role("menuitem", name="Convert to editable elements...").click() + dialog = editor.page.locator(".fw-convert") + expect(dialog).to_be_visible() + box = dialog.get_by_role("checkbox", name="Keep the page's script as a code section") + if box.is_checked() != keep: + box.click() + expect(box).to_be_checked(checked=keep) + dialog.get_by_role("button", name="Convert", exact=True).click() + notice = editor.page.locator(".fw-notice-text") + expect(notice).to_contain_text("Converted", timeout=60_000) + editor.until(lambda s: host not in code_sections(s), "the code section to become elements") + return notice.inner_text() + + +def test_converting_with_the_script_not_kept_keeps_no_rules_and_says_nothing_of_them(editor, tmp_path): + before, (host,) = import_as_code(editor, written(tmp_path, "board.html", BOARD)) + editor.page.evaluate("window.formweb.run('window.layers')") + page = next(p for p in before["pages"] if p["name"] == "Card board") + editor.page_row(page["id"]).click() + sentence = convert_in_dialog(editor, host, keep=False) + after = editor.site()["site"] + assert "style rule" not in sentence, f"a sentence about kept rules appeared without the script: {sentence!r}" + assert not any(record.get("css") for record in code_sections(after).values()), f"CSS was kept without the script: {code_sections(after)}" + assert not any(record.get("js") for record in code_sections(after).values()) + editor.undo() + editor.restored_to(before) + expect(editor.page.locator(".fw-convert")).to_be_hidden() + again = convert_in_dialog(editor, host, keep=True) + assert kept_count(again) >= 1, "the same page with its script kept was expected to keep rules" + + +FILL = { + "a page whose html and body are 100% high": """Tall page

Tall page

Foot of the page
""", + "a page whose body is at least 100vh high": """Tall page

Tall page

Foot of the page
""", +} + +HEIGHTS = """(e, foot) => ({ view: innerHeight, top: e.getBoundingClientRect().top + scrollY, height: e.getBoundingClientRect().height, + foot: document.querySelector(foot).getBoundingClientRect().bottom + scrollY })""" + + +def converted_tall_page(editor, chromium, tmp_path, layout): + n = list(FILL).index(layout) + 1 + html = FILL[layout].replace("Tall page", f"Tall page {n}").replace('id="foot"', f'id="foot-{n}"').replace("#foot", f"#foot-{n}") + source = written(tmp_path, f"tall-{n}.html", html) + context, original = published(chromium, source, scripts=False) + filled = original.evaluate(f"() => document.getElementById('foot-{n}').getBoundingClientRect().bottom - innerHeight") + context.close() + assert abs(filled) <= 1, f"the test page itself should end at the bottom of the window, it ends {filled} px from it" + import_as_elements(editor, source) + site = editor.site()["site"] + page = next(p for p in site["pages"] if p["name"] == f"Tall page {n}") + host = site["nodes"][page["root"]]["children"][0] + return site, page, host, by_attr_id(site, f"foot-{n}")["id"] + + +def test_a_converted_page_that_filled_the_window_is_as_tall_as_the_canvas_viewport(editor, chromium, tmp_path): + for layout in FILL: + site, page, host, foot = converted_tall_page(editor, chromium, tmp_path, layout) + editor.page.evaluate("window.formweb.run('window.layers')") + editor.page_row(page["id"]).click() + expect(editor.page_row(page["id"])).to_have_attribute("aria-current", "page") + root = editor.canvas.locator(f'[data-fw-id="{host}"]') + expect(root).to_be_visible() + shown = root.evaluate(HEIGHTS, f'[data-fw-id="{foot}"]') + assert shown["top"] + shown["height"] >= shown["view"] - 1, f"{layout}: on the canvas the converted page ends at {shown['top'] + shown['height']} px in a {shown['view']} px viewport" + assert abs(shown["foot"] - shown["view"]) <= 2, f"{layout}: on the canvas the footer ends at {shown['foot']} px, the original ends at the bottom of the {shown['view']} px viewport" + + +def test_a_converted_page_that_filled_the_window_is_as_tall_as_the_preview(editor, chromium, tmp_path): + for layout in FILL: + site, page, host, foot = converted_tall_page(editor, chromium, tmp_path, layout) + editor.page.evaluate("window.formweb.run('window.layers')") + editor.page_row(page["id"]).click() + expect(editor.page_row(page["id"])).to_have_attribute("aria-current", "page") + frame = preview(editor) + root = frame.locator(f'[data-fw-node="{host}"]') + expect(root).to_be_visible() + shown = root.evaluate(HEIGHTS, f'[data-fw-node="{foot}"]') + assert shown["top"] + shown["height"] >= shown["view"] - 1, f"{layout}: in Preview the converted page ends at {shown['top'] + shown['height']} px in a {shown['view']} px viewport" + assert abs(shown["foot"] - shown["view"]) <= 2, f"{layout}: in Preview the footer ends at {shown['foot']} px, the original ends at the bottom of the {shown['view']} px viewport" + close_preview(editor) + + +def test_one_undo_takes_the_conversion_back_another_the_import_and_redo_brings_both_back_with_the_cards_styled(editor, tmp_path): + before = editor.site()["site"] + import_as_elements(editor, written(tmp_path, "board.html", BOARD)) + converted = editor.until(lambda s: nodes_with(s, "h1", "Card board"), "the heading to become an element") + editor.page.evaluate("window.formweb.run('edit.undo')") + as_code = editor.until(lambda s: s != converted and code_sections(s), "one undo to bring the page back as code") + assert not nodes_with(as_code, "h1", "Card board") + assert any("Card board" in record.get("html", "") for record in code_sections(as_code).values()) + editor.page.evaluate("window.formweb.run('edit.undo')") + editor.restored_to(before) + editor.page.evaluate("window.formweb.run('edit.redo')") + editor.until(lambda s: s == as_code, "one redo to bring the page back as code") + editor.page.evaluate("window.formweb.run('edit.redo')") + editor.until(lambda s: s == converted, "a second redo to bring the conversion back with its kept rules") + page = next(p for p in converted["pages"] if p["name"] == "Card board") + editor.page.evaluate("window.formweb.run('window.layers')") + editor.page_row(page["id"]).click() + expect(editor.page_row(page["id"])).to_have_attribute("aria-current", "page") + expect_styled_cards(preview(editor), "in Preview after undo and redo") + + +def base36(n): + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + out = "" + while True: + n, r = divmod(n, 36) + out = digits[r] + out + if not n: + return out + + +def test_a_stylesheet_of_20000_rules_converts_without_hanging_the_window_and_the_sentence_says_rules_were_left_out(editor, tmp_path): + rules = "".join(f".a{base36(i)}{{top:0}}" for i in range(20_000)) + html = f"""Many rules
Host
+""" + sentence = import_as_elements(editor, written(tmp_path, "many.html", html), wait=180_000) + kept = kept_count(sentence) + left = re.search(r"(\d+) more style rules? (?:was|were) left out", sentence) + assert left, f"the sentence does not say that rules were left out: {sentence!r}" + assert kept >= 1 and int(left.group(1)) >= 1 and kept + int(left.group(1)) <= 20_000, sentence + editor.page.evaluate("window.formweb.run('window.layers')") + editor.page_row("home").click() + expect(editor.page_row("home")).to_have_attribute("aria-current", "page") + + +def test_with_the_batch_route_faking_the_engines_too_large_refusal_once_the_conversion_still_succeeds_without_the_kept_rules(editor, tmp_path): + before, (host,) = import_as_code(editor, written(tmp_path, "board.html", BOARD)) + try: + editor.command("code.section.set", {"node": host, "value": {"enabled": True, "html": "

x

", "css": "p{top:0}" * 40_000}}) + raise AssertionError("the engine took a code section CSS over 256 KiB") + except urllib.error.HTTPError as error: + refusal = json.loads(error.read())["detail"] + assert editor.site()["site"] == before + answered = [] + + def refuse_once(route): + if answered: + route.continue_() + return + answered.append(route.request.post_data) + route.fulfill(status=400, json={"detail": refusal}) + + editor.page.route("**/api/batch", refuse_once) + answer = editor.page.evaluate("h => window.formweb.run('library.convert-section', {node: h, keepScript: true})", host) + assert answered, "the conversion never reached the batch route" + assert answer["ran"] is True, answer + sentence = answer["result"]["message"] + assert "Converted" in sentence and "left out because the page's code would be too large" in sentence, sentence + site = editor.until(lambda s: host not in code_sections(s), "the code section to become elements") + assert nodes_with(site, "h1", "Card board") + assert not any(record.get("css") for record in code_sections(site).values()), f"the refused rules were stored: {code_sections(site)}" + assert any(record.get("js") for record in code_sections(site).values()), "the script itself was lost with its rules" + + +SITE_CSS = """@keyframes sitepulse { from, to { letter-spacing: 3px; } } +.site-banner { --site-gap: 6px; padding-left: var(--site-gap); animation: sitepulse 10s linear paused; }""" + +CLASH = """Clash

Imported heading

+ +""" + +SITE_LOOK = ["color", "text-transform", "font-size", "letter-spacing", "outline-style", "padding-left", "animation-name"] + + +def site_look(page): + return {key: look(page.locator(f'[data-fw-node="{key}"]'), SITE_LOOK) for key in ("site-heading", "site-banner-host")} | {"banner": look(page.locator(".site-banner"), SITE_LOOK)} + + +def test_kept_rules_with_names_the_site_already_uses_do_not_restyle_the_sites_own_heading_in_the_export(harbour, chromium, tmp_path): + editor = harbour + home = next(p for p in editor.site()["site"]["pages"] if p["slug"] == "/") + blank = lambda key, tag, name, text, styles: {"id": key, "tag": tag, "name": name, "text": text, "children": [], "attrs": {}, "styles": styles, "breakpoints": {}} + editor.page_row(home["id"]).click() + expect(editor.page_row(home["id"])).to_have_attribute("aria-current", "page") + editor.command(None, [ + {"command": "code.sections.allow", "params": {"enabled": True}}, + {"command": "node.add", "params": {"parent": home["root"], "node": blank("site-heading", "h1", "Site heading", "Our own heading", {"color": "rgb(10, 90, 10)", "font-size": "30px", "letter-spacing": "1px"})}}, + {"command": "node.add", "params": {"parent": home["root"], "node": blank("site-banner-host", "div", "Site banner", "", {})}}, + {"command": "code.section.set", "params": {"node": "site-banner-host", "value": {"enabled": True, "html": '

Our banner

', "css": SITE_CSS}}}, + ], batch=True) + editor.until(lambda s: "site-banner-host" in s["nodes"], "the site's own heading and banner") + first = exported(editor, tmp_path / "before") + context, page = published(chromium, first / "index.html") + try: + start = site_look(page) + assert start["banner"]["padding-left"] == "6px" and start["banner"]["letter-spacing"] == "3px", start + page.add_style_tag(content=CLASH.split("")[0]) + hit = site_look(page) + assert hit["site-heading"] != start["site-heading"] and hit["banner"] != start["banner"], f"the page's stylesheet, applied as it is, was expected to restyle the site's heading and banner: {hit}" + finally: + context.close() + sentence = import_as_elements(editor, written(tmp_path, "clash.html", CLASH), section=True) + assert kept_count(sentence) >= 1, sentence + second = exported(editor, tmp_path / "after") + for scripts in (False, True): + context, page = published(chromium, second / "index.html", scripts=scripts) + try: + if scripts: + expect(page.locator(".card")).to_have_css("background-color", "rgb(1, 2, 3)") + expect(page.locator(".card")).to_have_css("letter-spacing", "17px") + assert site_look(page) == start, f"with scripts {'on' if scripts else 'off'} the kept rules restyled the site's own elements: {site_look(page)} against {start}" + finally: + context.close() + + +SECTION_A = """Red deck
Red
+""" + +SECTION_B = """Blue deck
Blue
+""" + + +def test_two_pages_converted_in_one_go_each_keep_their_own_rules_and_neither_page_gets_the_others(editor, chromium, tmp_path): + site, hosts = import_as_code(editor, written(tmp_path, "red.html", SECTION_A), written(tmp_path, "blue.html", SECTION_B)) + assert len(hosts) == 2 + answer = editor.page.evaluate("h => window.formweb.run('library.convert-section', {nodes: h, keepScript: true})", hosts) + assert answer["ran"] is True, answer + assert kept_count(answer["result"]["message"]) >= 2, answer["result"]["message"] + editor.until(lambda s: not any(h in code_sections(s) for h in hosts), "both code sections to become elements") + folder = exported(editor, tmp_path / "export") + for slug, letter, own in (("red", "A", ("rgb(200, 0, 0)", "11px")), ("blue", "B", ("rgb(0, 0, 200)", "22px"))): + context, page = published(chromium, folder / slug / "index.html") + try: + card = page.locator(".card") + expect(card).to_have_count(1) + expect(card).to_have_text(letter) + shown = look(card, ["background-color", "padding-top"]) + assert (shown["background-color"], shown["padding-top"]) == own, f"on the {slug} page the built card shows {shown}, its own page's rule says {own}" + finally: + context.close() + + +def test_backspace_while_the_convert_dialog_works_removes_nothing_and_the_conversion_still_lands(editor, tmp_path): + before, (host,) = import_as_code(editor, written(tmp_path, "board.html", BOARD)) + editor.page.evaluate("window.formweb.run('window.layers')") + page = next(p for p in before["pages"] if p["name"] == "Card board") + editor.page_row(page["id"]).click() + editor.canvas.locator(f'[data-fw-id="{host}"]').click(button="right") + editor.menu().get_by_role("menuitem", name="Convert to editable elements...").click() + expect(editor.canvas.locator(f'[data-fw-id="{host}"]')).to_have_attribute("data-fw-selected", "") + held = [] + editor.page.route("**/api/batch", lambda route: route.continue_() if held else held.append(route)) + start = editor.site() + dialog = editor.page.locator(".fw-convert") + dialog.get_by_role("button", name="Convert", exact=True).click() + editor.eventually(lambda: bool(held), "the conversion's batch") + expect(dialog).to_have_attribute("aria-busy", "true") + assert editor.page.evaluate("document.activeElement !== document.body"), "focus fell to the page body while the conversion worked" + editor.page.keyboard.press("Backspace") + editor.page.keyboard.press("Delete") + assert editor.site() == start, "a key pressed while the conversion worked changed the site" + held[0].continue_() + after = editor.until(lambda s: host not in code_sections(s), "the code section to become elements") + assert host in after["nodes"] and nodes_with(after, "h1", "Card board"), "the converted section was removed" + expect(editor.page.locator(".fw-notice-text")).to_contain_text("Converted") + assert editor.page.evaluate("document.activeElement !== document.body"), "focus fell to the page body when the dialog closed" diff --git a/frontend/tests/window/test_export_folder.py b/frontend/tests/window/test_export_folder.py new file mode 100644 index 00000000..724a7c6a --- /dev/null +++ b/frontend/tests/window/test_export_folder.py @@ -0,0 +1,458 @@ +import io +import json +import re +import urllib.request +import zipfile + +from playwright.sync_api import expect + +KEY = "formweb.export-folder" +SHELL = """(() => { + const replies = JSON.parse(sessionStorage.getItem('fw-shell-replies') || '{}'); + const held = []; + const log = args => { + const calls = JSON.parse(sessionStorage.getItem('fw-shell-calls') || '[]'); + calls.push(args); + sessionStorage.setItem('fw-shell-calls', JSON.stringify(calls)); + }; + window.__shell = { + replies, + held, + answer(command, value, failed) { + const index = held.findIndex(entry => entry.command === command); + if (index < 0) return false; + const entry = held.splice(index, 1)[0]; + if (failed) entry.reject(value); else entry.resolve(value); + return true; + }, + }; + window.__TAURI__ = { core: { invoke(command, args) { + log([command, args === undefined ? null : args]); + const reply = replies[command]; + if (reply === 'hold') return new Promise((resolve, reject) => held.push({ command, resolve, reject })); + if (reply && typeof reply === 'object' && 'error' in reply) return Promise.reject(reply.error); + if (reply && typeof reply === 'object' && 'value' in reply) return Promise.resolve(reply.value); + if (command === 'set_export_place') return Promise.resolve({ mode: args.mode, folder: args.path }); + return Promise.resolve(null); + } } }; +})()""" + + +def desktop(editor, replies=None, stored=None): + page = editor.page + page.evaluate("([replies, key, stored]) => { sessionStorage.setItem('fw-shell-replies', JSON.stringify(replies)); sessionStorage.removeItem('fw-shell-calls'); if (stored === null) localStorage.removeItem(key); else localStorage.setItem(key, stored); }", [replies or {}, KEY, stored]) + page.context.add_init_script(SHELL) + page.reload(wait_until="domcontentloaded") + page.locator('[data-demo="harbour-ferries"]').wait_for() + return editor + + +def calls(editor, command=None): + made = editor.page.evaluate("JSON.parse(sessionStorage.getItem('fw-shell-calls') || '[]')") + return [args for name, args in made if name == command] if command else made + + +def place_calls(editor): + return [call for call in calls(editor) if call[0] in ("set_export_place", "choose_export_folder", "ask_export_place")] + + +def answer(editor, command, value, failed=False): + editor.eventually(lambda: editor.page.evaluate("command => window.__shell.held.some(entry => entry.command === command)", command), f"the page to ask the shell {command}") + assert editor.page.evaluate("([command, value, failed]) => window.__shell.answer(command, value, failed)", [command, value, failed]) + + +def held(editor, command): + return editor.page.evaluate("command => window.__shell.held.filter(entry => entry.command === command).length", command) + + +def tell(editor, detail): + editor.page.evaluate("detail => window.dispatchEvent(new CustomEvent('formweb-download', { detail }))", detail) + + +def stored(editor): + return editor.page.evaluate("key => localStorage.getItem(key)", KEY) + + +def watch(editor, part): + seen = [] + editor.page.on("request", lambda request: seen.append(request.url) if part in request.url else None) + return seen + + +def downloads(editor): + seen = [] + editor.page.on("download", lambda download: seen.append(download)) + return seen + + +def open_menu(editor, menu, command): + editor.page.locator(f'[data-menu="{menu}"]').click() + return editor.page.locator(f'[role="menu"]:visible [data-command="{command}"]') + + +def open_general(editor): + open_menu(editor, "Edit", "edit.settings").click() + dialog = editor.page.get_by_role("dialog", name="Preferences") + dialog.get_by_role("tab", name="General").click() + return dialog + + +def radio(dialog, name): + return dialog.get_by_role("radio", name=name, exact=True) + + +def export_button(editor): + return editor.page.locator('[data-cmd="file.export"]') + + +def notice(editor): + return editor.page.locator(".fw-notice .fw-notice-text") + + +def harbour_in(editor): + editor.open_demo("harbour-ferries", "p-fares") + return editor + + +def back_to_editor(editor): + editor.page.get_by_role("button", name="Back to Editor").click() + editor.page.locator(".canvas-frame[title='Website canvas']").wait_for() + + +def test_in_a_browser_preferences_says_the_browser_decides_and_export_static_site_downloads_as_before(editor): + harbour_in(editor) + dialog = open_general(editor) + expect(dialog.get_by_text("In a browser, the browser decides where downloads go.")).to_be_visible() + expect(dialog.get_by_role("radio")).to_have_count(0) + editor.page.keyboard.press("Escape") + with editor.page.expect_download() as download: + export_button(editor).click() + name = download.value.suggested_filename + assert re.fullmatch(r"harbour-ferries.*-site\.zip", name), name + expect(notice(editor)).to_have_text(f"Downloaded {name}. Your browser lists it with its downloads.") + + +def test_when_the_shell_is_there_the_page_offers_three_places_with_downloads_chosen_at_first(editor): + harbour_in(desktop(editor)) + dialog = open_general(editor) + for name in ("The Downloads folder", "A folder you choose", "Ask each time"): + expect(radio(dialog, name)).to_be_visible() + expect(dialog.get_by_role("radio")).to_have_count(3) + expect(radio(dialog, "The Downloads folder")).to_be_checked() + expect(dialog.get_by_text("No folder chosen yet.")).to_be_visible() + expect(dialog.get_by_text("In a browser, the browser decides where downloads go.")).to_have_count(0) + assert calls(editor, "set_export_place") == [{"mode": "downloads", "path": "", "forget": False}] + + +def test_choosing_a_folder_asks_the_shell_for_its_dialog_and_shows_the_path_the_shell_returns(editor): + harbour_in(desktop(editor, {"choose_export_folder": "hold"})) + dialog = open_general(editor) + radio(dialog, "A folder you choose").click() + answer(editor, "choose_export_folder", "/home/me/Exports/café sites/") + assert calls(editor, "choose_export_folder") == [None], "the page sent a folder of its own to the folder dialog" + shown = dialog.get_by_text("/home/me/Exports/café sites/", exact=True) + expect(shown).to_be_visible() + expect(shown).to_have_attribute("title", "/home/me/Exports/café sites/") + expect(dialog.get_by_text("No folder chosen yet.")).to_be_hidden() + expect(radio(dialog, "A folder you choose")).to_be_checked() + assert json.loads(stored(editor)) == {"mode": "folder", "path": "/home/me/Exports/café sites/"} + assert calls(editor, "set_export_place")[-1] == {"mode": "folder", "path": "/home/me/Exports/café sites/", "forget": False} + + +def test_a_long_folder_path_from_the_shell_is_cut_on_one_line_and_its_full_text_stays_available(editor): + long = "/home/me/" + "/".join(f"nested folder {i:02d} été" for i in range(20)) + harbour_in(desktop(editor, {"choose_export_folder": {"value": long}})) + dialog = open_general(editor) + radio(dialog, "A folder you choose").click() + shown = dialog.get_by_text(long, exact=True) + expect(shown).to_be_visible() + expect(shown).to_have_attribute("title", long) + cut = shown.evaluate("node => { const range = document.createRange(); range.selectNodeContents(node); return { cut: node.scrollWidth > node.clientWidth, lines: new Set([...range.getClientRects()].map(rect => Math.round(rect.top))).size }; }") + assert cut == {"cut": True, "lines": 1}, cut + + +def test_cancel_in_the_folder_dialog_puts_the_choice_back_to_downloads(editor): + harbour_in(desktop(editor, {"choose_export_folder": "hold"})) + dialog = open_general(editor) + radio(dialog, "A folder you choose").click() + expect(radio(dialog, "A folder you choose")).to_be_checked() + answer(editor, "choose_export_folder", None) + expect(radio(dialog, "The Downloads folder")).to_be_checked() + expect(dialog.get_by_text("No folder chosen yet.")).to_be_visible() + assert stored(editor) is None + assert calls(editor, "set_export_place") == [{"mode": "downloads", "path": "", "forget": False}] + + +def test_a_stored_folder_the_shell_has_no_record_of_gives_no_folder_chosen_yet_with_downloads_chosen(editor): + tampered = json.dumps({"mode": "folder", "path": "C:\\Users\\me\\Startup"}) + harbour_in(desktop(editor, {"set_export_place": {"value": {"mode": "downloads", "folder": ""}}}, stored=tampered)) + dialog = open_general(editor) + expect(radio(dialog, "The Downloads folder")).to_be_checked() + expect(dialog.get_by_text("No folder chosen yet.")).to_be_visible() + expect(dialog.get_by_text("C:\\Users\\me\\Startup")).to_have_count(0) + assert stored(editor) is None + assert place_calls(editor) == [["set_export_place", {"mode": "folder", "path": "C:\\Users\\me\\Startup", "forget": False}]] + + +def test_a_stored_folder_that_differs_from_the_shells_record_shows_the_folder_the_shell_answers(editor): + tampered = json.dumps({"mode": "folder", "path": "C:\\Users\\me\\Startup"}) + harbour_in(desktop(editor, {"set_export_place": {"value": {"mode": "folder", "folder": "D:\\Exports"}}}, stored=tampered)) + dialog = open_general(editor) + expect(radio(dialog, "A folder you choose")).to_be_checked() + expect(dialog.get_by_text("D:\\Exports", exact=True)).to_be_visible() + expect(dialog.get_by_text("C:\\Users\\me\\Startup")).to_have_count(0) + assert json.loads(stored(editor)) == {"mode": "folder", "path": "D:\\Exports"} + assert place_calls(editor) == [["set_export_place", {"mode": "folder", "path": "C:\\Users\\me\\Startup", "forget": False}]] + + +def test_in_ask_mode_the_page_asks_the_shell_before_any_export_request_and_a_no_saves_nothing(editor): + harbour_in(desktop(editor, {"ask_export_place": "hold"}, stored='{"mode":"ask","path":""}')) + exports = watch(editor, "/api/export") + files = downloads(editor) + export_button(editor).click() + editor.eventually(lambda: held(editor, "ask_export_place") == 1, "the page to ask the shell where to save") + assert exports == [], "the export was requested before the shell was asked" + answer(editor, "ask_export_place", False) + expect(editor.status).to_have_text("Nothing was saved.") + assert exports == [] and files == [] + with editor.page.expect_download() as download: + export_button(editor).click() + answer(editor, "ask_export_place", True) + assert len(exports) == 1, exports + asked = calls(editor, "ask_export_place") + assert asked == [{"name": download.value.suggested_filename}] * 2, asked + + +def test_in_ask_mode_a_yes_from_the_shell_is_followed_by_exactly_one_export(editor): + harbour_in(desktop(editor, {"ask_export_place": "hold"}, stored='{"mode":"ask","path":""}')) + exports = watch(editor, "/api/export") + files = downloads(editor) + export_button(editor).click() + answer(editor, "ask_export_place", True) + expect(editor.status).to_contain_text("Static site exported") + editor.eventually(lambda: len(files) == 1, "the download") + assert len(exports) == 1, exports + assert files[0].suggested_filename.endswith("-site.zip") + + +def test_two_exports_in_a_row_in_ask_mode_ask_twice_in_order(editor): + harbour_in(desktop(editor, {"ask_export_place": "hold"}, stored='{"mode":"ask","path":""}')) + asked_routes = watch(editor, "/api/") + files = downloads(editor) + export_button(editor).click() + editor.eventually(lambda: held(editor, "ask_export_place") == 1, "the first question") + open_menu(editor, "File", "file.download").click() + assert held(editor, "ask_export_place") == 1, "the second download asked before the first was answered" + answer(editor, "ask_export_place", True) + editor.eventually(lambda: len(files) == 1, "the first download") + answer(editor, "ask_export_place", True) + editor.eventually(lambda: len(files) == 2, "the second download") + names = [f.suggested_filename for f in files] + assert names[0].endswith("-site.zip") and names[1].endswith(".fweb"), names + assert calls(editor, "ask_export_place") == [{"name": names[0]}, {"name": names[1]}] + fetched = [url for url in asked_routes if "/api/export" in url or "/api/project-file" in url] + assert [("export" if "/api/export" in url else "project") for url in fetched] == ["export", "project"], fetched + + +def test_when_the_shell_reports_the_chosen_folder_could_not_be_used_the_notice_names_both_folders(editor): + harbour_in(desktop(editor, stored='{"mode":"folder","path":"/home/me/Exports"}')) + with editor.page.expect_download() as download: + export_button(editor).click() + name = download.value.suggested_filename + expect(notice(editor)).to_have_text(f"Saving {name}...") + tell(editor, {"url": download.value.url, "ok": True, "file": name, "folder": "/home/me/Downloads", "unusable": "/home/me/Exports"}) + expect(notice(editor)).to_contain_text("/home/me/Exports") + expect(notice(editor)).to_contain_text(f"so {name} was saved to /home/me/Downloads.") + expect(editor.page.locator(".fw-notice")).to_have_class(re.compile(r"\bis-error\b")) + expect(editor.page.locator(".fw-notice").get_by_role("button", name="Show in folder")).to_be_visible() + + +def test_after_a_save_the_notice_names_the_folder_the_shell_reported_and_show_in_folder_asks_the_shell(editor): + harbour_in(desktop(editor, stored='{"mode":"folder","path":"/home/me/Exports/café sites"}')) + with editor.page.expect_download() as download: + export_button(editor).click() + name = download.value.suggested_filename + expect(notice(editor)).to_have_text(f"Saving {name}...") + tell(editor, {"url": download.value.url, "ok": True, "file": name, "folder": "/home/me/Exports/café sites", "unusable": ""}) + expect(notice(editor)).to_have_text(f"Exported {name} to /home/me/Exports/café sites.") + expect(editor.page.locator(".fw-notice")).not_to_have_class(re.compile(r"\bis-error\b")) + assert calls(editor, "reveal_download") == [] + editor.page.locator(".fw-notice").get_by_role("button", name="Show in folder").click() + editor.eventually(lambda: calls(editor, "reveal_download") == [None], "Show in folder to ask the shell") + + +def test_when_the_shell_refuses_a_download_it_was_not_asked_for_the_notice_says_nothing_was_saved(editor): + harbour_in(desktop(editor, {"ask_export_place": {"value": True}}, stored='{"mode":"ask","path":""}')) + with editor.page.expect_download() as download: + export_button(editor).click() + name = download.value.suggested_filename + expect(notice(editor)).to_have_text(f"Saving {name}...") + tell(editor, {"url": download.value.url, "ok": False, "reason": "not-asked", "file": name, "folder": "", "unusable": ""}) + expect(notice(editor)).to_have_text("Nothing was saved.") + expect(editor.page.locator(".fw-notice")).not_to_have_class(re.compile(r"\bis-error\b")) + + +def test_in_ask_mode_an_error_from_the_shell_saves_nothing(editor): + harbour_in(desktop(editor, {"ask_export_place": {"error": "the dialog could not open"}}, stored='{"mode":"ask","path":""}')) + exports = watch(editor, "/api/export") + files = downloads(editor) + export_button(editor).click() + expect(editor.status).to_have_text("Nothing was saved.") + assert calls(editor, "ask_export_place") != [] + assert exports == [] and files == [] + + +def test_download_project_in_ask_mode_asks_the_shell_first_and_a_no_saves_nothing(editor): + harbour_in(desktop(editor, {"ask_export_place": "hold"}, stored='{"mode":"ask","path":""}')) + fetched = watch(editor, "/api/project-file") + files = downloads(editor) + open_menu(editor, "File", "file.download").click() + editor.eventually(lambda: held(editor, "ask_export_place") == 1, "the page to ask the shell") + assert fetched == [] + answer(editor, "ask_export_place", False) + expect(editor.status).to_have_text("Nothing was saved.") + assert fetched == [] and files == [] + with editor.page.expect_download() as download: + open_menu(editor, "File", "file.download").click() + answer(editor, "ask_export_place", True) + assert download.value.suggested_filename.endswith(".fweb"), download.value.suggested_filename + assert len(fetched) == 1 + assert calls(editor, "ask_export_place") == [{"name": download.value.suggested_filename}] * 2 + + +def test_the_qr_code_download_in_ask_mode_asks_the_shell_first_and_a_no_saves_nothing(editor): + harbour_in(desktop(editor, {"ask_export_place": "hold"}, stored='{"mode":"ask","path":""}')) + fetched = watch(editor, "/api/qr") + files = downloads(editor) + open_menu(editor, "Page", "page.qr").click() + dialog = editor.page.get_by_role("dialog", name="QR code") + dialog.get_by_role("button", name="Download", exact=True).click() + editor.eventually(lambda: held(editor, "ask_export_place") == 1, "the page to ask the shell") + assert fetched == [] + answer(editor, "ask_export_place", False) + expect(editor.status).to_have_text("Nothing was saved.") + assert fetched == [] and files == [] + open_menu(editor, "Page", "page.qr").click() + with editor.page.expect_download() as download: + dialog.get_by_role("button", name="Download", exact=True).click() + answer(editor, "ask_export_place", True) + assert re.fullmatch(r"qr-.+\.png", download.value.suggested_filename), download.value.suggested_filename + assert len(fetched) == 1 + assert calls(editor, "ask_export_place") == [{"name": download.value.suggested_filename}] * 2 + + +def test_the_choice_survives_a_reload_and_is_handed_to_the_shell_again_at_start(editor): + harbour_in(desktop(editor, {"choose_export_folder": {"value": "/home/me/Exports"}})) + dialog = open_general(editor) + radio(dialog, "A folder you choose").click() + expect(dialog.get_by_text("/home/me/Exports", exact=True)).to_be_visible() + before = len(place_calls(editor)) + editor.page.reload(wait_until="domcontentloaded") + back_to_editor(editor) + started = place_calls(editor)[before:] + assert started == [["set_export_place", {"mode": "folder", "path": "/home/me/Exports", "forget": False}]], started + dialog = open_general(editor) + expect(radio(dialog, "A folder you choose")).to_be_checked() + expect(dialog.get_by_text("/home/me/Exports", exact=True)).to_be_visible() + + +def test_the_choice_is_in_neither_the_site_state_nor_the_export(editor): + marker = "/home/me/fw-marker-folder-9147" + harbour_in(desktop(editor, {"choose_export_folder": {"value": marker}})) + dialog = open_general(editor) + radio(dialog, "A folder you choose").click() + expect(dialog.get_by_text(marker, exact=True)).to_be_visible() + assert marker in stored(editor) + with urllib.request.urlopen(editor.base + "/api/state", timeout=30) as r: + state = r.read().decode("utf-8") + assert "harbour" in state.lower() + assert marker not in state and KEY not in state + with urllib.request.urlopen(editor.base + "/api/export", timeout=60) as r: + archive = zipfile.ZipFile(io.BytesIO(r.read())) + assert archive.namelist() + for name in archive.namelist(): + body = archive.read(name) + assert marker.encode() not in body and KEY.encode() not in body, name + + +def test_reset_all_preferences_puts_the_choice_back_to_downloads_and_tells_the_shell_to_forget(editor): + harbour_in(desktop(editor, stored='{"mode":"folder","path":"/home/me/Exports"}')) + dialog = open_general(editor) + expect(radio(dialog, "A folder you choose")).to_be_checked() + dialog.get_by_role("button", name="Reset All Preferences...").click() + with editor.page.expect_navigation(): + dialog.get_by_role("button", name="Reset", exact=True).click() + back_to_editor(editor) + assert {"mode": "downloads", "path": "", "forget": True} in calls(editor, "set_export_place") + assert calls(editor, "set_export_place")[-1] == {"mode": "downloads", "path": "", "forget": False} + assert stored(editor) is None + dialog = open_general(editor) + expect(radio(dialog, "The Downloads folder")).to_be_checked() + expect(dialog.get_by_text("No folder chosen yet.")).to_be_visible() + + +def test_a_malformed_stored_value_means_downloads(editor): + harbour_in(desktop(editor, stored='{"mode":"ask","path":""}')) + dialog = open_general(editor) + expect(radio(dialog, "Ask each time")).to_be_checked() + for bad in ('{not json', '{"mode":"folder"}', '{"mode":"elsewhere","path":"/home/me/Exports"}', '"ask"'): + editor.page.evaluate("([key, value]) => { localStorage.setItem(key, value); sessionStorage.removeItem('fw-shell-calls'); }", [KEY, bad]) + editor.page.reload(wait_until="domcontentloaded") + back_to_editor(editor) + assert calls(editor, "set_export_place") == [{"mode": "downloads", "path": "", "forget": False}], bad + dialog = open_general(editor) + expect(radio(dialog, "The Downloads folder"), bad).to_be_checked() + editor.page.keyboard.press("Escape") + + +def test_the_busy_export_button_keeps_the_focus_while_the_shell_is_asked_and_a_second_click_or_enter_starts_no_second_export(editor): + harbour_in(desktop(editor, {"ask_export_place": "hold"}, stored='{"mode":"ask","path":""}')) + exports = watch(editor, "/api/export") + files = downloads(editor) + button = export_button(editor) + button.click() + editor.eventually(lambda: held(editor, "ask_export_place") == 1, "the page to ask the shell") + expect(button).to_have_attribute("aria-busy", "true") + expect(button).to_be_focused() + button.click(force=True) + editor.page.keyboard.press("Enter") + expect(button).to_be_focused() + answer(editor, "ask_export_place", True) + editor.eventually(lambda: len(files) == 1, "the download") + expect(button).not_to_have_attribute("aria-busy", "true") + expect(button).to_be_focused() + open_menu(editor, "File", "file.download").click() + editor.eventually(lambda: held(editor, "ask_export_place") == 1, "the next question") + asked = [entry["name"] for entry in calls(editor, "ask_export_place")] + assert asked == [files[0].suggested_filename, asked[1]] and asked[1].endswith(".fweb"), f"a press while busy queued another export: {asked}" + answer(editor, "ask_export_place", False) + expect(editor.status).to_have_text("Nothing was saved.") + assert len(exports) == 1 and len(files) == 1 + + +def test_delete_and_backspace_on_the_rows_controls_remove_nothing(editor): + desktop(editor, {"choose_export_folder": {"value": "/home/me/Exports"}}) + editor.open_demo("coldmere-plumbing", "services") + editor.layer_row("hm-lead").click() + expect(editor.layer_row("hm-lead")).to_have_attribute("aria-selected", "true") + start = editor.site()["site"] + dialog = open_general(editor) + downloads_radio = radio(dialog, "The Downloads folder") + downloads_radio.focus() + expect(downloads_radio).to_be_focused() + for key in ("Delete", "Backspace"): + editor.page.keyboard.press(key) + radio(dialog, "A folder you choose").click() + choose = dialog.get_by_role("button", name="Choose folder...") + choose.focus() + expect(choose).to_be_focused() + for key in ("Delete", "Backspace"): + editor.page.keyboard.press(key) + expect(dialog.get_by_text("/home/me/Exports", exact=True)).to_be_visible() + assert editor.site()["site"] == start, "Delete or Backspace on the row's controls changed the site" + editor.page.keyboard.press("Escape") + expect(dialog).to_be_hidden() + editor.layer_row("hm-lead").click() + editor.page.keyboard.press("Delete") + after = editor.changed_from(start) + assert "hm-lead" not in after["nodes"]["hm-hero-copy"]["children"] diff --git a/frontend/tests/window/test_import_outside.py b/frontend/tests/window/test_import_outside.py new file mode 100644 index 00000000..7b223aaa --- /dev/null +++ b/frontend/tests/window/test_import_outside.py @@ -0,0 +1,358 @@ +import io +import re +import zipfile +from urllib.parse import urlsplit + +from playwright.sync_api import expect + +LOOKS = """Lap timer + + + +

Ready

Press start to time a lap.

+ +""" + +PLAIN = """Opening hours + +

Open daily

From nine until five.

""" + + +def page_with(title, head): + return f"{title}{head}

{title}

Some words.

" + + +def html_file(tmp_path, name, html): + path = tmp_path / name + path.write_text(html, "utf-8") + return path + + +def zip_file(tmp_path, name, entries): + data = io.BytesIO() + with zipfile.ZipFile(data, "w") as archive: + for entry, body in entries.items(): + archive.writestr(entry, body) + path = tmp_path / name + path.write_bytes(data.getvalue()) + return path + + +def pick(editor, *paths, command="file.import-site"): + with editor.page.expect_file_chooser() as chooser: + editor.page.evaluate(f"window.formweb.run('{command}')") + chooser.value.set_files([str(p) for p in paths]) + return editor.page.locator(".fw-lib-site") + + +def rows(view): + return view.locator(".fw-lib-site-review .fw-lib-site-item") + + +def web_sentence(row): + return row.get_by_text("loads files from the web") + + +def option(view, value): + return view.locator(f'[data-bring="{value}"]') + + +def expect_chosen(view, value): + other = "elements" if value == "code" else "code" + expect(option(view, value)).to_have_attribute("aria-checked", "true") + expect(option(view, other)).to_have_attribute("aria-checked", "false") + + +def choice(view): + return view.get_by_role("radiogroup").filter(has=view.page.locator("[data-bring]")) + + +def reason(view): + group = choice(view) + expect(group).to_have_attribute("aria-describedby", re.compile(r"\S")) + line = view.locator(f'[id="{group.get_attribute("aria-describedby")}"]') + expect(line).to_be_visible() + return line + + +def expect_no_reason(view): + expect(choice(view)).not_to_have_attribute("aria-describedby", re.compile(r"\S")) + for words in ("Kept as code", "As elements, "): + expect(view.get_by_text(words)).to_have_count(0) + + +def import_now(view): + view.locator(".fw-lib-insert:not([disabled])").click() + + +def code_sections(site): + return (site.get("extensions", {}).get("code") or {}).get("sections") or {} + + +PLACES = """view => { + const scrollerOf = el => { for (let at = el.parentElement; at; at = at.parentElement) { const y = getComputedStyle(at).overflowY; if (y === 'auto' || y === 'scroll') return at; } return document.documentElement; }; + const place = el => { if (!el || !el.getClientRects().length) return null; const scroller = scrollerOf(el), r = el.getBoundingClientRect(), s = scroller.getBoundingClientRect(); return [r.left - s.left, r.top - s.top + scroller.scrollTop, r.width, r.height].map(v => Math.round(v * 10) / 10).join(','); }; + const group = view.querySelector('[data-bring]')?.closest('[role="radiogroup"]'); + const line = group && group.getAttribute('aria-describedby') ? document.getElementById(group.getAttribute('aria-describedby')) : null; + return { rows: [...view.querySelectorAll('.fw-lib-site-review .fw-lib-site-item')].map(place), code: place(view.querySelector('[data-bring="code"]')), elements: place(view.querySelector('[data-bring="elements"]')), reason: place(line && line.parentElement), button: place(view.querySelector('.fw-lib-insert')) }; +}""" + + +def outside_host(url, base): + parts = urlsplit(url) + return parts.scheme in ("http", "https", "ws", "wss") and not url.startswith(base) + + +def test_the_review_row_names_both_hosts_as_plain_text_with_how_many_files_each_and_holds_no_link(editor, tmp_path): + view = pick(editor, html_file(tmp_path, "lap-timer.html", LOOKS)) + row = rows(view).filter(has_text="lap-timer.html") + sentence = web_sentence(row) + expect(sentence).to_be_visible() + expect(sentence).to_contain_text("1 stylesheet from cdn.example.net") + expect(sentence).to_contain_text("1 script from code.example.org") + expect(sentence).to_contain_text("not brought along") + assert sentence.evaluate("e => [e.children.length, !!e.closest('a, [href], [role=link]')]") == [0, False] + assert view.locator('a, [href*="example."], [src*="example."], [role="link"]').count() == 0 + + +def test_a_page_that_loads_files_from_the_web_starts_on_code_sections_with_a_reason_and_as_code_its_script_runs_in_preview(editor, tmp_path): + before = editor.site()["site"] + view = pick(editor, html_file(tmp_path, "lap-timer.html", LOOKS)) + expect(web_sentence(rows(view).first)).to_be_visible() + expect_chosen(view, "code") + expect(reason(view)).to_contain_text("Kept as code") + import_now(view) + expect(view.locator(".fw-lib-note")).to_contain_text("Imported 1 page") + site = editor.until(lambda s: len(s["pages"]) == len(before["pages"]) + 1 and len(code_sections(s)) == len(code_sections(before)) + 1, "one more page held as code") + added = [record for key, record in code_sections(site).items() if key not in code_sections(before)] + assert "The page script ran" in added[0]["js"] + editor.page.locator('[data-cmd="view.preview-full"]').click() + overlay = editor.page.get_by_role("dialog", name="Preview as published") + expect(overlay).to_be_visible() + expect(overlay.frame_locator("iframe.fw-fp-frame:visible").locator("#clock")).to_have_text("The page script ran") + + +def test_picking_editable_elements_says_what_will_be_missing_and_the_result_names_the_hosts(editor, tmp_path): + before = editor.site()["site"] + view = pick(editor, html_file(tmp_path, "lap-timer.html", LOOKS)) + expect_chosen(view, "code") + option(view, "elements").click() + expect_chosen(view, "elements") + line = reason(view) + expect(line).to_contain_text("As elements") + expect(line).to_contain_text("cdn.example.net") + expect(line).to_contain_text("code.example.org") + expect(line).to_contain_text("missing") + import_now(view) + note = view.locator(".fw-lib-note") + expect(note).to_contain_text("Converted") + expect(note).to_contain_text(re.compile(r"Files from (cdn\.example\.net and code\.example\.org|code\.example\.org and cdn\.example\.net) were not brought along")) + site = editor.until(lambda s: any(n["tag"] == "h1" and n["text"] == "Ready" for n in s["nodes"].values()), "the heading as an element") + assert len(site["pages"]) == len(before["pages"]) + 1 + + +def test_after_a_page_that_loads_files_from_the_web_a_page_with_none_starts_on_editable_elements_with_no_such_sentence(editor, tmp_path): + view = pick(editor, html_file(tmp_path, "lap-timer.html", LOOKS)) + expect_chosen(view, "code") + expect(reason(view)).to_contain_text("Kept as code") + view = pick(editor, html_file(tmp_path, "opening-hours.html", PLAIN)) + expect(rows(view)).to_have_count(1) + expect(rows(view)).to_contain_text("opening-hours.html") + expect_chosen(view, "elements") + expect_no_reason(view) + expect(web_sentence(rows(view).first)).to_have_count(0) + expect(view.get_by_text("from the web")).to_have_count(0) + + +def test_in_a_zip_of_three_pages_where_one_loads_files_from_the_web_the_review_names_that_page_and_starts_on_code_saying_1_of_3_pages(editor, tmp_path): + archive = zip_file(tmp_path, "three.zip", { + "index.html": page_with("Home", ''), + "about.html": page_with("About", ''), + "contact.html": page_with("Contact", ""), + "css/site.css": "h1 { color: #123456; }", + }) + view = pick(editor, archive) + expect(rows(view)).to_have_count(3) + about = rows(view).filter(has_text="about.html") + expect(web_sentence(about)).to_contain_text("cdn.example.net") + expect(web_sentence(about)).to_contain_text("code.example.org") + for name in ("index.html", "contact.html"): + expect(web_sentence(rows(view).filter(has_text=name))).to_have_count(0) + expect_chosen(view, "code") + expect(reason(view)).to_contain_text("1 of 3 pages") + + +def test_a_choice_the_person_made_survives_the_use_toggle_a_theme_and_a_language_switch_and_only_a_new_pick_decides_again(harbour, tmp_path): + page = harbour.page + looks = html_file(tmp_path, "lap-timer.html", LOOKS) + view = pick(harbour, looks) + expect_chosen(view, "code") + option(view, "elements").click() + expect_chosen(view, "elements") + view.get_by_role("radio", name="As a section of this page").click() + expect(view.get_by_role("radio", name="As a section of this page")).to_have_attribute("aria-checked", "true") + expect_chosen(view, "elements") + view.get_by_role("radio", name="As new pages", exact=True).click() + expect(view.get_by_role("radio", name="As new pages", exact=True)).to_have_attribute("aria-checked", "true") + expect_chosen(view, "elements") + theme = page.locator("html").get_attribute("data-theme") + page.evaluate("window.formweb.run('view.theme')") + expect(page.locator("html")).not_to_have_attribute("data-theme", theme or "") + expect_chosen(view, "elements") + page.evaluate("window.formweb.run('view.theme')") + expect_chosen(view, "elements") + page.keyboard.press("Control+,") + languages = page.get_by_label("Editor language") + expect(languages).to_be_visible() + languages.select_option("de") + expect(page.locator("html")).to_have_attribute("lang", "de") + expect_chosen(view, "elements") + page.locator('select:has(option[value="de"]):visible').select_option("en") + expect(page.locator("html")).to_have_attribute("lang", "en") + page.keyboard.press("Escape") + expect(languages).to_be_hidden() + expect_chosen(view, "elements") + expect(reason(view)).to_contain_text("As elements") + view = pick(harbour, looks) + expect(web_sentence(rows(view).first)).to_be_visible() + expect_chosen(view, "code") + expect(reason(view)).to_contain_text("Kept as code") + + +def test_no_request_leaves_for_an_outside_host_during_the_review_both_imports_preview_and_export(editor, tmp_path): + context = editor.page.context + stopped, seen = [], [] + + def stop(route): + stopped.append(route.request.url) + route.abort() + + context.route(lambda url: outside_host(url, editor.base), stop) + context.on("request", lambda request: seen.append(request.url) if outside_host(request.url, editor.base) else None) + blank = context.new_page() + assert blank.evaluate("() => fetch('https://probe.example.net/ping').then(() => 'answered', () => 'refused')") == "refused" + blank.close() + assert stopped == seen == ["https://probe.example.net/ping"], f"the recorders did not both see the deliberate outside request: routed {stopped}, seen {seen}" + stopped.clear() + seen.clear() + + before = editor.site()["site"] + looks = html_file(tmp_path, "lap-timer.html", LOOKS) + view = pick(editor, looks) + expect(web_sentence(rows(view).first)).to_contain_text("cdn.example.net") + expect_chosen(view, "code") + import_now(view) + editor.until(lambda s: len(s["pages"]) == len(before["pages"]) + 1, "the page as code") + view = pick(editor, html_file(tmp_path, "lap-timer-two.html", LOOKS.replace("Lap timer", "Lap timer two"))) + expect(web_sentence(rows(view).first)).to_contain_text("code.example.org") + option(view, "elements").click() + import_now(view) + expect(view.locator(".fw-lib-note")).to_contain_text("Converted") + editor.until(lambda s: len(s["pages"]) == len(before["pages"]) + 2, "the page as elements") + editor.page.locator('[data-cmd="view.preview-full"]').click() + overlay = editor.page.get_by_role("dialog", name="Preview as published") + expect(overlay.frame_locator("iframe.fw-fp-frame:visible").locator("h1").first).to_be_visible() + editor.page.keyboard.press("Escape") + expect(overlay).to_be_hidden() + with editor.page.expect_download() as download: + editor.page.locator('[data-cmd="file.export"]').click() + assert download.value.suggested_filename.endswith(".zip") + download.value.path() + assert stopped == [] and seen == [], f"requests went to outside hosts: routed {stopped}, seen {seen}" + + +def test_a_malformed_or_very_long_host_is_never_named_and_a_good_host_is_shown_as_text(editor, tmp_path): + long_host = "a" * 300 + ".example.net" + head = (f'' + '') + view = pick(editor, html_file(tmp_path, "odd-hosts.html", page_with("Odd hosts", head))) + sentence = web_sentence(rows(view).first) + expect(sentence).to_contain_text("1 stylesheet from cdn.example.net") + words = sentence.inner_text() + assert "aaaa" not in words and "under_score" not in words and "::1" not in words and "script" not in words, words + assert sentence.evaluate("e => e.children.length") == 0 + assert view.locator('a, [href*="example."], [src*="example."], [role="link"]').count() == 0 + + +def test_a_row_whose_outside_files_are_all_named_says_so_once_and_not_again_in_the_older_warning_words(editor, tmp_path): + view = pick(editor, html_file(tmp_path, "lap-timer.html", LOOKS)) + row = rows(view).first + expect(web_sentence(row)).to_contain_text("1 script from code.example.org") + words = row.inner_text() + assert words.count("not brought along") == 1, words + assert "external script" not in words and "external stylesheet" not in words, words + assert "https://" not in words, words + + +def test_a_warning_that_says_more_than_the_named_hosts_still_shows_in_the_row(editor, tmp_path): + head = ('' + '') + view = pick(editor, html_file(tmp_path, "partly.html", page_with("Partly named", head))) + row = rows(view).first + sentence = web_sentence(row) + expect(sentence).to_contain_text("1 script from code.example.org") + expect(sentence).to_contain_text("style.example.org") + expect(row).to_contain_text("https://style.example.org/block.css") + expect(row).to_contain_text("https://under_score.example.net/x.js") + assert "under_score" not in sentence.inner_text() + + +def test_five_files_from_one_host_name_the_host_once_with_the_count_five(editor, tmp_path): + head = "".join(f'' for i in range(5)) + view = pick(editor, html_file(tmp_path, "five.html", page_with("Five", head))) + sentence = web_sentence(rows(view).first) + expect(sentence).to_contain_text("5 scripts from five.example.net") + assert sentence.inner_text().count("five.example.net") == 1 + + +def test_the_rows_and_the_choice_do_not_move_when_the_review_and_its_reason_line_appear(editor, tmp_path): + held = [] + editor.page.route("**/api/library/import-site/review", lambda route: held.append(route)) + with editor.page.expect_file_chooser() as chooser: + editor.page.evaluate("window.formweb.run('file.import-site')") + chooser.value.set_files(str(zip_file(tmp_path, "two.zip", {"index.html": LOOKS, "hours.html": PLAIN}))) + editor.eventually(lambda: bool(held), "the review request") + editor.page.evaluate(f"""() => {{ + const read = {PLACES}; + const view = document.querySelector('.fw-lib-site'); + window.__places = []; + const sample = () => {{ + window.__places.push(read(view)); + if (window.__places.length < 4000) requestAnimationFrame(sample); + }}; + requestAnimationFrame(sample); + }}""") + held[0].continue_() + view = editor.page.locator(".fw-lib-site") + expect(rows(view)).to_have_count(2) + expect_chosen(view, "code") + expect(reason(view)).to_contain_text("Kept as code") + editor.page.evaluate("() => new Promise(done => { let n = 0; const tick = () => (++n > 30 ? done() : requestAnimationFrame(tick)); requestAnimationFrame(tick); })") + samples = editor.page.evaluate("() => { const all = window.__places; window.__places = []; return all; }") + final = samples[-1] + assert len(final["rows"]) == 2 and all(final["rows"]) and final["code"] and final["reason"], final + for name in ("code", "elements", "reason", "button"): + seen = [s[name] for s in samples if s[name] and s["rows"]] + assert set(seen) == {final[name]}, f"the {name} box moved after the review appeared: {sorted(set(seen))}" + for i in range(2): + seen = [s["rows"][i] for s in samples if len(s["rows"]) == 2 and s["rows"][i]] + assert set(seen) == {final["rows"][i]}, f"review row {i + 1} moved after it appeared: {sorted(set(seen))}" + + +def test_switching_the_choice_moves_no_row_no_option_the_reason_box_or_the_import_button(editor, tmp_path): + view = pick(editor, zip_file(tmp_path, "two.zip", {"index.html": LOOKS, "hours.html": PLAIN})) + expect(rows(view)).to_have_count(2) + expect_chosen(view, "code") + line = reason(view) + expect(line).to_contain_text("Kept as code") + places = lambda: view.evaluate(PLACES) + start = places() + assert len(start["rows"]) == 2 and all(start["rows"]) and start["reason"] and start["button"], start + option(view, "elements").click() + expect_chosen(view, "elements") + expect(reason(view)).to_contain_text("As elements") + assert places() == start, "something moved when Editable elements was picked" + option(view, "code").click() + expect_chosen(view, "code") + expect(reason(view)).to_contain_text("Kept as code") + assert places() == start, "something moved when Code sections was picked again" diff --git a/frontend/tests/window/test_property_search.py b/frontend/tests/window/test_property_search.py index 0bb8850c..7e7a5fa1 100644 --- a/frontend/tests/window/test_property_search.py +++ b/frontend/tests/window/test_property_search.py @@ -49,13 +49,14 @@ def test_the_shortcut_opens_a_closed_right_panel_and_focuses_the_search_field(im def test_the_plan_example_queries_give_results_grouped_by_tab_and_section(image_selected): - groups = image_selected.page.locator("#inspector-results-list .inspector-results-group") + groups = image_selected.page.locator("#inspector-results-list .inspector-result-place") for query, wanted in EXAMPLES.items(): search(image_selected).fill(query) expect(image_selected.page.locator("#inspector-results-list .inspector-result").first).to_be_visible() names = set(result_names(image_selected)) assert wanted <= names, f"{query!r} gave {sorted(names)}" - assert all(re.fullmatch(r"(Design|Motion|Content|Page) > .+", g) for g in groups.all_inner_texts()), query + places = groups.all_inner_texts() + assert places and all(re.fullmatch(r"(Design|Motion|Content|Page) > .+", g) for g in places), query search(image_selected).fill("PADDING") expect(image_selected.page.locator("#inspector-results-list .inspector-result").first).to_be_visible() upper = result_names(image_selected) @@ -66,11 +67,8 @@ def test_the_plan_example_queries_give_results_grouped_by_tab_and_section(image_ def grouped_results(editor): return editor.page.locator("#inspector-results-list").evaluate( - """list => { let group = ''; const out = []; - for (const node of list.children) { - if (node.classList.contains('inspector-results-group')) group = node.textContent.trim(); - else if (node.classList.contains('inspector-result')) out.push([group, node.querySelector('.inspector-result-name').textContent.trim()]); - } return out; }""" + """list => Array.from(list.querySelectorAll('.inspector-result')).map(node => + [node.querySelector('.inspector-result-place').textContent.trim(), node.querySelector('.inspector-result-name').textContent.trim()])""" ) @@ -99,15 +97,29 @@ def test_no_field_result_name_ends_with_the_text_of_a_button_for_an_image(image_ assert not joined, f"{query!r}: {joined}" -def test_enter_switches_to_the_tab_of_the_field_and_focuses_it(image_selected): +def test_a_result_shows_its_place_as_text_and_enter_or_a_click_on_it_goes_nowhere(image_selected): tab(image_selected, "Content").click() expect(tab(image_selected, "Content")).to_have_class(re.compile(r"\bactive\b")) search(image_selected).fill("rounded") - expect(image_selected.page.locator("#inspector-results-list .inspector-result").first).to_contain_text("Radius") + row = image_selected.page.locator("#inspector-results-list .inspector-result").filter(has_text="Radius").first + expect(row).to_be_visible() + expect(row.locator(".inspector-result-place")).to_have_text(re.compile(r"^Design > .+")) search(image_selected).press("Enter") - expect(tab(image_selected, "Design")).to_have_class(re.compile(r"\bactive\b")) - focused = image_selected.page.evaluate("document.activeElement.closest('.field')?.querySelector('.field-label')?.firstChild?.textContent.trim()") - assert focused == "Radius" + search(image_selected).press("ArrowDown") + search(image_selected).press("Enter") + row.click() + expect(row).to_be_visible() + expect(tab(image_selected, "Content")).to_have_class(re.compile(r"\bactive\b")) + expect(tab(image_selected, "Design")).not_to_have_class(re.compile(r"\bactive\b")) + expect(search(image_selected)).to_be_focused() + expect(search(image_selected)).to_have_value("rounded") + + +def test_a_motion_preset_is_found_and_listed_with_its_place(image_selected): + search(image_selected).fill("fade up") + rows = image_selected.page.locator("#inspector-results-list .inspector-result") + expect(rows.first).to_be_visible() + assert ["Motion > Presets", "Fade up"] in grouped_results(image_selected) def test_a_query_with_no_match_says_no_matching_properties(image_selected): From 97b4e4fcc0c0ac083036024a961712ee39aab721 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 17:27:02 -0500 Subject: [PATCH 15/38] docs(hashout): audit markers, the export folder, outside files in the import review, kept rules, menus during a trial and the search as a list, in the two logs --- backend/HASHOUT_LOG.md | 12 ++++++++++++ frontend/HASHOUT_LOG.md | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 911cea5e..63bc1ee7 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1,5 +1,17 @@ # Backend context +## The import review names the files a page loads from other hosts · v0.35.0 (2026-11-27) + +The fourth of five releases (0.32.0 to 0.36.0) that answer the follow-up on issue #36; `frontend/HASHOUT_LOG.md`, same version, has the editor side and the desktop shell's export folder. The routes, `mode`, `revision`, the commands, undo and every earlier field and warning sentence are unchanged; the three new fields are additive. Nothing is fetched: no code added here resolves a name or opens a connection (`urlsplit` is not used for the host, and the `idna` codec is a string operation), and a run under `strace` saw no outside connection from the service during reviews and imports. + +`outside_file(kind, reference)` (`app/site_import.py`) reads one reference the way a browser reads an http or https link, without a regular expression and bounded before any parsing: leading and trailing C0 controls and spaces are trimmed and tabs and line breaks removed; the reference must be printable and at most 2,048 characters (`URL_MAX`); the scheme is read by hand and only `http`, `https` or none (protocol-relative) is taken; after it there must be two slashes, `/` or `\` in any mix, and every further slash is skipped; the authority ends at the first `/`, `\`, `?` or `#`, the last `@` ends the credentials (dropped), and the port follows the first `:`, digits only, at most 65535. Cases, each checked against the test browser's own URL parser (`new URL(x, base)`, 66 cases, 0 different): `https://tracker.evil\@cdn.example.net/x.js` is host `tracker.evil` (the browser reads the backslash as a slash, so the path is `/@cdn...`; the first version used `urlsplit` and named the trusted host, which a downloaded page could use to make the review and the agents reading it name the wrong host); `https:\\evil.com\x.css`, `\\evil.com/x.js`, `/\evil.com/x.js` and `https:///evil.com/x` are listed with their host; `https:evil.com/x` and `https:/evil.com/x` are not listed, because their host depends on the page's own scheme; a protocol-relative URL with port 80 or 443 is not listed for the same reason, while `//host:8080/` is; uppercase schemes and hosts are lower-cased; a default port is dropped and another kept in `host`; IPv6 (`[`), a host with `%`, `\`, `@` or white space, a host over 253 characters (`HOST_MAX`), labels outside 1 to 63 characters of `a-z`, `0-9` and `-` with no hyphen at either end (so `under_score` is refused), and a trailing dot are refused; a non-ASCII host goes through the `idna` codec unless it holds a UTS46 deviation character (`ß`, `ẞ`, `ς`, ZWJ, ZWNJ) or a code point unassigned in Unicode 3.2, and an `xn--` label must decode; a host whose last label is a number (decimal or `0x`) is read by the WHATWG IPv4 rules (hex, octal, fewer than four parts, `_ipv4`, `_number`) and listed dotted (`0x7f.1` is `127.0.0.1`) or refused (`1.2.3.4.5`, `256.1.1.1`); `data:`, `blob:`, `javascript:` and `ftp:` are not listed. The answer is `{kind, host, url}`, `url` with the scheme lower-cased, no credentials, the ASCII host, no default port and backslashes in the path turned to `/` (a protocol-relative URL stays `//host/...`). A reference it refuses stays only in the existing warning sentences, which agents still read. + +`Site.listing` collects `(kind, reference)` while one page is read (`_page`): every `