From 4fcad537ff01e23dbc13eeecf18790d84c0ededd Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 16:02:57 -0500 Subject: [PATCH 01/31] feat(desktop): the window shows as soon as the editor is ready, after a minimum of 0.5 s instead of 2.6 s, and the shell writes one start-up line to its log with the milliseconds at which the service started, the service answered, the editor was ready and the window was shown --- src-tauri/src/main.rs | 3 +++ src-tauri/src/reveal.rs | 9 ++++++++- src-tauri/src/start_times.rs | 30 ++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 src-tauri/src/start_times.rs diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index e7e7a2da..34cf0d2c 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -28,6 +28,7 @@ mod downloads; mod engine_start; mod render; mod reveal; +mod start_times; mod text_edit; mod traffic_lights; #[cfg(windows)] @@ -415,6 +416,7 @@ fn main() { Ok(child) => child, Err(failure) => engine_failed(&handle, failure, packaged), }; + start_times::mark(&start_times::SERVICE_STARTED); capture_window_key(&mut child); #[cfg(unix)] SERVICE_GROUP.store(child.id() as i32, std::sync::atomic::Ordering::SeqCst); @@ -430,6 +432,7 @@ fn main() { engine_failed(&handle, failure, packaged); } } + start_times::mark(&start_times::SERVICE_READY); let main_thread = handle.clone(); let _ = handle.run_on_main_thread(move || open_editor(&main_thread)); }); diff --git a/src-tauri/src/reveal.rs b/src-tauri/src/reveal.rs index ef2e0430..f035d2f8 100644 --- a/src-tauri/src/reveal.rs +++ b/src-tauri/src/reveal.rs @@ -4,7 +4,7 @@ use std::time::{Duration, Instant}; use tauri::{Manager, Runtime, WebviewWindow}; -pub const SPLASH_MIN: Duration = Duration::from_millis(2600); +pub const SPLASH_MIN: Duration = Duration::from_millis(500); pub const BACKGROUND: tauri::window::Color = tauri::window::Color(10, 10, 10, 255); const BAR_FINISH: Duration = Duration::from_millis(220); const FALLBACK: Duration = Duration::from_secs(20); @@ -16,6 +16,10 @@ pub fn mark_launch() { let _ = LAUNCH.set(Instant::now()); } +pub fn since_launch() -> Duration { + LAUNCH.get_or_init(Instant::now).elapsed() +} + pub const BUILD_VISIBLE: bool = !cfg!(target_os = "macos"); pub fn conceal(window: &WebviewWindow) { @@ -38,6 +42,7 @@ pub fn close_splash(app: &tauri::AppHandle) { #[tauri::command(async)] pub fn app_ready(app: tauri::AppHandle) { + crate::start_times::mark(&crate::start_times::EDITOR_READY); show_main(&app); } @@ -58,8 +63,10 @@ fn show_main(app: &tauri::AppHandle) { let _ = main.show(); let _ = main.set_focus(); crate::traffic_lights::place(&main.as_ref().window()); + crate::start_times::mark(&crate::start_times::WINDOW_SHOWN); } close_splash(app); + crate::start_times::report(); } #[cfg(target_os = "macos")] diff --git a/src-tauri/src/start_times.rs b/src-tauri/src/start_times.rs new file mode 100644 index 00000000..e906d67a --- /dev/null +++ b/src-tauri/src/start_times.rs @@ -0,0 +1,30 @@ +use std::io::Write; +use std::sync::OnceLock; +use std::time::Duration; + +pub static SERVICE_STARTED: OnceLock = OnceLock::new(); +pub static SERVICE_READY: OnceLock = OnceLock::new(); +pub static EDITOR_READY: OnceLock = OnceLock::new(); +pub static WINDOW_SHOWN: OnceLock = OnceLock::new(); + +pub fn mark(moment: &OnceLock) { + let _ = moment.set(crate::reveal::since_launch()); +} + +pub fn report() { + let text = line(SERVICE_STARTED.get().copied(), SERVICE_READY.get().copied(), EDITOR_READY.get().copied(), WINDOW_SHOWN.get().copied()); + let _ = writeln!(std::io::stderr(), "{text}"); +} + +/// The shell's start-up summary. A service that answered without being started is one the shell found already running. +pub fn line(started: Option, ready: Option, editor: Option, shown: Option) -> String { + let moment = |name: &str, at: Option| match at { + Some(at) => format!("{name} {} ms", at.as_millis()), + None => format!("{name} not reached"), + }; + let first = match (started, ready) { + (None, Some(_)) => "service already running".to_string(), + _ => moment("service started", started), + }; + format!("[formweb] start-up: {first}, {}, {}, {}", moment("service ready", ready), moment("editor ready", editor), moment("window shown", shown)) +} From c8cfbc8ec23a0cd9edd7d46daf4dfdf0fa705754 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 16:02:57 -0500 Subject: [PATCH 02/31] feat(import): a site import counts only files outside node_modules, __MACOSX and dot folders toward its 1,000 limit, refuses a project's source with advice to build it and import the output folder, takes loose .html files as JSON on the same two routes, and ends every refusal by saying nothing was imported --- backend/app/authoring_tools.py | 2 +- backend/app/library_routes.py | 22 +++-- backend/app/site_import.py | 162 +++++++++++++++++++++++++++++---- 3 files changed, 157 insertions(+), 29 deletions(-) diff --git a/backend/app/authoring_tools.py b/backend/app/authoring_tools.py index a80e360e..f27ea772 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 entries, 100 pages and 128 MiB unpacked. 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, 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, or a page that loads .ts, .tsx, .jsx, .vue or .svelte scripts) 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/library_routes.py b/backend/app/library_routes.py index a2c334fa..10b92705 100644 --- a/backend/app/library_routes.py +++ b/backend/app/library_routes.py @@ -322,26 +322,32 @@ async def library_import_html(request: Request): return {**(result if isinstance(result, dict) else {}), 'root': host, 'warnings': warnings + ([site_import.left_out_scripts(foreign)] if foreign else [])} -async def _archive(request: Request) -> bytes: +async def _archive(request: Request) -> bytes | dict | list: body = bytearray() async for chunk in request.stream(): body.extend(chunk) if len(body) > MAX_SITE_ARCHIVE_BYTES: - raise EngineError('The archive is larger than 64 MiB, the most a site import takes.', 413) - return bytes(body) + raise EngineError('The upload is larger than 64 MiB, the most a site import takes. Zip only the folder that holds the finished site, leaving out large videos and files it does not use. Nothing was imported.', 413) + if request.headers.get('content-type', '').split(';', 1)[0].strip().lower() != 'application/json': + return bytes(body) + return site_import.loose(bytes(body)) -async def review_site(data: bytes) -> dict: - archive = await asyncio.to_thread(site_import.read_archive, data) +def _read(data) -> dict: + return site_import.read_archive(data) if isinstance(data, (bytes, bytearray)) else site_import.read_files(data) + + +async def review_site(data) -> dict: + archive = await asyncio.to_thread(_read, data) site, revision = await _current() result = await asyncio.to_thread(site_import.plan, archive, site, kit_script) return {**site_import.review(result), 'revision': revision} -async def import_site(data: bytes, mode: str, revision: int | None) -> dict: +async def import_site(data, mode: str, revision: int | None) -> dict: if mode not in ('new', 'replace'): raise EngineError('Mode must be new or replace.') - archive = await asyncio.to_thread(site_import.read_archive, data) + archive = await asyncio.to_thread(_read, data) site, current = await _current() if revision is not None and revision != current: raise EngineError('The site changed after the review. Review the archive again before importing.', 409) @@ -349,7 +355,7 @@ async def import_site(data: bytes, mode: str, revision: int | None) -> dict: commands, pages = await asyncio.to_thread(site_import.commands, result, site, mode, archive, kit_script) assets = site_import.store_assets(result, archive, studio) outcome = await studio.mutate('batch', {'commands': commands, 'expectedRevision': current}) - studio.access.record('library.import-site', {'pages': pages, 'assets': assets, 'mode': mode, 'bytes': len(data)}) + studio.access.record('library.import-site', {'pages': pages, 'assets': assets, 'mode': mode, 'bytes': len(data) if isinstance(data, (bytes, bytearray)) else sum(len(body) for _, body in archive['files'].values())}) skipped = result['skipped'] warnings = [f'{page["name"]}: {warning}' for page in result['pages'] for warning in page['warnings']] return {**(outcome if isinstance(outcome, dict) else {}), 'pages': pages, 'assets': assets, 'skipped': skipped, 'warnings': warnings, diff --git a/backend/app/site_import.py b/backend/app/site_import.py index 4fb3e40b..45d6ce09 100644 --- a/backend/app/site_import.py +++ b/backend/app/site_import.py @@ -20,7 +20,12 @@ from .engine import EngineError MAX_ENTRIES = 1000 +MAX_RAW_ENTRIES = 40000 +MAX_PEEK = 300000 MAX_LISTING = 2 * 1024 * 1024 +MAX_NAME = 255 +BUILD_SCRIPTS = ('.ts', '.tsx', '.jsx', '.vue', '.svelte') +BUILT = ('dist', 'build') MAX_UNPACKED = 128 * 1024 * 1024 MAX_DEPTH = 12 MAX_RATIO = 100 @@ -70,57 +75,171 @@ def _ext(path: str) -> str: return name.rsplit('.', 1)[-1].lower() if '.' in name else '' +def _parts(name: str) -> list[str]: + return [part for part in name.replace('\\', '/').split('/') if part not in ('', '.')] + + +def _ignored(parts: list[str]) -> bool: + return parts[0] == '__MACOSX' or 'node_modules' in parts or any(part.startswith('.') for part in parts) + + +def _peek(data: bytes, end: int, listing: int) -> list[list[str]]: + """Names from the archive's file list, read record by record without zipfile, only to choose the sentence for an + archive that is refused before it is opened.""" + names, position = [], end - listing if 0 < listing <= end else struct.unpack(' str | None: + """The refusal for a project's source rather than a built site: a package.json at the top or one folder down, and + no HTML page or a page that loads a script needing a build step. Without the pages' text, any such script file counts.""" + if not any(parts[-1].lower() == 'package.json' and len(parts) <= 2 for parts in names): + return None + html = [parts for parts in names if _ext(parts[-1]) in ('html', 'htm')] + if pages is None: + found = sorted((parts for parts in names if parts[-1].lower().endswith(BUILD_SCRIPTS)), + key=lambda parts: (parts[-1].rsplit('.', 1)[0].lower() not in ('main', 'index'), len(parts), '/'.join(parts).lower())) + needs = ['/'.join(parts) for parts in found] + else: + needs = [] + for body in pages.values(): + for tag in re.finditer(r']*>', _text(body), re.I): + source = _attrs(tag.group(0)).get('src', '').strip() + address = urlsplit(source) + if source and not address.scheme and not address.netloc and unquote(address.path).lower().endswith(BUILD_SCRIPTS): + needs.append(unquote(address.path).lstrip('./')) + if html and not needs: + return None + shown = list(dict.fromkeys(_show(item) for item in needs)) + reason = (f'it has package.json and scripts that still need building ({", ".join(shown[:3])}{"..." if len(shown) > 3 else ""})' if needs + else 'it has package.json and no HTML page') + built = sorted('/'.join(parts[:-1]) for parts in html if parts[-1].lower() == 'index.html' and 2 <= len(parts) <= 3 and parts[-2].lower() in BUILT) + extra = f' The zip also holds a built copy in the {_show(built[0])} folder: zip that folder on its own and import it.' if built else '' + return (f'This zip is a project\'s source, not a finished site: {reason}. Build it first (usually npm run build), then zip the output folder ' + f'(often dist or build) and import that.{extra} Nothing was imported.') + + +def _too_many(count: int, names: list[list[str]]) -> EngineError: + return EngineError(_project(names) or f'The archive holds {count:,} files outside system and dependency folders; a site import takes at most {MAX_ENTRIES:,}. ' + 'Zip only the folder that holds the finished site\'s pages, styles, scripts and pictures, then import that. Nothing was imported.', 413) + + +def _too_large(names: list[list[str]]) -> EngineError: + return EngineError(_project(names) or f'The archive unpacks to more than {_size(MAX_UNPACKED)}, the most a site import takes. ' + 'Leave out large videos and files the site does not use, then zip it again. Nothing was imported.', 413) + + +def _unopened(data: bytes, end: int, listing: int, sentence: str) -> EngineError: + return EngineError(_project(_peek(data, end, listing)) or sentence, 413) + + +def loose(body: bytes): + """The decoded JSON body of a loose-files import, checked by read_files.""" + try: + return json.loads(body) + except (ValueError, RecursionError) as error: + raise EngineError('The list of files to import is not valid JSON. Nothing was imported.', 400) from error + + +def read_files(payload) -> dict: + """Loose HTML files sent as JSON, read into the same structure read_archive gives for a zip holding them at its top level.""" + files = payload.get('files') if isinstance(payload, dict) else None + if not isinstance(files, list) or not all(isinstance(item, dict) and isinstance(item.get('name'), str) and isinstance(item.get('html'), str) for item in files): + raise EngineError('Send the pages as {"files": [{"name": "about.html", "html": "..."}]}. Nothing was imported.', 400) + if not files: + raise EngineError('Choose at least one .html file to import. Nothing was imported.', 400) + if len(files) > MAX_PAGES: + raise EngineError(f'{len(files):,} files were chosen; a site import brings at most {MAX_PAGES} pages. Choose fewer files, or zip the site and import the zip. Nothing was imported.', 413) + entries, seen = [], set() + for item in files: + name = item['name'].replace('\\', '/').rsplit('/', 1)[-1].strip() + if not name or len(name) > MAX_NAME or not name.isprintable() or name.startswith('.'): + raise EngineError(f'The file name {_show(name) or "(empty)"} cannot be imported. Give the file an ordinary name such as about.html. Nothing was imported.', 400) + if _ext(name) not in ('html', 'htm'): + raise EngineError(f'{_show(name)} is not an HTML file. Only .html and .htm files can be imported on their own; zip a site to bring its styles and pictures. Nothing was imported.', 400) + folded = unicodedata.normalize('NFC', name).casefold() + if folded in seen: + raise EngineError(f'Two of the chosen files are named {_show(name)}. Rename one and import again. Nothing was imported.', 400) + seen.add(folded) + entries.append((name, item['html'].encode('utf-8'))) + if sum(len(body) for _, body in entries) > MAX_UNPACKED: + raise EngineError(f'The chosen files add up to more than {_size(MAX_UNPACKED)}, the most a site import takes. Choose fewer files. Nothing was imported.', 413) + kept: dict[str, tuple[str, bytes]] = {} + skipped: list[dict] = [] + for name, body in sorted(entries, key=lambda entry: entry[0].lower()): + if len(body) > FILE_CAPS['page']: + skipped.append({'file': name, 'reason': f'Larger than the {_size(FILE_CAPS["page"])} a file of this type may be.'}) + continue + kept[name] = ('page', body) + return {'files': kept, 'skipped': skipped, 'ignored': 0} + + def read_archive(data: bytes) -> dict: """Entries kept by kind with their bytes, the skipped ones with a reason, and how many system files were ignored.""" if not data: - raise EngineError('Choose a .zip file that holds the site.') + raise EngineError('Choose a .zip file that holds the site. Nothing was imported.') if len(data) > MAX_SITE_ARCHIVE_BYTES: - raise EngineError(f'The archive is larger than {_size(MAX_SITE_ARCHIVE_BYTES)}, the most a site import takes.', 413) + raise EngineError(f'The archive is larger than {_size(MAX_SITE_ARCHIVE_BYTES)}, the most a site import takes. Zip only the folder that holds the finished site, ' + 'leaving out large videos and files it does not use. Nothing was imported.', 413) end = data.rfind(b'PK\x05\x06', max(0, len(data) - 65558)) if end < 0 or len(data) < end + 22: - raise EngineError('This file is not a zip archive FormWeb can read.', 400) + raise EngineError('This file is not a zip archive FormWeb can read. Nothing was imported.', 400) count, listing = struct.unpack(' MAX_ENTRIES: - raise EngineError(f'The archive holds {count:,} entries; a site import takes at most {MAX_ENTRIES:,}. Nothing was imported.', 413) + if count > MAX_RAW_ENTRIES: + raise _unopened(data, end, listing, f'The archive holds {count:,} entries, more than the {MAX_RAW_ENTRIES:,} a site import opens, counting the system and dependency folders it ' + 'leaves out. Zip only the folder that holds the finished site, then import that. Nothing was imported.') if listing > MAX_LISTING: - raise EngineError('The archive\'s list of files is far longer than a website needs, so it was not opened.', 413) + raise _unopened(data, end, listing, 'The archive\'s list of files is far longer than a website needs, so it was not opened. Zip only the folder that holds the finished site, ' + 'without dependency folders such as node_modules, then import that. Nothing was imported.') try: archive = zipfile.ZipFile(io.BytesIO(data)) infos = archive.infolist() except (zipfile.BadZipFile, zipfile.LargeZipFile, ValueError, OSError, EOFError): - raise EngineError('This file is not a zip archive FormWeb can read.', 400) - if len(infos) > MAX_ENTRIES: - raise EngineError(f'The archive holds {len(infos):,} entries; a site import takes at most {MAX_ENTRIES:,}. Nothing was imported.', 413) + raise EngineError('This file is not a zip archive FormWeb can read. Nothing was imported.', 400) + if len(infos) > MAX_RAW_ENTRIES: + raise _unopened(data, end, listing, f'The archive holds {len(infos):,} entries, more than the {MAX_RAW_ENTRIES:,} a site import opens, counting the system and dependency folders it ' + 'leaves out. Zip only the folder that holds the finished site, then import that. Nothing was imported.') kept, ignored, seen = [], 0, set() for info in infos: raw = info.filename name = raw.replace('\\', '/') - parts = [part for part in name.split('/') if part not in ('', '.')] + parts = _parts(raw) if (info.external_attr >> 16) & 0o170000 == stat.S_IFLNK: - raise EngineError(f'The archive holds a link ({_show(raw)}). Links are not allowed in a site import, so nothing was imported.', 400) + raise EngineError(f'The archive holds a link ({_show(raw)}). Links are not allowed in a site import. Nothing was imported.', 400) if '\x00' in name or name.startswith('/') or re.match(r'^[A-Za-z]:', name) or '..' in parts: - raise EngineError(f'The archive names a file outside its own folder ({_show(raw)}), so nothing was imported.', 400) + raise EngineError(f'The archive names a file outside its own folder ({_show(raw)}). Nothing was imported.', 400) if info.flag_bits & 0x1: - raise EngineError('The archive is password protected. Make the zip again without a password.', 400) + raise EngineError('The archive is password protected. Make the zip again without a password. Nothing was imported.', 400) if info.is_dir() or not parts: continue - if len(parts) > MAX_DEPTH: - raise EngineError(f'The archive has folders more than {MAX_DEPTH} levels deep ({_show(raw)}). Nothing was imported.', 400) - if parts[0] == '__MACOSX' or 'node_modules' in parts or any(part.startswith('.') for part in parts): + if _ignored(parts): ignored += 1 continue + if len(parts) > MAX_DEPTH: + raise EngineError(f'The archive has folders more than {MAX_DEPTH} levels deep ({_show(raw)}). Nothing was imported.', 400) key = '/'.join(parts) folded = unicodedata.normalize('NFC', key).casefold() if folded in seen: raise EngineError(f'The archive holds {_show(key)} twice. Nothing was imported.', 400) seen.add(folded) if info.file_size > 1024 * 1024 and info.file_size > MAX_RATIO * max(info.compress_size, 1): - raise EngineError(f'{_show(key)} expands far more than a website file would, so the archive was not opened.', 400) + raise EngineError(f'{_show(key)} expands far more than a website file would, so the archive was not opened. Nothing was imported.', 400) kept.append((parts, info)) + names = [parts for parts, _ in kept] + if len(kept) > MAX_ENTRIES: + raise _too_many(len(kept), names) if kept and all(len(parts) > 1 for parts, _ in kept) and len({parts[0] for parts, _ in kept}) == 1: kept = [(parts[1:], info) for parts, info in kept] if sum(info.file_size for _, info in kept) > MAX_UNPACKED: - raise EngineError(f'The archive unpacks to more than {_size(MAX_UNPACKED)}, the most a site import takes.', 413) + raise _too_large(names) files: dict[str, tuple[str, bytes]] = {} skipped: list[dict] = [] total = 0 @@ -145,7 +264,7 @@ def read_archive(data: bytes) -> dict: continue total += len(body) if total > MAX_UNPACKED: - raise EngineError(f'The archive unpacks to more than {_size(MAX_UNPACKED)}, the most a site import takes.', 413) + raise _too_large(names) if kind == 'asset': wanted = STORED.get(extension, extension) try: @@ -163,6 +282,9 @@ def read_archive(data: bytes) -> dict: skipped.append({'file': path, 'reason': str(error)}) continue files[path] = (kind, body) + source = _project(names, {path: body for path, (kind, body) in files.items() if kind == 'page'}) + if source: + raise EngineError(source, 400) return {'files': files, 'skipped': skipped, 'ignored': ignored} @@ -404,7 +526,7 @@ 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, which an import leaves out')): + for found, noun, where in ((outside_scripts, 'external script', ''), (outside_styles, 'external stylesheet', ' in the page head')): if found: 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 ""}.') From 2af6b88635935670854a7ee8fa0742bb3ed3350a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 16:03:13 -0500 Subject: [PATCH 03/31] feat(library): File > Import HTML files opens the file picker at once for one or several .html files, which become new pages through the same review as a site zip or, for one file, a section of the open page that the canvas then brings into view; the import view shows HTML files, a site zip and pasted code as three separate parts, starts clean on every pick and after an undone import, and keeps its place when a review or a refusal appears --- frontend/src/commands/catalogue.ts | 4 +- frontend/src/features/library/bring.ts | 13 +- frontend/src/features/library/importer.ts | 101 ++++----- frontend/src/features/library/index.ts | 25 ++- frontend/src/features/library/site-import.ts | 222 +++++++++++++++---- frontend/src/main.ts | 4 +- frontend/src/styles/library.css | 16 ++ 7 files changed, 281 insertions(+), 104 deletions(-) diff --git a/frontend/src/commands/catalogue.ts b/frontend/src/commands/catalogue.ts index b3d3dd64..5f96b644 100644 --- a/frontend/src/commands/catalogue.ts +++ b/frontend/src/commands/catalogue.ts @@ -24,8 +24,8 @@ const META: Record = { 'file.new': { description: 'Open the New site dialog to start an empty site in the engine.', flags: 'mr', when: 'Use when the person wants a blank site; it replaces the open site.' }, 'file.projects': { description: 'Open the saved projects list to load one.', flags: 'm', when: 'Use when switching to another saved project.' }, 'file.import': { description: 'Pick a .fweb project file, or a .fpub package of a FormWeb site made by FormPublisher, from disk and load it into the editor.', flags: 'mr', when: 'Use when the person gives a project file to open; it replaces the open site.' }, - 'file.import-html': { description: 'Open the Library panel on its Import HTML tab, where a pasted page or an .html file becomes one code section.', when: 'Use when the person has an HTML page to bring into the open site.' }, - 'file.import-site': { description: 'Open Library > Import site from zip and its file picker: the person picks a .zip of a static site, reviews the pages, routes, assets and skipped files, then imports them as new pages (or replaces matching routes) in one undo step. Agents with the zip bytes can use the library_import_site tool instead.', flags: 'm', when: 'Use when the person has a site built elsewhere as HTML, CSS and JS files to bring in.' }, + 'file.import-html': { description: 'Open the file picker for one or several .html files, with Library > Import HTML behind it. The person then chooses: as new pages (the same review and one-undo-step import as a site zip) or, for one file, as a section of the open page. Agents with the HTML text can use the library_import_html tool instead.', flags: 'm', when: 'Use when the person has one or more HTML files to bring into the open site.' }, + 'file.import-site': { description: 'Open Library > Import site from zip and its file picker for a .zip of a static site (loose .html files are accepted too): the person reviews the pages, routes, assets and skipped files, then imports them as new pages (or replaces matching routes) in one undo step. Agents with the zip bytes can use the library_import_site tool instead.', flags: 'm', when: 'Use when the person has a site built elsewhere as HTML, CSS and JS files to bring in.' }, 'file.save': { description: 'Save the open site as a local project.', flags: 'm', when: 'Use after a set of edits the person wants kept.' }, 'file.download': { description: 'Download the open site as a .fweb project file.' }, 'file.export': { description: 'Export the open site as a portable static HTML ZIP.', flags: 'm' }, diff --git a/frontend/src/features/library/bring.ts b/frontend/src/features/library/bring.ts index 60637a0b..96e56bad 100644 --- a/frontend/src/features/library/bring.ts +++ b/frontend/src/features/library/bring.ts @@ -9,7 +9,7 @@ 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 } { +export function bringChoice(heading: string): { element: HTMLElement; value(): Bring; disable(on: boolean): void; heading(english: string): void } { const box = element('div', 'fw-lib-bring'); const head = element('h3', 'fw-lib-subhead'); label(head, heading); @@ -40,5 +40,14 @@ export function bringChoice(heading: string): { element: HTMLElement; value(): B labelAttr(group, 'aria-label', heading); paint(); box.append(head, group); - return { element: box, value: () => chosen, disable: on => buttons.forEach(button => { button.disabled = on; }) }; + let named = heading; + return { + element: box, value: () => chosen, disable: on => buttons.forEach(button => { button.disabled = on; }), + heading: english => { + if (english === named) return; + named = english; + label(head, english); + labelAttr(group, 'aria-label', english); + } + }; } diff --git a/frontend/src/features/library/importer.ts b/frontend/src/features/library/importer.ts index 5da46e37..e2a1235e 100644 --- a/frontend/src/features/library/importer.ts +++ b/frontend/src/features/library/importer.ts @@ -3,38 +3,62 @@ import { element, text } from '../../ui/dom'; import { icon } from '../../ui/icons'; import { labelAttr, t } from '../../i18n'; import type { LibResult, LibraryHooks } from './types'; -import { bringChoice } from './bring'; +import { bringChoice, type Bring } from './bring'; + +/** 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 { + 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; + 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.'); } + 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); + made?.([result.root, root].filter((id): id is string => !!id)); + hooks.notify(note, false); + return message; +} /** - * Import HTML: paste a whole page (or pick an .html file) and optionally some CSS; the server turns it into one code - * section placed like any other insert. The kit's reduced, onTheme and token helpers are provided there. + * The Library's import view: three separate ways in, in this order. HTML files (one or several, picked and reviewed in + * the site import view), a whole site in a .zip (the same review), and pasted HTML code, which the server turns into one + * code section placed like any other insert. The kit's reduced, onTheme and token helpers are provided there. */ export class HtmlImport { readonly element = element('div', 'fw-lib-view fw-lib-import'); private name = element('input'); private html = element('textarea', 'fw-lib-area fw-lib-code'); private css = element('textarea', 'fw-lib-area fw-lib-code'); - private file = element('input'); private note = element('p', 'fw-lib-note'); private go = element('button', 'fw-lib-insert primary'); private bring = bringChoice('Bring it in as'); private busy = false; - constructor(private hooks: LibraryHooks, openSite: () => void) { + constructor(private hooks: LibraryHooks, openFiles: () => void, openSite: () => void) { const scroller = element('div', 'fw-lib-scroll'); - const site = element('button', 'fw-lib-choose fw-lib-site-open', t('Import site from zip...')); - site.type = 'button'; - site.prepend(icon('upload')); - site.addEventListener('click', openSite); - const help = element('p', 'fw-lib-help', t('Brings in one web page made somewhere else as a section of this page. Paste its HTML or choose the .html file: its styles and main script come along, and the script runs in Preview and on the published site.')); - labelAttr(help, 'title', 'Turns one whole HTML page into a code section. Its styles and first module script come along, and the formai kit helpers reduced, onTheme and token are provided. A code section runs its own JavaScript in Preview and in exports.'); - scroller.append( - element('h3', 'fw-lib-subhead', t('Import a whole site')), - element('p', 'fw-lib-help', t('A .zip of a static site made elsewhere: every HTML file becomes a page, with its stylesheets, pictures and fonts. You review the pages before anything changes.')), - site, - element('h3', 'fw-lib-subhead', t('Import HTML')), - help - ); + const part = (english: string, help: string, ...body: HTMLElement[]): HTMLElement => { + const box = element('section', 'fw-lib-import-part'); + box.append(element('h3', 'fw-lib-subhead', t(english)), element('p', 'fw-lib-help', t(help)), ...body); + return box; + }; + const chooser = (english: string, run: () => void): HTMLButtonElement => { + const button = element('button', 'fw-lib-choose', t(english)); + button.type = 'button'; + button.prepend(icon('folder')); + button.addEventListener('click', run); + return button; + }; + const files = part('HTML files', 'Choose one or several .html files. Each becomes a new page, or a single file can go into this page as a section.', chooser('Choose .html files...', openFiles)); + files.querySelector('.fw-lib-choose')?.classList.add('fw-lib-files-open'); + const site = part('A whole site in a .zip', 'A .zip of a static site made elsewhere: every HTML file becomes a page, with its stylesheets, pictures and fonts. You review the pages before anything changes.', chooser('Choose a .zip file...', openSite)); + site.querySelector('.fw-lib-choose')?.classList.add('fw-lib-site-open'); + const paste = part('Paste HTML code', 'Paste the HTML of one page to add it to this page as a section. Its styles and main script come along, and the script runs in Preview and on the published site.'); + labelAttr(paste.querySelector('.fw-lib-help')!, 'title', 'Turns one whole HTML page into a code section. Its styles and first module script come along, and the formai kit helpers reduced, onTheme and token are provided. A code section runs its own JavaScript in Preview and in exports.'); + scroller.append(files, site, paste); this.name.type = 'text'; this.name.maxLength = 120; this.name.setAttribute('aria-label', t('Section name')); @@ -46,35 +70,19 @@ export class HtmlImport { this.css.rows = 4; this.css.spellcheck = false; this.css.setAttribute('aria-label', t('Extra CSS')); - this.file.type = 'file'; - this.file.accept = '.html,.htm,text/html'; - this.file.hidden = true; - const pick = element('button', 'fw-lib-choose', t('Choose an .html file')); - pick.type = 'button'; - pick.prepend(icon('folder')); - pick.addEventListener('click', () => this.file.click()); - this.file.addEventListener('change', () => { - const chosen = this.file.files?.[0]; - this.file.value = ''; - if (!chosen) return; - chosen.text().then(body => { this.html.value = body; if (!this.name.value) this.name.value = chosen.name.replace(/\.html?$/i, ''); this.say(chosen.name, false); }) - .catch(error => this.say(error instanceof Error ? error.message : String(error), true)); - }); const field = (label: string, control: HTMLElement): HTMLElement => { const wrap = element('div', 'field'); wrap.append(element('span', 'field-label', label), control); return wrap; }; const fields = element('div', 'fw-lib-fields'); - fields.append(field(t('Section name'), this.name), field(t('HTML'), this.html), pick, this.file, field(t('Extra CSS (optional)'), this.css)); - scroller.append(fields, this.bring.element); + fields.append(field(t('Section name'), this.name), field(t('HTML'), this.html), field(t('Extra CSS (optional)'), this.css)); this.note.setAttribute('role', 'status'); this.go.type = 'button'; this.go.append(icon('plus'), element('span', '', t('Import as section'))); this.go.addEventListener('click', () => void this.submit()); - const foot = element('div', 'fw-lib-foot'); - foot.append(this.note, this.go); - this.element.append(scroller, foot); + paste.append(fields, this.bring.element, this.go, this.note); + this.element.append(scroller); } private say(message: string, error: boolean): void { @@ -84,26 +92,13 @@ export class HtmlImport { private async submit(): Promise { if (this.busy) return; - if (!this.html.value.trim()) { this.say(t('Paste a page or choose an .html file first.'), true); this.html.focus(); return; } + if (!this.html.value.trim()) { this.say(t('Paste the HTML of a page first.'), true); this.html.focus(); return; } this.busy = true; this.go.disabled = true; this.say('', false); try { - const where = this.hooks.placement(); - const result = await libraryMutate('/api/library/import-html', { - html: this.html.value, css: this.css.value || undefined, name: this.name.value.trim() || undefined, - parent: where.parent, index: where.index, page: where.page - }); - let message = result.warnings?.[0] || t('HTML section imported.'); - let note = t('HTML section imported.'); - if (result.root && this.bring.value() === 'elements') { - this.say(t('Converting...'), false); - try { const done = await this.hooks.convert([result.root]); message = note = done.message + ' ' + t('Undo once to get the pages back as code, twice to remove them.'); } - catch (error) { message = note = t('HTML section imported.') + ' ' + t('The pages stayed code sections: {0}', [error instanceof Error ? error.message : String(error)]); } - } - if (result.root) this.hooks.select(result.root); - this.say(message, false); - this.hooks.notify(note, false); + const body = { html: this.html.value, css: this.css.value || undefined, name: this.name.value.trim() || undefined }; + this.say(await importSection(this.hooks, body, this.bring.value(), message => this.say(message, false)), false); } catch (error) { this.say(error instanceof Error ? error.message : String(error), true); } finally { diff --git a/frontend/src/features/library/index.ts b/frontend/src/features/library/index.ts index 1681e5a1..5d4bc0be 100644 --- a/frontend/src/features/library/index.ts +++ b/frontend/src/features/library/index.ts @@ -10,7 +10,7 @@ import type { LibIndex, LibResult, LibSection, LibraryHooks } from './types'; import '../../styles/library.css'; export type { LibraryHooks } from './types'; -export type LibraryPanel = { element: HTMLElement; setVisible: (on: boolean) => void; showTab: (id: Tab) => void; importSite: () => void }; +export type LibraryPanel = { element: HTMLElement; setVisible: (on: boolean) => void; showTab: (id: Tab) => void; importSite: () => void; importHtml: () => void }; type Tab = 'sections' | 'kits' | 'import'; @@ -42,8 +42,14 @@ export function installLibrary(hooks: LibraryHooks): LibraryPanel { }); const kits = new Kits(hooks, page => hooks.openPage(page)); let site = false; - const importer = new HtmlImport(hooks, () => importSite()); - const siteImport = new SiteImport(hooks, () => { site = false; paint(); }); + const importer = new HtmlImport(hooks, () => importHtml(), () => importSite()); + const siteImport = new SiteImport(hooks, () => { site = false; settle(); paint(); }, () => { tab = 'import'; site = true; paint(); }); + /** A finished import is not kept for later: coming back finds the import view in its waiting state. */ + function settle(): void { + if (!siteImport.finished) return; + siteImport.reset(); + site = false; + } const tabs = element('div', 'fw-seg fw-lib-tabs'); tabs.setAttribute('role', 'tablist'); @@ -54,7 +60,7 @@ export function installLibrary(hooks: LibraryHooks): LibraryPanel { button.type = 'button'; if (id === 'kits') labelAttr(button, 'title', 'Presets and starters'); button.setAttribute('role', 'tab'); - button.addEventListener('click', () => { tab = id; paint(); }); + button.addEventListener('click', () => { if (id === 'import' && tab !== 'import') settle(); tab = id; paint(); }); buttons.set(id, button); tabs.append(button); } @@ -77,11 +83,18 @@ export function installLibrary(hooks: LibraryHooks): LibraryPanel { const showDetail = tab === 'sections' && !!opened; if (detail.element.hidden === showDetail) detail.element.hidden = !showDetail; } + /** Both open the system file picker in the same click; HTML files with the import view behind it, a zip with the review view. */ function importSite(): void { tab = 'import'; site = true; paint(); - siteImport.choose(); + siteImport.choose('site'); + } + function importHtml(): void { + tab = 'import'; + site = false; + paint(); + siteImport.choose('html'); } function open(section: LibSection): void { opened = section.id; @@ -127,7 +140,9 @@ export function installLibrary(hooks: LibraryHooks): LibraryPanel { return { element: root, importSite, + importHtml, setVisible(on: boolean): void { + if (on && root.hidden) { settle(); paint(); } if (root.hidden === on) root.hidden = !on; if (on) void load(); }, diff --git a/frontend/src/features/library/site-import.ts b/frontend/src/features/library/site-import.ts index ae039402..f10bfdab 100644 --- a/frontend/src/features/library/site-import.ts +++ b/frontend/src/features/library/site-import.ts @@ -4,23 +4,43 @@ import { icon } from '../../ui/icons'; import { label, t } from '../../i18n'; import type { LibraryHooks, SitePage, SiteResult, SiteReview, SiteSkip } from './types'; import { bringChoice } from './bring'; -import { state } from '../../api'; +import { importSection } from './importer'; +import { state, subscribe } from '../../api'; type Mode = 'new' | 'replace'; +type Use = 'pages' | 'section'; +type Loose = { name: string; html: string }; const size = (bytes: number): string => bytes >= 1048576 ? `${(bytes / 1048576).toFixed(1)} MiB` : `${Math.max(1, Math.round(bytes / 1024))} KiB`; +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); /** - * Import site from zip: pick a .zip holding a static site, read the server's review of it (pages and their routes, - * assets, what is skipped and why), choose new pages or replacing matching routes, then import in one undo step. + * Import HTML files or a site from a zip: pick one .zip holding a static site, or one or several loose .html files, + * read the server's review (pages and their routes, assets, what is skipped and why), choose new pages or replacing + * matching routes, then import in one undo step. A single loose file can instead go into the open page as a section. * Every block is mounted once and shown by `hidden`; the lists are keyed. */ export class SiteImport { readonly element = element('div', 'fw-lib-view fw-lib-import fw-lib-site'); private file = element('input'); + private title = element('h3', 'fw-lib-subhead'); + private help = element('div', 'fw-lib-site-help'); + private helpHtml = element('p', 'fw-lib-help'); + private helpZip = element('p', 'fw-lib-help'); + private made: string[] = []; private pick = element('button', 'fw-lib-choose'); - private chosen = element('p', 'fw-lib-site-file'); + private pickLabel = element('span'); + private chosen = element('div', 'fw-lib-site-files'); + private uses = element('div', 'fw-seg fw-lib-site-modes fw-lib-site-uses'); + private asPages = element('button', 'fw-seg-btn'); + private asSection = element('button', 'fw-seg-btn'); + private useNote = element('p', 'fw-lib-row-meta fw-lib-site-use-note'); + private section = element('p', 'fw-lib-help fw-lib-site-section'); + private scroller = element('div', 'fw-lib-scroll'); private review = element('div', 'fw-lib-site-review'); + private reviewTail = element('div', 'fw-lib-site-skipped'); private counts = element('p', 'fw-lib-row-text'); private pages = element('div', 'fw-lib-site-list'); private modes = element('div', 'fw-seg fw-lib-site-modes'); @@ -33,30 +53,50 @@ export class SiteImport { private go = element('button', 'fw-lib-insert primary'); private goLabel = element('span'); private bring = bringChoice('Bring pages in as'); + private working = ''; private current: File | null = null; + private loose: Loose[] | null = null; + private picked: File[] = []; + private kind: 'html' | 'site' = 'site'; + private use: Use = 'pages'; private plan: SiteReview | null = null; private mode: Mode = 'new'; private busy = false; private done = false; - constructor(private hooks: LibraryHooks, back: () => void) { - const scroller = element('div', 'fw-lib-scroll'); + constructor(private hooks: LibraryHooks, back: () => void, private show: () => void) { + const scroller = this.scroller; const backButton = element('button', 'fw-lib-choose fw-lib-site-back'); backButton.type = 'button'; backButton.append(icon('chevronLeft'), element('span', '', t('Import HTML'))); backButton.addEventListener('click', back); + text(this.helpHtml, t('Each file becomes a new page at the address shown in the review, or a single file goes into the open page as a section.')); + 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(); }); this.file.type = 'file'; - this.file.accept = '.zip,application/zip'; + this.file.multiple = true; this.file.hidden = true; this.file.addEventListener('change', () => { - const picked = this.file.files?.[0]; + const picked = Array.from(this.file.files || []); this.file.value = ''; - if (picked) void this.read(picked); + if (picked.length) void this.read(picked); }); this.pick.type = 'button'; - this.pick.append(icon('folder'), element('span', '', t('Choose a .zip file'))); - this.pick.addEventListener('click', () => this.choose()); + this.pick.append(icon('folder'), this.pickLabel); + this.pick.addEventListener('click', () => this.choose(this.kind)); this.chosen.setAttribute('aria-live', 'polite'); + for (const [button, use, english] of [[this.asPages, 'pages', 'As new pages'], [this.asSection, 'section', 'As a section of this page']] as [HTMLButtonElement, Use, string][]) { + button.type = 'button'; + label(button, english); + button.setAttribute('role', 'radio'); + button.addEventListener('click', () => { if (!button.disabled) { this.use = use; this.paint(); } }); + this.uses.append(button); + } + this.uses.setAttribute('role', 'radiogroup'); + this.uses.setAttribute('aria-label', t('Bring the files in')); + this.section.hidden = true; + text(this.section, t('The page goes into the open page as one section, after the selected section. Its styles and main script come along.')); for (const [button, mode, english] of [[this.fresh, 'new', 'Add as new pages'], [this.replace, 'replace', 'Replace matching routes']] as [HTMLButtonElement, Mode, string][]) { button.type = 'button'; label(button, english); @@ -68,33 +108,52 @@ export class SiteImport { this.modes.setAttribute('aria-label', t('How to add the pages')); label(this.skippedHead, 'Skipped'); this.review.hidden = true; + this.reviewTail.hidden = true; + this.bring.element.hidden = true; this.review.append( element('h3', 'fw-lib-subhead', t('Review')), this.counts, element('h3', 'fw-lib-subhead', t('Pages')), this.pages, - element('h3', 'fw-lib-subhead', t('Add them')), this.modes, this.modeNote, - this.bring.element, - this.skippedHead, this.skipped - ); - scroller.append( - backButton, - element('h3', 'fw-lib-subhead', t('Import site from zip')), - element('p', 'fw-lib-help', 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.pick, this.file, this.chosen, this.review + element('h3', 'fw-lib-subhead', t('Add them')), this.modes, this.modeNote ); + this.reviewTail.append(this.skippedHead, this.skipped); + scroller.append(backButton, this.title, this.help, this.pick, this.file, this.chosen, this.uses, this.useNote, this.review, this.section, this.bring.element, this.reviewTail, this.note); this.note.setAttribute('role', 'status'); this.go.type = 'button'; this.go.disabled = true; this.go.append(icon('upload'), this.goLabel); this.go.addEventListener('click', () => void this.submit()); const foot = element('div', 'fw-lib-foot'); - foot.append(this.note, this.go); + foot.append(this.go); this.element.append(scroller, foot); this.paint(); } - /** Opens the file picker; File > Import site from zip... lands here. */ - choose(): void { - if (!this.busy) this.file.click(); + /** Opens the file picker inside the caller's click: .html files only, or a .zip (loose .html files allowed too). */ + choose(kind: 'html' | 'site'): void { + if (this.busy) return; + this.reset(); + this.kind = kind; + this.file.accept = kind === 'html' ? HTML_ACCEPT : `.zip,application/zip,${HTML_ACCEPT}`; + this.file.click(); + } + + /** True once an import has finished: the view then holds nothing the person still needs. */ + get finished(): boolean { return this.done && !this.busy; } + + /** Back to the clean waiting state: no files, review, note or finished button, scrolled to the top. */ + reset(): void { + if (this.busy) return; + this.made = []; + this.picked = []; + this.current = null; + this.loose = null; + this.plan = null; + this.mode = 'new'; + this.use = 'pages'; + this.done = false; + this.say('', false); + this.paint(); + this.scroller.scrollTop = 0; } private say(message: string, error: boolean): void { @@ -102,32 +161,52 @@ export class SiteImport { this.note.classList.toggle('is-error', error); } + /** Work in progress reads on the import button, so the note changes only once, to the result. */ + private progress(message: string): void { + this.working = message; + text(this.goLabel, message); + } + private setBusy(on: boolean): void { this.busy = on; + if (!on) this.working = ''; this.pick.disabled = on; this.bring.disable(on); this.element.setAttribute('aria-busy', String(on)); this.paint(); } - private async read(picked: File): Promise { + private async read(files: File[]): Promise { if (this.busy) return; - this.current = picked; + const zips = files.filter(isZip); + const pages = files.filter(isHtml); + this.picked = files; + this.current = null; + this.loose = null; this.plan = null; this.mode = 'new'; + this.use = 'pages'; this.done = false; - text(this.chosen, `${picked.name} (${size(picked.size)})`); - if (picked.size > 64 * 1024 * 1024) { - this.current = null; + this.say('', false); + this.show(); + if (zips.length + pages.length !== files.length || (zips.length && files.length > 1)) { + this.paint(); + this.say(t('Choose one .zip file, or one or more .html files.'), true); + return; + } + if (files.reduce((sum, file) => sum + file.size, 0) > 64 * 1024 * 1024) { this.paint(); - this.say(t('The archive is larger than 64 MiB, the most a site import takes.'), true); + this.say(zips.length ? t('The archive is larger than 64 MiB, the most a site import takes.') : t('The files are larger than 64 MiB together, the most an import takes.'), true); return; } - this.say(t('Reading the archive...'), false); + this.working = zips.length ? t('Reading the archive...') : t('Reading the files...'); this.setBusy(true); try { - this.plan = await request('/api/library/import-site/review', picked); - this.say(this.plan.pages.length ? '' : t('The archive has no HTML page that can be imported.'), !this.plan.pages.length); + if (zips.length) this.current = zips[0]; + else this.loose = await Promise.all(pages.map(async file => ({ name: file.name, html: await file.text() }))); + this.plan = await request('/api/library/import-site/review', this.body()); + const empty = !this.plan.pages.length; + 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); } catch (error) { this.current = null; this.say(error instanceof Error ? error.message : String(error), true); @@ -136,11 +215,53 @@ export class SiteImport { } } + private body(): File | { files: Loose[] } { + return this.current || { files: this.loose || [] }; + } + private paint(): void { const plan = this.plan; - if (this.review.hidden === !!plan) this.review.hidden = !plan; + const html = !!this.picked.length && this.picked.every(isHtml); + const one = html && this.picked.length === 1; + if (!one && this.use === 'section') this.use = 'pages'; + const section = this.use === 'section'; + text(this.title, html ? t('Import HTML files') : t('Import site from zip')); + for (const [node, on] of [[this.helpHtml, html], [this.helpZip, !html]] as [HTMLElement, boolean][]) { + node.classList.toggle('is-on', on); + node.setAttribute('aria-hidden', String(!on)); + } + text(this.pickLabel, this.picked.length ? t('Choose other files...') : t('Choose a .zip file')); + keyed(this.chosen, this.picked, file => file.name, () => { + const node = element('div', 'fw-lib-site-chosen'); + node.append(element('span', 'fw-lib-site-chosen-name'), element('span', 'fw-lib-row-meta')); + return node; + }, (node, file) => { + const [name, meta] = Array.from(node.children) as HTMLElement[]; + text(name, file.name); + text(meta, size(file.size)); + }); + if (this.uses.hidden === html) this.uses.hidden = !html; + this.asPages.disabled = this.done; + this.asSection.disabled = this.done || !one; + for (const [button, use] of [[this.asPages, 'pages'], [this.asSection, 'section']] as [HTMLButtonElement, Use][]) { + button.classList.toggle('is-on', this.use === use); + button.setAttribute('aria-checked', String(this.use === use)); + } + text(this.useNote, html && !one ? t('A section takes one file. Choose a single file to add it to this page as a section.') : ''); + if (this.section.hidden === section) this.section.hidden = !section; + const showReview = !!plan && !section; + if (this.review.hidden === showReview) this.review.hidden = !showReview; + 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'); + if (this.bring.element.hidden === showBring) this.bring.element.hidden = !showBring; const count = plan?.pages.length ?? 0; - text(this.goLabel, this.done ? t('Imported') : count === 1 ? t('Import 1 page') : count ? t('Import {0} pages', [count]) : t('Import site')); + if (section) { + text(this.goLabel, this.working || (this.done ? t('Imported') : t('Import as section'))); + this.go.disabled = this.busy || this.done || !this.loose?.length; + return; + } + text(this.goLabel, this.working || (this.done ? t('Imported') : count === 1 ? t('Import 1 page') : count ? t('Import {0} pages', [count]) : html ? t('Import pages') : t('Import site'))); this.go.disabled = this.busy || this.done || !plan || !count; if (!plan) { keyed(this.pages, [], () => '', () => element('div'), () => undefined); keyed(this.skipped, [], () => '', () => element('div'), () => undefined); return; } if (this.mode === 'replace' && !plan.canReplace) this.mode = 'new'; @@ -149,7 +270,7 @@ export class SiteImport { plan.assets.count === 1 ? t('1 asset ({0}).', [size(plan.assets.bytes)]) : t('{0} assets ({1}).', [plan.assets.count, size(plan.assets.bytes)]), plan.supportFiles === 1 ? t('1 stylesheet or script.') : plan.supportFiles ? t('{0} stylesheets and scripts.', [plan.supportFiles]) : '', plan.skipped.length === 1 ? t('1 file is skipped.') : plan.skipped.length ? t('{0} files are skipped.', [plan.skipped.length]) : '', - plan.ignored ? t('{0} system files are ignored.', [plan.ignored]) : '' + plan.ignored === 1 ? t('1 file in a system or dependency folder is ignored.') : plan.ignored ? t('{0} files in system and dependency folders are ignored.', [plan.ignored]) : '' ]; text(this.counts, parts.filter(Boolean).join(' ')); this.fresh.disabled = this.done; @@ -188,19 +309,39 @@ export class SiteImport { if (meta.hidden) meta.hidden = false; } + private async placeSection(): Promise { + const page = this.loose?.[0]; + if (this.busy || !page) return; + 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; }); + this.done = true; + this.say(message, false); + } catch (error) { + this.say(error instanceof Error ? error.message : String(error), true); + } finally { + this.setBusy(false); + this.note.scrollIntoView({ block: 'nearest' }); + } + } + private async submit(): Promise { + if (this.use === 'section') return this.placeSection(); const plan = this.plan; - if (this.busy || !plan || !this.current) return; - this.say(t('Importing...'), false); + if (this.busy || !plan || (!this.current && !this.loose)) return; + this.working = t('Importing...'); this.setBusy(true); try { const query = `?mode=${this.mode}&revision=${encodeURIComponent(String(plan.revision))}`; - const result = await libraryMutate('/api/library/import-site' + query, this.current); + const result = await libraryMutate('/api/library/import-site' + query, this.body()); let message = result.message || t('Site imported.'); this.done = true; + this.made = result.pages || []; this.current = null; + this.loose = null; if (this.bring.value() === 'elements' && result.pages?.length) { - this.say(t('Converting...'), false); + 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.'); } @@ -213,6 +354,7 @@ export class SiteImport { this.say(error instanceof Error ? error.message : String(error), true); } finally { this.setBusy(false); + this.note.scrollIntoView({ block: 'nearest' }); } } } diff --git a/frontend/src/main.ts b/frontend/src/main.ts index d3350685..49acd9b4 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -444,7 +444,7 @@ const libraryPanel = installLibrary({ const at = anchor && anchor !== root && siblings.includes(anchor) ? siblings.indexOf(anchor) + 1 : siblings.length; return { page: currentPage().id, parent: root, index: at < siblings.length ? at : undefined }; }, - select: id => { selectedId = id; update(state()); }, + select: id => { selectNode(id); canvas.bring(id); }, openPage: id => { const page = state().site.pages.find(entry => entry.id === id); if (!page) return; @@ -2232,7 +2232,7 @@ registerCommands([ { id: 'file.new', label: 'New site...', menu: 'File', run: () => openDialog('new') }, { id: 'file.projects', label: 'Open project...', menu: 'File', run: () => openDialog('projects'), enabled: ready }, { id: 'file.import', label: 'Import .fweb or .fpub file...', menu: 'File', run: () => importer.click() }, - { id: 'file.import-html', label: 'Import HTML...', menu: 'File', run: () => { openDock('left'); setSidebar('library'); libraryPanel.showTab('import'); }, enabled: ready }, + { id: 'file.import-html', label: 'Import HTML files...', menu: 'File', run: () => { if (home.isShown) home.dismiss(); if (layout.state.left !== 'open' || activeSidebar !== 'library') toggleLeft('library'); libraryPanel.importHtml(); }, enabled: ready }, { id: 'file.import-site', label: 'Import site from zip...', menu: 'File', run: () => { if (home.isShown) home.dismiss(); if (layout.state.left !== 'open' || activeSidebar !== 'library') toggleLeft('library'); libraryPanel.importSite(); }, enabled: ready }, { id: 'file.save', label: 'Save', menu: 'File', keys: ['Mod+S'], global: true, group: 1, run: saveProject, enabled: ready }, { id: 'file.download', label: 'Download .fweb project', menu: 'File', group: 1, run: downloadProject, enabled: ready }, diff --git a/frontend/src/styles/library.css b/frontend/src/styles/library.css index 486b89df..b62554a7 100644 --- a/frontend/src/styles/library.css +++ b/frontend/src/styles/library.css @@ -74,16 +74,32 @@ .fw-lib-starter-form { display: flex; flex-direction: column; gap: var(--space-3); margin-top: var(--space-2); padding-top: var(--space-3); border-top: 1px solid var(--line-1); } .fw-lib-starter-form[hidden] { display: none; } .fw-lib-import .fw-lib-fields > .fw-lib-choose { align-self: flex-start; } +.fw-lib-import-part { display: flex; flex-direction: column; align-items: stretch; padding: var(--space-2) 0 var(--space-3); border-top: 1px solid var(--line-1); } +.fw-lib-import-part:first-child { border-top: 0; } +.fw-lib-import-part > .fw-lib-choose { align-self: flex-start; } +.fw-lib-import-part > .fw-lib-bring { margin-top: var(--space-2); } +.fw-lib-import-part > .fw-lib-note { margin-top: var(--space-2); } /* Import site from zip */ .fw-lib-site-back { align-self: flex-start; margin-top: var(--space-2); } .fw-lib-site > .fw-lib-scroll { display: flex; flex-direction: column; align-items: stretch; } +.fw-lib-site > .fw-lib-scroll > * { flex-shrink: 0; } +.fw-lib-site-help { display: grid; } +.fw-lib-site-help > .fw-lib-help { grid-area: 1 / 1; } +.fw-lib-site-help > :not(.is-on) { visibility: hidden; } .fw-lib-site > .fw-lib-scroll > .fw-lib-choose { align-self: flex-start; } .fw-lib-site-file { min-height: 30px; margin: var(--space-1) 0 0; color: var(--text-secondary); font-size: var(--fs-11); line-height: 15px; overflow-wrap: anywhere; } .fw-lib-site-review[hidden], .fw-lib-subhead[hidden] { display: none; } +.fw-lib-site-files { display: flex; flex-direction: column; gap: 2px; min-height: 30px; margin: var(--space-2) 0; } +.fw-lib-site-chosen { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-2); font-size: var(--fs-11); line-height: 15px; } +.fw-lib-site-chosen-name { min-width: 0; color: var(--text-secondary); overflow-wrap: anywhere; } +.fw-lib-site-uses[hidden], .fw-lib-site-section[hidden], .fw-lib-site-skipped[hidden], .fw-lib-bring[hidden] { display: none; } +.fw-lib-site-use-note { margin: 0 0 var(--space-2); } +.fw-lib-site-use-note:empty { display: none; } .fw-lib-site-list { display: flex; flex-direction: column; gap: var(--space-1); margin-bottom: var(--space-2); } .fw-lib-site-item { display: flex; flex-direction: column; gap: var(--space-1); padding: var(--space-2); border: 1px solid var(--line-1); border-radius: var(--radius-md); background: var(--surface-1); } .fw-lib-site-item > [hidden] { display: none; } +.fw-lib-site-item > .fw-lib-row-meta { overflow-wrap: anywhere; } .fw-lib-site-route { color: var(--accent-text); font-family: var(--font-mono); font-size: var(--fs-10); overflow-wrap: anywhere; } .fw-lib-site-modes { flex-direction: column; flex-wrap: nowrap; margin-bottom: var(--space-1); } .fw-lib-site-modes .fw-seg-btn { flex: none; width: 100%; text-align: left; overflow: hidden; text-overflow: ellipsis; } From b1ef7faf29db31585b9c37e0849b135d1ba1a071 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 16:03:23 -0500 Subject: [PATCH 04/31] feat(canvas): a page's script is one named thing: its block on the canvas says Page script and can be clicked and selected, its layer has its own icon, Content opens on its code, and Design and Motion say they do not apply to it; a code section's block says Code section --- frontend/src/features/canvas-menu.ts | 3 +- .../src/features/inspector/code-section.ts | 1 + .../src/features/inspector/script-note.ts | 63 +++++++++++++++++++ frontend/src/main.ts | 7 ++- frontend/src/styles/page-script.css | 4 ++ frontend/src/ui/canvas.ts | 33 ++++++++-- frontend/src/ui/icons.ts | 1 + 7 files changed, 103 insertions(+), 9 deletions(-) create mode 100644 frontend/src/features/inspector/script-note.ts create mode 100644 frontend/src/styles/page-script.css diff --git a/frontend/src/features/canvas-menu.ts b/frontend/src/features/canvas-menu.ts index 359216f5..fe380697 100644 --- a/frontend/src/features/canvas-menu.ts +++ b/frontend/src/features/canvas-menu.ts @@ -1,6 +1,7 @@ import { commands, state } from '../api'; import { commands as registry } from '../commands/registry'; import type { CommandDef } from '../ui/shell'; +import { codeKind } from '../ui/canvas'; import { ctrlClickOffMac, menuKeyPressed, showContextMenu, type MenuEntry, type MenuItem, type OpenMenu } from '../ui/context-menu'; import { t } from '../i18n'; import { invoke } from './panel'; @@ -37,7 +38,7 @@ type Link = { id: string; label: string; tab: 'design' | 'content'; kind: 'style const VECTOR = new Set(['g', 'path', 'defs', 'linearGradient', 'radialGradient', 'stop', 'clipPath', 'mask', 'text', 'textPath', 'symbol', 'use', 'pattern', 'tspan', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon']); const TEXT_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'a', 'button', 'label', 'li', 'blockquote', 'figcaption', 'strong', 'em', 'small', 'b', 'i', 'summary', 'legend', 'dt', 'dd', 'td', 'th', 'caption', 'code', 'pre', 'time']); -const html = (node: SiteNode): boolean => !VECTOR.has(node.tag); +const html = (node: SiteNode): boolean => !VECTOR.has(node.tag) && codeKind(state().site, node.id) !== 'script'; const LINKS: Link[] = [ { id: 'inspector.text-style', label: 'Text style', tab: 'design', kind: 'style', key: 'font-size', applies: node => html(node) && node.tag !== 'svg' && (!!node.text || TEXT_TAGS.has(node.tag)) }, { id: 'inspector.background', label: 'Background', tab: 'design', kind: 'style', key: 'background', applies: node => html(node) && node.tag !== 'img' && node.tag !== 'svg' }, diff --git a/frontend/src/features/inspector/code-section.ts b/frontend/src/features/inspector/code-section.ts index 63c2e00c..fa5f627a 100644 --- a/frontend/src/features/inspector/code-section.ts +++ b/frontend/src/features/inspector/code-section.ts @@ -44,6 +44,7 @@ export function parseImport(source: string): { html: string; css: string; js: st export function installCodeSection(ctx: InspectorContext): { update(next: EditorState, node: SiteNode): void } { const block = ctx.section(ctx.panes.content, 'Code section'); + block.dataset.codeSection = ''; const body = element('div', 'fw-ext-group'); block.append(body); diff --git a/frontend/src/features/inspector/script-note.ts b/frontend/src/features/inspector/script-note.ts new file mode 100644 index 00000000..7862f12b --- /dev/null +++ b/frontend/src/features/inspector/script-note.ts @@ -0,0 +1,63 @@ +import '../../styles/page-script.css'; +import { icon } from '../../ui/icons'; +import { codeKind } from '../../ui/canvas'; +import type { Site } from '../../types'; +import { labeled } from './labeled'; + +export function layerGlyph(): HTMLElement { + const glyph = icon('box'); + glyph.dataset.glyph = 'box'; + glyph.firstElementChild!.setAttribute('data-for', 'box'); + for (const name of ['code', 'script'] as const) { + const svg = icon(name).firstElementChild!; + svg.setAttribute('data-for', name); + glyph.append(svg); + } + return glyph; +} + +export function paintGlyph(glyph: Element, site: Site, id: string): void { + const kind = codeKind(site, id) || 'box'; + if (glyph instanceof HTMLElement && glyph.dataset.glyph && glyph.dataset.glyph !== kind) glyph.dataset.glyph = kind; +} + +export function isPageScript(site: Site, id: string): boolean { + return codeKind(site, id) === 'script'; +} + +export function installScriptPanes(panes: HTMLElement[]): { update(script: boolean, tab: string): string } { + const notes = panes.map(pane => { + const note = labeled('p', 'micro fw-script-note', 'A page script has no box on the page, so these settings do not apply to it.'); + note.hidden = true; + pane.prepend(note); + return note; + }); + let shown = false; + let before = ''; + let offset = 0; + const scroller = (): HTMLElement | null => panes[0].parentElement; + return { + update(script, tab) { + if (script === shown) return tab; + shown = script; + panes.forEach((pane, index) => { + pane.classList.toggle('fw-pane-script', script); + notes[index].hidden = !script; + }); + const box = scroller(); + if (script) { + before = tab === 'design' || tab === 'motion' ? tab : ''; + offset = box?.scrollTop ?? 0; + if (before || tab === 'content') queueMicrotask(() => { + const code = box?.querySelector('[data-code-section]'); + if (box && code && code.getClientRects().length) box.scrollTop += code.getBoundingClientRect().top - box.getBoundingClientRect().top; + }); + return before ? 'content' : tab; + } + const back = before && tab === 'content' ? before : tab; + if (back !== tab) queueMicrotask(() => { if (box) box.scrollTop = offset; }); + before = ''; + return back; + } + }; +} diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 49acd9b4..0ad7246e 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -55,6 +55,7 @@ import { sectionToggle } from './features/panel/fold'; import { watchHelp } from './ui/help-fit'; import { installDecorativeImage } from './features/decorative-image'; import { installPageSlug } from './features/page-slug'; +import { installScriptPanes, isPageScript, layerGlyph, paintGlyph } from './features/inspector/script-note'; import { isLang, label, labelAttr, labelText, language, languages, onLanguage, setLanguage, startLanguage, startPageTranslator, t } from './i18n'; import './styles/features.css'; import './styles/stage-head.css'; @@ -502,6 +503,7 @@ const pagePane = element('div'); const motionPane = element('div'); motionPane.hidden = true; 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, @@ -1520,12 +1522,13 @@ function update(next: EditorState): void { paintSelectMode(); keyed(layersList, layers, item => item.node.id, () => { const row = button('', undefined, undefined, 'list-row layer-row'); - row.append(icon('box'), element('span', 'row-label'), element('span', 'row-detail')); + row.append(layerGlyph(), element('span', 'row-label'), element('span', 'row-detail')); row.addEventListener('click', event => layerRowClick(event, row.dataset.key!)); row.addEventListener('contextmenu', event => showLayerMenu(event, row.dataset.key!)); panel.layerRow(row, event => showLayerMenu(event, row.dataset.key!)); return row; }, (row, item) => { + paintGlyph(row.children[0], site, item.node.id); text(row.children[1] as HTMLElement, item.node.name); text(row.children[2] as HTMLElement, item.node.componentId ? 'instance' : item.node.tag); row.style.setProperty('--depth', String(item.depth)); @@ -1629,7 +1632,7 @@ function update(next: EditorState): void { if (dialogMode === 'locales') updateLocales(); if (dialogMode === 'tokens') updateTokens(); updateBrand(next); - setInspector(activeInspector); + setInspector(scriptPanes.update(isPageScript(site, node.id) && selectedIds().length < 2, activeInspector)); setSidebar(activeSidebar); reportSelection(); revealApp(); diff --git a/frontend/src/styles/page-script.css b/frontend/src/styles/page-script.css new file mode 100644 index 00000000..b369e703 --- /dev/null +++ b/frontend/src/styles/page-script.css @@ -0,0 +1,4 @@ +.icon[data-glyph] > svg { display: none; } +.icon[data-glyph="box"] > svg[data-for="box"], .icon[data-glyph="code"] > svg[data-for="code"], .icon[data-glyph="script"] > svg[data-for="script"] { display: block; } +.fw-pane-script > :not(.fw-script-note) { display: none !important; } +.fw-script-note { margin: 0; padding: var(--space-4); } diff --git a/frontend/src/ui/canvas.ts b/frontend/src/ui/canvas.ts index 92edb62b..adef3683 100644 --- a/frontend/src/ui/canvas.ts +++ b/frontend/src/ui/canvas.ts @@ -34,6 +34,16 @@ function subtreeIds(site: Site, root: string): Set { function scopedFragment(url: string, ids: Record): string { return url.startsWith('#') && ids[url.slice(1)] ? '#' + ids[url.slice(1)] : url; } +export function codeKind(site: Site, id: string): 'script' | 'code' | '' { + const sections = (site.extensions?.code as { sections?: Record } | undefined)?.sections; + const section = sections?.[id]; + if (!section || typeof section !== 'object') return ''; + return !section.html?.trim() && section.js?.trim() ? 'script' : 'code'; +} +function posterWords(kind: string): [string, string] { + if (kind === 'script') return [t('Page script'), t('Runs in Preview and on the published site, not on this canvas.')]; + return [kind === 'code' ? t('Code section') : t('Component'), '']; +} const REVEAL_MS = 2000; const REVEAL_MARGIN = 24; function shift(start: number, end: number, low: number, high: number, center: boolean): number { @@ -91,7 +101,7 @@ export class Canvas { if (this.last) this.render(this.last.site, this.last.page, this.last.selected, this.last.width, this.last.locale, this.last.scope); } - private syncPoster(node: HTMLElement, key: string, id: string, tag: string): void { + private syncPoster(site: Site, node: HTMLElement, key: string, id: string, tag: string): void { const doc = this.doc; if (!doc) return; const dark = Object.prototype.hasOwnProperty.call(this.posters, id) ? this.posters[id] : undefined; @@ -111,10 +121,21 @@ export class Canvas { poster.setAttribute('draggable', 'false'); poster.setAttribute('style', 'display:block;width:100%;height:100%;object-fit:cover;pointer-events:none'); } else { - poster.setAttribute('style', 'display:flex;align-items:center;justify-content:center;width:100%;height:100%;min-height:48px;outline:1px dashed color-mix(in srgb, currentColor 40%, transparent);outline-offset:-1px;font-size:12px;pointer-events:none'); - poster.textContent = t('Component'); + poster.setAttribute('style', 'display:flex;flex-direction:column;gap:2px;align-items:center;justify-content:center;text-align:center;width:100%;height:100%;min-height:48px;font-size:12px;pointer-events:none'); + const note = doc.createElement('span'); + note.setAttribute('style', 'font-size:11px;opacity:.7'); + poster.append(doc.createElement('span'), note); } } + if (wanted === 'div') { + const kind = codeKind(site, id) || 'component'; + const [title, line] = posterWords(kind); + if (poster.getAttribute('data-fw-poster') !== kind) poster.setAttribute('data-fw-poster', kind); + const [head, note] = Array.from(poster.children) as HTMLElement[]; + if (head.textContent !== title) head.textContent = title; + if (note.textContent !== line) note.textContent = line; + if (note.hidden !== !line) note.hidden = !line; + } if (wanted === 'img' && poster.getAttribute('src') !== url) poster.setAttribute('src', url!); if (poster.parentNode !== node || node.lastChild !== poster) node.append(poster); } @@ -154,7 +175,7 @@ export class Canvas { resolve(); }, { once: true }); }); - this.frame.srcdoc = ''; + this.frame.srcdoc = ''; new ResizeObserver(() => this.fit()).observe(stage); } @@ -180,7 +201,7 @@ export class Canvas { private find(id: string): HTMLElement | undefined { if (!this.doc) return undefined; - return [...this.doc.querySelectorAll(`[data-fw-id="${CSS.escape(id)}"]`)].find(node => node.getClientRects().length > 0); + return [...this.doc.querySelectorAll(`[data-fw-id="${CSS.escape(id)}"]`)].map(node => node.getClientRects().length > 0 ? node : node.querySelector(':scope > [data-fw-poster=script]')).find(node => !!node && node.getClientRects().length > 0) ?? undefined; } private bringInto(target: HTMLElement, center: boolean): void { @@ -416,7 +437,7 @@ export class Canvas { const childId = (child as HTMLElement).dataset.fwId; if (childId && !data.children.includes(childId)) child.remove(); } - this.syncPoster(node, key, id, tag); + this.syncPoster(site, node, key, id, tag); } return node; } diff --git a/frontend/src/ui/icons.ts b/frontend/src/ui/icons.ts index 711db12b..72bcdfaf 100644 --- a/frontend/src/ui/icons.ts +++ b/frontend/src/ui/icons.ts @@ -18,6 +18,7 @@ const paths = { check: '', close: '', code: '', + script: '', save: '', folder: '', history: '', From 36e33c61bdb1964198d983a5c6610cdfe1418d0d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 16:03:23 -0500 Subject: [PATCH 05/31] feat(canvas): the mouse resting on a layer outlines its element on the canvas, and resting on an element outlines it and tints its layer, without selecting or scrolling; nothing shows during drags, text editing, open menus or Preview, and View > Show hover outlines turns it off --- frontend/src/commands/catalogue.ts | 1 + frontend/src/features/hover-outline.ts | 137 +++++++++++++++++++++++++ frontend/src/main.ts | 2 + frontend/src/styles/hover-outline.css | 1 + 4 files changed, 141 insertions(+) create mode 100644 frontend/src/features/hover-outline.ts create mode 100644 frontend/src/styles/hover-outline.css diff --git a/frontend/src/commands/catalogue.ts b/frontend/src/commands/catalogue.ts index 5f96b644..87591d60 100644 --- a/frontend/src/commands/catalogue.ts +++ b/frontend/src/commands/catalogue.ts @@ -82,6 +82,7 @@ const META: Record = { 'view.preview-full': { description: 'Open or close the full-window preview of the compiled site as visitors will see it, with a page picker, device widths from the site breakpoints, locale, refresh and open in browser. While it is open every other window command is disabled.', when: 'Use when the person wants to see the finished site; it changes nothing.' }, 'view.theme': { description: 'Switch between the light and dark editor theme.' }, '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.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.' }, 'vector.guides.lock': { description: 'Lock or unlock the guides so they cannot be moved or released. The lock is saved with the SVG and is one undo step.', flags: 'm' }, diff --git a/frontend/src/features/hover-outline.ts b/frontend/src/features/hover-outline.ts new file mode 100644 index 00000000..16f6e175 --- /dev/null +++ b/frontend/src/features/hover-outline.ts @@ -0,0 +1,137 @@ +import { subscribe } from '../api'; +import type { CommandDef } from '../ui/shell'; +import '../styles/hover-outline.css'; + +export interface HoverOutlineHost { + frame: HTMLIFrameElement; + loaded: () => Promise; + list: HTMLElement; + ready: () => boolean; + editing: () => boolean; + busy: () => boolean; + root: () => string; + selectionIds: () => string[]; + status: (message: string) => void; +} + +const KEY = 'formweb.canvas.hover-outline'; +const ATTR = 'data-fw-hover'; +const IDLE = `html:not([data-fw-dragging]):not([data-fw-holding]) [${ATTR}]:not([data-fw-selected]):not([data-fw-marked]):not([data-fw-lifted]):not(body>*)`; +const CANVAS_RULE = `${IDLE},${IDLE}>[data-fw-poster=script]{outline:1px solid #f97316b3!important;outline-offset:1px}`; + +function remembered(): boolean { + try { return localStorage.getItem(KEY) !== '0'; } catch { return true; } +} + +function remember(on: boolean): void { + try { localStorage.setItem(KEY, on ? '1' : '0'); } catch { } +} + +export function installHoverOutline(host: HoverOutlineHost): CommandDef[] { + let on = remembered(); + let doc: Document | null = null; + let shown = ''; + let shownRoot = ''; + let element: HTMLElement | null = null; + let row: HTMLElement | null = null; + let wanted = ''; + let frame = 0; + + const clear = (): void => { + wanted = ''; + if (frame) { cancelAnimationFrame(frame); frame = 0; } + paint(''); + }; + + const blocked = (): boolean => { + if (!on || !doc || !host.ready() || !host.editing() || host.busy()) return true; + const html = doc.documentElement; + if (html.hasAttribute('data-fw-dragging') || html.hasAttribute('data-fw-holding')) return true; + if (doc.querySelector('[contenteditable="true"]')) return true; + const body = document.body.classList; + if (body.contains('fw-row-dragging') || body.contains('fw-row-holding') || body.contains('fw-canvas-dragging')) return true; + return !!document.querySelector('.fw-menu:not([hidden])'); + }; + + const canvasNode = (id: string): HTMLElement | null => { + if (!doc) return null; + for (const node of doc.querySelectorAll(`[data-fw-id="${CSS.escape(id)}"]`)) { + if (node.getClientRects().length || node.querySelector(':scope>[data-fw-poster=script]')?.getClientRects().length) return node; + } + return null; + }; + + const layerRow = (id: string): HTMLElement | null => { + for (const child of host.list.children) if ((child as HTMLElement).dataset.key === id) return child as HTMLElement; + return null; + }; + + function paint(key: string): void { + if (key === shown) return; + element?.removeAttribute(ATTR); + row?.removeAttribute(ATTR); + element = row = null; + shown = key; + if (!key) return; + shownRoot = host.root(); + const at = key.indexOf(':'); + const id = key.slice(at + 1); + element = canvasNode(id); + element?.setAttribute(ATTR, ''); + if (key.startsWith('canvas:')) { row = layerRow(id); row?.setAttribute(ATTR, ''); } + } + + const want = (id: string, from: 'canvas' | 'layers'): void => { + wanted = id && id !== host.root() && !host.selectionIds().includes(id) ? `${from}:${id}` : ''; + if (!frame) frame = requestAnimationFrame(() => { + frame = 0; + paint(blocked() ? '' : wanted); + }); + }; + + const mouse = (event: PointerEvent): boolean => event.pointerType === 'mouse'; + + host.list.addEventListener('pointermove', event => { + if (!mouse(event)) { clear(); return; } + const hit = (event.target as Element | null)?.closest?.('.layer-row'); + want(hit && hit.parentElement === host.list ? hit.dataset.key || '' : '', 'layers'); + }); + host.list.addEventListener('pointerleave', clear); + host.list.addEventListener('pointerdown', clear, true); + host.list.addEventListener('contextmenu', clear, true); + new MutationObserver(() => { + if (!shown) return; + if (host.root() !== shownRoot || !element?.isConnected || (row && !row.isConnected)) clear(); + }).observe(host.list, { childList: true }); + subscribe(() => { if (shown || wanted) clear(); }); + window.addEventListener('blur', clear); + document.documentElement.addEventListener('pointerleave', clear); + + void host.loaded().then(() => { + const at = host.frame.contentDocument; + if (!at) return; + doc = at; + const style = at.createElement('style'); + style.textContent = CANVAS_RULE; + at.head.append(style); + at.addEventListener('pointermove', event => { + if (!mouse(event)) { clear(); return; } + const hit = (event.target as Element | null)?.closest?.('[data-fw-id]'); + want(hit && hit.parentElement !== at.body ? hit.dataset.fwId || '' : '', 'canvas'); + }, { passive: true }); + at.addEventListener('pointerout', event => { if (!event.relatedTarget) clear(); }); + at.addEventListener('pointerdown', clear, true); + at.addEventListener('dblclick', clear, true); + at.addEventListener('contextmenu', clear, true); + }); + + const toggle = (): void => { + on = !on; + remember(on); + if (!on) clear(); + host.status(on ? 'Hover outlines are on: pointing at a layer outlines its element on the canvas, and pointing at an element tints its layer.' : 'Hover outlines are off.'); + }; + return [ + { id: 'view.hover-outline', label: 'Show hover outlines', menu: 'View', group: 2, run: toggle, checked: () => on, enabled: host.ready } + ]; +} diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 0ad7246e..bb9f4ba2 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -50,6 +50,7 @@ import { installPanel } from './features/panel'; import { canvasClick, installSelection, isMulti, isSelected, layerClick, topMost, pageClick, paintLayerRow, paintPageRow, selectedIds, selectedPageIds, selectNodes } from './features/selection'; 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 { installSelectMode, paintSelectMode } from './features/select-mode'; import { sectionToggle } from './features/panel/fold'; import { watchHelp } from './ui/help-fit'; @@ -2326,6 +2327,7 @@ installSelection({ ready, site: () => state().site, primary: () => selectedId, s installSelectionActions({ idle: () => !!scrim.hidden, pageRoot: () => currentPage().root, status, copyNote }); registerCommands(installSelectMode({ heads: [{ head: pagesHead, kind: 'pages' }, { head: layersHead, kind: 'layers' }], lists: [pagesList, layersList], frame: canvas.frame, loaded: canvas.loaded(), ready, status: message => status(message) })); registerCommands(installCanvasDrag({ frame: canvas.frame, stage, overlay, loaded: () => canvas.loaded(), state, ready, editing: () => !preview, root: () => currentPage().root, selectionIds: selectedIds, select: selectNode, commands, run, status }).commands); +registerCommands(installHoverOutline({ frame: canvas.frame, loaded: () => canvas.loaded(), list: layersList, ready, editing: () => !preview && !fullPreview.isOpen, busy: () => insertFlyout.isOpen() || !scrim.hidden, root: () => currentPage().root, selectionIds: selectedIds, status: message => status(message) })); const vector = installVector({ canvas, getSelected: () => selectedId, select: selectNode, pageRoot: () => currentPage().root, notify: message => status(message, true), panelHost: document.body }); registerCommands(vector.commands); const wishlist = installWishlist({ state, commands: batch => commands(batch), selected: () => selectedId, select: selectNode, notify: status, audit: () => request<{ issues: AuditIssue[] }>('/api/audit') }); diff --git a/frontend/src/styles/hover-outline.css b/frontend/src/styles/hover-outline.css new file mode 100644 index 00000000..4787eee0 --- /dev/null +++ b/frontend/src/styles/hover-outline.css @@ -0,0 +1 @@ +.layer-row[data-fw-hover]:not(.active):not(.is-multi) { background: var(--accent-tint); } From eae187c5b7c0771565c8839cd30ce36a64a977b9 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 16:03:23 -0500 Subject: [PATCH 06/31] i18n: the 41 new strings of 0.32.0 (Import HTML files, Page script, hover outlines and the site import's fixed refusals) in all 23 languages --- frontend/src/i18n/keys.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/cs.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/da.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/de.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/es.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/fi.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/fr.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/hu.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/id.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/it.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/ja.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/ko.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/nb.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/nl.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/pl.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/pt-BR.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/ru.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/sv.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/th.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/tr.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/uk.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/vi.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/zh-CN.ts | 41 ++++++++++++++++++++++++++++++ frontend/src/i18n/locales/zh-TW.ts | 41 ++++++++++++++++++++++++++++++ 24 files changed, 984 insertions(+) diff --git a/frontend/src/i18n/keys.ts b/frontend/src/i18n/keys.ts index 9a3ed717..0fa0d9c1 100644 --- a/frontend/src/i18n/keys.ts +++ b/frontend/src/i18n/keys.ts @@ -2899,4 +2899,45 @@ export const KEYS: readonly string[] = [ "1 page was too large to convert at once and stayed a code section: convert it one part at a time with Convert to editable elements.", "{0} pages were too large to convert at once and stayed code sections: convert each one part at a time with Convert to editable elements.", "Check it at phone width in Preview, then adjust under each breakpoint.", + "Import HTML files", + "HTML files", + "Choose one or several .html files. Each becomes a new page, or a single file can go into this page as a section.", + "Choose .html files", + "A whole site in a .zip", + "Paste HTML code", + "Paste the HTML of one page to add it to this page as a section. Its styles and main script come along, and the script runs in Preview and on the published site.", + "Paste the HTML of a page first.", + "As new pages", + "As a section of this page", + "Bring the files in", + "The page goes into the open page as one section, after the selected section. Its styles and main script come along.", + "Choose one .zip file, or one or more .html files.", + "The files are larger than 64 MiB together, the most an import takes.", + "Reading the files", + "None of the files is an HTML page that can be imported.", + "Each file becomes a new page at the address shown in the review, or a single file goes into the open page as a section.", + "Choose other files", + "A section takes one file. Choose a single file to add it to this page as a section.", + "Import pages", + "Page script", + "Runs in Preview and on the published site, not on this canvas.", + "A page script has no box on the page, so these settings do not apply to it.", + "Show hover outlines", + "Hover outlines are on: pointing at a layer outlines its element on the canvas, and pointing at an element tints its layer.", + "Hover outlines are off.", + "The list of files to import is not valid JSON. Nothing was imported.", + "Choose at least one .html file to import.", + "The upload is larger than 64 MiB, the most a site import takes. Zip only the folder that holds the finished site, leaving out large videos and files it does not use. Nothing was imported.", + "The archive unpacks to more than 128.0 MiB, the most a site import takes. Leave out large videos and files the site does not use, then zip it again. Nothing was imported.", + "The chosen files add up to more than 128.0 MiB, the most a site import takes. Choose fewer files. Nothing was imported.", + "The archive's list of files is far longer than a website needs, so it was not opened. Zip only the folder that holds the finished site, without dependency folders such as node_modules, then import that. Nothing was imported.", + "This zip is a project's source, not a finished site: it has package.json and no HTML page. Build it first (usually npm run build), then zip the output folder (often dist or build) and import that. Nothing was imported.", + "Undo once to get the section back as code, twice to remove it.", + "{0} files in system and dependency folders are ignored.", + "1 file in a system or dependency folder is ignored.", + "Choose at least one .html file to import. Nothing was imported.", + "Choose a .zip file that holds the site. Nothing was imported.", + "This file is not a zip archive FormWeb can read. Nothing was imported.", + "The archive is password protected. Make the zip again without a password. Nothing was imported.", + "The archive is larger than 64.0 MiB, the most a site import takes. Zip only the folder that holds the finished site, leaving out large videos and files it does not use. Nothing was imported.", ]; diff --git a/frontend/src/i18n/locales/cs.ts b/frontend/src/i18n/locales/cs.ts index 50e06ed8..35b31f4d 100644 --- a/frontend/src/i18n/locales/cs.ts +++ b/frontend/src/i18n/locales/cs.ts @@ -2899,4 +2899,45 @@ export default [ "1 stránka byla příliš velká na převod najednou a zůstala sekcí kódu: převeďte ji po částech pomocí Převést na upravitelné prvky.", "Stránky příliš velké na převod najednou: {0}; zůstaly sekcemi kódu: převeďte každou po částech pomocí Převést na upravitelné prvky.", "Zkontrolujte ji v Náhledu na šířce telefonu a pak ji upravte u každého zlomového bodu.", + "Importovat soubory HTML", + "Soubory HTML", + "Vyberte jeden nebo více souborů .html. Každý se stane novou stránkou, nebo jeden soubor může přijít na tuto stránku jako sekce.", + "Vybrat soubory .html", + "Celý web v souboru .zip", + "Vložit kód HTML", + "Vložte HTML jedné stránky a přidejte ho na tuto stránku jako sekci. Jeho styly a hlavní skript se přenesou s ním a skript běží v náhledu i na publikovaném webu.", + "Nejdřív vložte HTML stránky.", + "Jako nové stránky", + "Jako sekce této stránky", + "Převzít soubory", + "Stránka přijde do otevřené stránky jako jedna sekce, za vybranou sekci. Její styly a hlavní skript se přenesou s ní.", + "Vyberte jeden soubor .zip, nebo jeden či více souborů .html.", + "Soubory jsou dohromady větší než 64 MiB, což je limit pro import.", + "Čtení souborů", + "Žádný ze souborů není stránka HTML, kterou lze importovat.", + "Každý soubor se stane novou stránkou na adrese uvedené v kontrole, nebo jeden soubor přijde do otevřené stránky jako sekce.", + "Vybrat jiné soubory", + "Sekce pojme jeden soubor. Vyberte jediný soubor a přidejte ho na tuto stránku jako sekci.", + "Importovat stránky", + "Skript stránky", + "Běží v náhledu a na publikovaném webu, ne na tomto plátně.", + "Skript stránky nemá na stránce žádný rámeček, proto se na něj tato nastavení nevztahují.", + "Zobrazit obrysy při najetí", + "Obrysy při najetí jsou zapnuté: ukázání na vrstvu obtáhne její prvek na plátně a ukázání na prvek zvýrazní jeho vrstvu.", + "Obrysy při najetí jsou vypnuté.", + "Seznam souborů k importu není platný JSON. Nic nebylo importováno.", + "Vyberte alespoň jeden soubor .html k importu.", + "Nahrávaná data jsou větší než 64 MiB, což je limit pro import webu. Zabalte do zipu jen složku s hotovým webem a vynechte velká videa a soubory, které nepoužívá. Nic nebylo importováno.", + "Archiv má po rozbalení více než 128.0 MiB, což je limit pro import webu. Vynechte velká videa a soubory, které web nepoužívá, a zabalte ho do zipu znovu. Nic nebylo importováno.", + "Vybrané soubory mají dohromady více než 128.0 MiB, což je limit pro import webu. Vyberte méně souborů. Nic nebylo importováno.", + "Seznam souborů v archivu je mnohem delší, než web potřebuje, proto nebyl otevřen. Zabalte do zipu jen složku s hotovým webem, bez složek závislostí jako node_modules, a importujte ji. Nic nebylo importováno.", + "Tento zip je zdrojový kód projektu, ne hotový web: obsahuje package.json a žádnou stránku HTML. Nejdřív ho sestavte (obvykle npm run build), pak zabalte do zipu výstupní složku (často dist nebo build) a importujte ji. Nic nebylo importováno.", + "Jedním vrácením zpět dostanete sekci zpět jako kód, dvěma ji odstraníte.", + "Ignorované soubory v systémových složkách a složkách závislostí: {0}.", + "1 soubor v systémové složce nebo složce závislostí bude ignorován.", + "Vyberte alespoň jeden soubor .html k importu. Nic nebylo importováno.", + "Vyberte soubor .zip, který obsahuje web. Nic nebylo importováno.", + "Tento soubor není archiv zip, který FormWeb dokáže přečíst. Nic nebylo importováno.", + "Archiv je chráněný heslem. Vytvořte zip znovu bez hesla. Nic nebylo importováno.", + "Archiv je větší než 64.0 MiB, což je limit pro import webu. Zabalte do zipu jen složku s hotovým webem a vynechte velká videa a soubory, které nepoužívá. Nic nebylo importováno.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/da.ts b/frontend/src/i18n/locales/da.ts index bdc914f1..0327c252 100644 --- a/frontend/src/i18n/locales/da.ts +++ b/frontend/src/i18n/locales/da.ts @@ -2899,4 +2899,45 @@ export default [ "1 side var for stor til at blive konverteret på én gang og forblev en kodesektion: konvertér den én del ad gangen med Konvertér til redigerbare elementer.", "{0} sider var for store til at blive konverteret på én gang og forblev kodesektioner: konvertér hver af dem én del ad gangen med Konvertér til redigerbare elementer.", "Tjek den i telefonbredde i Eksempel, og tilpas den derefter under hvert breakpoint.", + "Importér HTML-filer", + "HTML-filer", + "Vælg en eller flere .html-filer. Hver fil bliver en ny side, eller en enkelt fil kan komme ind på denne side som en sektion.", + "Vælg .html-filer", + "Et helt site i en .zip", + "Indsæt HTML-kode", + "Indsæt HTML'en fra én side for at tilføje den til denne side som en sektion. Dens stilarter og hovedscript følger med, og scriptet kører i eksemplet og på det udgivne site.", + "Indsæt først HTML'en fra en side.", + "Som nye sider", + "Som en sektion på denne side", + "Hent filerne ind", + "Siden kommer ind på den åbne side som én sektion, efter den valgte sektion. Dens stilarter og hovedscript følger med.", + "Vælg én .zip-fil eller en eller flere .html-filer.", + "Filerne er tilsammen større end 64 MiB, som er det maksimale for en import.", + "Læser filerne", + "Ingen af filerne er en HTML-side, der kan importeres.", + "Hver fil bliver en ny side på den adresse, gennemgangen viser, eller en enkelt fil kommer ind på den åbne side som en sektion.", + "Vælg andre filer", + "En sektion tager én fil. Vælg en enkelt fil for at tilføje den til denne side som en sektion.", + "Importér sider", + "Sidescript", + "Kører i eksemplet og på det udgivne site, ikke på dette lærred.", + "Et sidescript har ingen boks på siden, så disse indstillinger gælder ikke for det.", + "Vis konturer ved peg", + "Konturer ved peg er slået til: når du peger på et lag, får dets element en kontur på lærredet, og når du peger på et element, fremhæves dets lag.", + "Konturer ved peg er slået fra.", + "Listen over filer, der skal importeres, er ikke gyldig JSON. Intet blev importeret.", + "Vælg mindst én .html-fil at importere.", + "Uploaden er større end 64 MiB, som er det maksimale for en siteimport. Zip kun mappen med det færdige site, og udelad store videoer og filer, det ikke bruger. Intet blev importeret.", + "Arkivet fylder mere end 128.0 MiB udpakket, som er det maksimale for en siteimport. Udelad store videoer og filer, sitet ikke bruger, og zip det igen. Intet blev importeret.", + "De valgte filer fylder tilsammen mere end 128.0 MiB, som er det maksimale for en siteimport. Vælg færre filer. Intet blev importeret.", + "Arkivets filliste er langt længere, end et website har brug for, så det blev ikke åbnet. Zip kun mappen med det færdige site, uden afhængighedsmapper som node_modules, og importér den. Intet blev importeret.", + "Denne zip er et projekts kildekode, ikke et færdigt site: den har package.json og ingen HTML-side. Byg den først (som regel med npm run build), zip derefter outputmappen (ofte dist eller build), og importér den. Intet blev importeret.", + "Fortryd én gang for at få sektionen tilbage som kode, to gange for at fjerne den.", + "{0} filer i system- og afhængighedsmapper ignoreres.", + "1 fil i en system- eller afhængighedsmappe ignoreres.", + "Vælg mindst én .html-fil at importere. Intet blev importeret.", + "Vælg en .zip-fil, der indeholder sitet. Intet blev importeret.", + "Denne fil er ikke et zip-arkiv, som FormWeb kan læse. Intet blev importeret.", + "Arkivet er beskyttet med adgangskode. Lav zip-filen igen uden adgangskode. Intet blev importeret.", + "Arkivet er større end 64.0 MiB, som er det maksimale for en siteimport. Zip kun mappen med det færdige site, og udelad store videoer og filer, det ikke bruger. Intet blev importeret.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/de.ts b/frontend/src/i18n/locales/de.ts index 333199e6..1af54ec5 100644 --- a/frontend/src/i18n/locales/de.ts +++ b/frontend/src/i18n/locales/de.ts @@ -2899,4 +2899,45 @@ export default [ "1 Seite war zu groß, um auf einmal umgewandelt zu werden, und blieb ein Codeabschnitt: Wandle sie mit In bearbeitbare Elemente umwandeln Teil für Teil um.", "{0} Seiten waren zu groß, um auf einmal umgewandelt zu werden, und blieben Codeabschnitte: Wandle jede mit In bearbeitbare Elemente umwandeln Teil für Teil um.", "Prüfe sie in der Vorschau in Handybreite und passe sie dann an jedem Breakpoint an.", + "HTML-Dateien importieren", + "HTML-Dateien", + "Wähle eine oder mehrere .html-Dateien. Jede wird eine neue Seite, oder eine einzelne Datei kommt als Abschnitt in diese Seite.", + ".html-Dateien auswählen", + "Eine ganze Website als .zip", + "HTML-Code einfügen", + "Füge das HTML einer Seite ein, um es dieser Seite als Abschnitt hinzuzufügen. Seine Stile und sein Hauptskript kommen mit, und das Skript läuft in der Vorschau und auf der veröffentlichten Website.", + "Füge zuerst das HTML einer Seite ein.", + "Als neue Seiten", + "Als Abschnitt dieser Seite", + "Dateien übernehmen", + "Die Seite kommt als ein Abschnitt in die geöffnete Seite, nach dem ausgewählten Abschnitt. Ihre Stile und ihr Hauptskript kommen mit.", + "Wähle eine .zip-Datei oder eine oder mehrere .html-Dateien.", + "Die Dateien sind zusammen größer als 64 MiB, das Maximum für einen Import.", + "Dateien werden gelesen", + "Keine der Dateien ist eine HTML-Seite, die importiert werden kann.", + "Jede Datei wird eine neue Seite unter der Adresse, die die Überprüfung zeigt, oder eine einzelne Datei kommt als Abschnitt in die geöffnete Seite.", + "Andere Dateien auswählen", + "Ein Abschnitt nimmt eine Datei auf. Wähle eine einzelne Datei, um sie dieser Seite als Abschnitt hinzuzufügen.", + "Seiten importieren", + "Seitenskript", + "Läuft in der Vorschau und auf der veröffentlichten Website, nicht auf dieser Arbeitsfläche.", + "Ein Seitenskript hat keinen Kasten auf der Seite, daher gelten diese Einstellungen nicht für es.", + "Umrisse beim Darüberfahren anzeigen", + "Umrisse beim Darüberfahren sind an: Zeigst du auf eine Ebene, wird ihr Element auf der Arbeitsfläche umrandet, und zeigst du auf ein Element, wird seine Ebene hervorgehoben.", + "Umrisse beim Darüberfahren sind aus.", + "Die Liste der zu importierenden Dateien ist kein gültiges JSON. Es wurde nichts importiert.", + "Wähle mindestens eine .html-Datei zum Importieren.", + "Der Upload ist größer als 64 MiB, das Maximum für einen Website-Import. Packe nur den Ordner mit der fertigen Website als Zip und lass große Videos und Dateien weg, die sie nicht nutzt. Es wurde nichts importiert.", + "Das Archiv ist entpackt größer als 128.0 MiB, das Maximum für einen Website-Import. Lass große Videos und Dateien weg, die die Website nicht nutzt, und packe es neu als Zip. Es wurde nichts importiert.", + "Die gewählten Dateien sind zusammen größer als 128.0 MiB, das Maximum für einen Website-Import. Wähle weniger Dateien. Es wurde nichts importiert.", + "Die Dateiliste des Archivs ist weit länger, als eine Website braucht, daher wurde es nicht geöffnet. Packe nur den Ordner mit der fertigen Website als Zip, ohne Abhängigkeitsordner wie node_modules, und importiere diesen. Es wurde nichts importiert.", + "Dieses Zip ist der Quellcode eines Projekts, keine fertige Website: Es enthält package.json und keine HTML-Seite. Baue es zuerst (meist mit npm run build), packe dann den Ausgabeordner (oft dist oder build) als Zip und importiere diesen. Es wurde nichts importiert.", + "Einmal rückgängig machen holt den Abschnitt als Code zurück, zweimal entfernt ihn.", + "{0} Dateien in System- und Abhängigkeitsordnern werden ignoriert.", + "1 Datei in einem System- oder Abhängigkeitsordner wird ignoriert.", + "Wähle mindestens eine .html-Datei zum Importieren. Es wurde nichts importiert.", + "Wähle eine .zip-Datei, die die Website enthält. Es wurde nichts importiert.", + "Diese Datei ist kein Zip-Archiv, das FormWeb lesen kann. Es wurde nichts importiert.", + "Das Archiv ist passwortgeschützt. Erstelle das Zip ohne Passwort neu. Es wurde nichts importiert.", + "Das Archiv ist größer als 64.0 MiB, das Maximum für einen Website-Import. Packe nur den Ordner mit der fertigen Website als Zip und lass große Videos und Dateien weg, die sie nicht nutzt. Es wurde nichts importiert.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/es.ts b/frontend/src/i18n/locales/es.ts index ebb3a477..8c2aa480 100644 --- a/frontend/src/i18n/locales/es.ts +++ b/frontend/src/i18n/locales/es.ts @@ -2899,4 +2899,45 @@ export default [ "1 página era demasiado grande para convertirla de una vez y quedó como sección de código: conviértela parte por parte con Convertir en elementos editables.", "{0} páginas eran demasiado grandes para convertirlas de una vez y quedaron como secciones de código: convierte cada una parte por parte con Convertir en elementos editables.", "Revísala con el ancho de un teléfono en Vista previa y luego ajústala en cada punto de interrupción.", + "Importar archivos HTML", + "Archivos HTML", + "Elige uno o varios archivos .html. Cada uno se convierte en una página nueva, o un solo archivo puede entrar en esta página como sección.", + "Elegir archivos .html", + "Un sitio completo en un .zip", + "Pegar código HTML", + "Pega el HTML de una página para incorporarlo a esta página como sección. Sus estilos y su script principal vienen con él, y el script se ejecuta en la vista previa y en el sitio publicado.", + "Pega primero el HTML de una página.", + "Como páginas nuevas", + "Como sección de esta página", + "Traer los archivos", + "La página entra en la página abierta como una sección, después de la sección seleccionada. Sus estilos y su script principal vienen con ella.", + "Elige un archivo .zip, o uno o más archivos .html.", + "Los archivos pesan más de 64 MiB en total, lo máximo que admite una importación.", + "Leyendo los archivos", + "Ninguno de los archivos es una página HTML que se pueda importar.", + "Cada archivo se convierte en una página nueva en la dirección que muestra la revisión, o un solo archivo entra en la página abierta como sección.", + "Elegir otros archivos", + "Una sección admite un solo archivo. Elige un único archivo para incorporarlo a esta página como sección.", + "Importar páginas", + "Script de página", + "Funciona en la vista previa y en el sitio publicado, no en este lienzo.", + "Un script de página no tiene caja en la página, así que estos ajustes no se le aplican.", + "Mostrar contornos al pasar el puntero", + "Los contornos al pasar el puntero están activados: al señalar una capa se marca su elemento en el lienzo, y al señalar un elemento se resalta su capa.", + "Los contornos al pasar el puntero están desactivados.", + "La lista de archivos para importar no es un JSON válido. No se importó nada.", + "Elige al menos un archivo .html para importar.", + "La subida pesa más de 64 MiB, lo máximo que admite una importación de sitio. Comprime en zip solo la carpeta que contiene el sitio terminado, sin archivos multimedia grandes ni archivos que no use. No se importó nada.", + "El archivo comprimido ocupa más de 128.0 MiB al descomprimirse, lo máximo que admite una importación de sitio. Deja fuera los archivos multimedia grandes y los que el sitio no usa, y vuelve a comprimirlo en zip. No se importó nada.", + "Los archivos elegidos suman más de 128.0 MiB, lo máximo que admite una importación de sitio. Elige menos archivos. No se importó nada.", + "La lista de archivos del archivo comprimido es mucho más larga de lo que necesita un sitio web, así que no se abrió. Comprime en zip solo la carpeta que contiene el sitio terminado, sin carpetas de dependencias como node_modules, y luego impórtala. No se importó nada.", + "Este zip es el código fuente de un proyecto, no un sitio terminado: tiene package.json y ninguna página HTML. Compílalo primero (normalmente con npm run build), luego comprime en zip la carpeta de salida (a menudo dist o build) e impórtala. No se importó nada.", + "Deshaz una vez para recuperar la sección como código y dos veces para quitarla.", + "Se ignoran {0} archivos de carpetas del sistema y de dependencias.", + "Se ignora 1 archivo de una carpeta del sistema o de dependencias.", + "Elige al menos un archivo .html para importar. No se importó nada.", + "Elige un archivo .zip que contenga el sitio. No se importó nada.", + "Este archivo no es un archivo zip que FormWeb pueda leer. No se importó nada.", + "El archivo comprimido está protegido con contraseña. Vuelve a crear el zip sin contraseña. No se importó nada.", + "El archivo comprimido pesa más de 64.0 MiB, lo máximo que admite una importación de sitio. Comprime en zip solo la carpeta que contiene el sitio terminado, sin archivos multimedia grandes ni archivos que no use. No se importó nada.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/fi.ts b/frontend/src/i18n/locales/fi.ts index 62d1da5d..37ba3478 100644 --- a/frontend/src/i18n/locales/fi.ts +++ b/frontend/src/i18n/locales/fi.ts @@ -2899,4 +2899,45 @@ export default [ "1 sivu oli liian suuri muunnettavaksi kerralla ja jäi koodiosioksi: muunna se osa kerrallaan toiminnolla Muunna muokattaviksi elementeiksi.", "{0} sivua oli liian suuria muunnettaviksi kerralla ja jäi koodiosioiksi: muunna kukin osa kerrallaan toiminnolla Muunna muokattaviksi elementeiksi.", "Tarkista se puhelimen leveydellä Esikatselussa ja säädä sitten kunkin breakpointin alla.", + "Tuo HTML-tiedostoja", + "HTML-tiedostot", + "Valitse yksi tai useampi .html-tiedosto. Jokaisesta tulee uusi sivu, tai yksittäinen tiedosto voi tulla tälle sivulle osiona.", + "Valitse .html-tiedostot", + "Koko sivusto .zip-tiedostona", + "Liitä HTML-koodia", + "Liitä yhden sivun HTML lisätäksesi sen tälle sivulle osiona. Sen tyylit ja pääskripti tulevat mukana, ja skripti toimii esikatselussa ja julkaistulla sivustolla.", + "Liitä ensin sivun HTML.", + "Uusina sivuina", + "Tämän sivun osiona", + "Tuo tiedostot", + "Sivu tulee avoimelle sivulle yhtenä osiona valitun osion jälkeen. Sen tyylit ja pääskripti tulevat mukana.", + "Valitse yksi .zip-tiedosto tai yksi tai useampi .html-tiedosto.", + "Tiedostot ovat yhteensä suurempia kuin 64 MiB, joka on tuonnin enimmäiskoko.", + "Luetaan tiedostoja", + "Mikään tiedostoista ei ole tuotava HTML-sivu.", + "Jokaisesta tiedostosta tulee uusi sivu tarkistuksessa näkyvään osoitteeseen, tai yksittäinen tiedosto tulee avoimelle sivulle osiona.", + "Valitse muut tiedostot", + "Osioon mahtuu yksi tiedosto. Valitse yksi tiedosto lisätäksesi sen tälle sivulle osiona.", + "Tuo sivut", + "Sivun skripti", + "Toimii esikatselussa ja julkaistulla sivustolla, ei tällä piirtoalueella.", + "Sivun skriptillä ei ole laatikkoa sivulla, joten nämä asetukset eivät koske sitä.", + "Näytä ääriviivat osoitettaessa", + "Ääriviivat osoitettaessa ovat käytössä: tason osoittaminen rajaa sen elementin piirtoalueella, ja elementin osoittaminen korostaa sen tason.", + "Ääriviivat osoitettaessa eivät ole käytössä.", + "Tuotavien tiedostojen luettelo ei ole kelvollista JSONia. Mitään ei tuotu.", + "Valitse vähintään yksi tuotava .html-tiedosto.", + "Lähetys on suurempi kuin 64 MiB, joka on sivustotuonnin enimmäiskoko. Pakkaa zip-tiedostoksi vain valmiin sivuston kansio ja jätä pois suuret videot ja tiedostot, joita se ei käytä. Mitään ei tuotu.", + "Arkisto purkautuu suuremmaksi kuin 128.0 MiB, joka on sivustotuonnin enimmäiskoko. Jätä pois suuret videot ja tiedostot, joita sivusto ei käytä, ja pakkaa se uudelleen zip-tiedostoksi. Mitään ei tuotu.", + "Valitut tiedostot ovat yhteensä suurempia kuin 128.0 MiB, joka on sivustotuonnin enimmäiskoko. Valitse vähemmän tiedostoja. Mitään ei tuotu.", + "Arkiston tiedostoluettelo on paljon pidempi kuin verkkosivusto tarvitsee, joten sitä ei avattu. Pakkaa zip-tiedostoksi vain valmiin sivuston kansio ilman riippuvuuskansioita, kuten node_modules, ja tuo se. Mitään ei tuotu.", + "Tämä zip on projektin lähdekoodi eikä valmis sivusto: siinä on package.json eikä yhtään HTML-sivua. Käännä se ensin (yleensä npm run build), pakkaa sitten tuloskansio (usein dist tai build) zip-tiedostoksi ja tuo se. Mitään ei tuotu.", + "Kumoa kerran, niin osio palaa koodiksi, ja kahdesti, niin se poistuu.", + "Ohitettavia tiedostoja järjestelmä- ja riippuvuuskansioissa: {0}.", + "1 järjestelmä- tai riippuvuuskansion tiedosto ohitetaan.", + "Valitse vähintään yksi tuotava .html-tiedosto. Mitään ei tuotu.", + "Valitse .zip-tiedosto, jossa sivusto on. Mitään ei tuotu.", + "Tämä tiedosto ei ole zip-arkisto, jota FormWeb osaa lukea. Mitään ei tuotu.", + "Arkisto on suojattu salasanalla. Tee zip-tiedosto uudelleen ilman salasanaa. Mitään ei tuotu.", + "Arkisto on suurempi kuin 64.0 MiB, joka on sivustotuonnin enimmäiskoko. Pakkaa zip-tiedostoksi vain valmiin sivuston kansio ja jätä pois suuret videot ja tiedostot, joita se ei käytä. Mitään ei tuotu.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/fr.ts b/frontend/src/i18n/locales/fr.ts index c8933c29..da47a695 100644 --- a/frontend/src/i18n/locales/fr.ts +++ b/frontend/src/i18n/locales/fr.ts @@ -2899,4 +2899,45 @@ export default [ "1 page était trop grande pour être convertie d'un coup et est restée une section de code : convertissez-la partie par partie avec Convertir en éléments modifiables.", "{0} pages étaient trop grandes pour être converties d'un coup et sont restées des sections de code : convertissez chacune partie par partie avec Convertir en éléments modifiables.", "Vérifiez-la à la largeur d’un téléphone dans Aperçu, puis ajustez-la à chaque point d’arrêt.", + "Importer des fichiers HTML", + "Fichiers HTML", + "Choisissez un ou plusieurs fichiers .html. Chacun devient une nouvelle page, ou un seul fichier peut entrer dans cette page comme section.", + "Choisir des fichiers .html", + "Un site entier dans un .zip", + "Coller du code HTML", + "Collez le HTML d’une page pour l’ajouter à cette page comme section. Ses styles et son script principal suivent, et le script s’exécute dans l’aperçu et sur le site publié.", + "Collez d’abord le HTML d’une page.", + "Comme nouvelles pages", + "Comme section de cette page", + "Importer les fichiers", + "La page entre dans la page ouverte comme une section, après la section sélectionnée. Ses styles et son script principal suivent.", + "Choisissez un fichier .zip, ou un ou plusieurs fichiers .html.", + "Les fichiers dépassent 64 MiB au total, le maximum accepté pour une importation.", + "Lecture des fichiers", + "Aucun des fichiers n’est une page HTML importable.", + "Chaque fichier devient une nouvelle page à l’adresse indiquée dans la vérification, ou un seul fichier entre dans la page ouverte comme section.", + "Choisir d’autres fichiers", + "Une section ne prend qu’un fichier. Choisissez un seul fichier pour l’ajouter à cette page comme section.", + "Importer les pages", + "Script de page", + "S’exécute dans l’aperçu et sur le site publié, pas sur ce canevas.", + "Un script de page n’a pas de boîte sur la page, ces réglages ne s’y appliquent donc pas.", + "Afficher les contours au survol", + "Les contours au survol sont activés : pointer un calque trace le contour de son élément sur le canevas, et pointer un élément met son calque en évidence.", + "Les contours au survol sont désactivés.", + "La liste des fichiers à importer n’est pas un JSON valide. Rien n’a été importé.", + "Choisissez au moins un fichier .html à importer.", + "L’envoi dépasse 64 MiB, le maximum accepté pour une importation de site. Zippez seulement le dossier qui contient le site terminé, sans les grosses vidéos ni les fichiers qu’il n’utilise pas. Rien n’a été importé.", + "L’archive dépasse 128.0 MiB une fois décompressée, le maximum accepté pour une importation de site. Retirez les grosses vidéos et les fichiers que le site n’utilise pas, puis zippez-la à nouveau. Rien n’a été importé.", + "Les fichiers choisis dépassent 128.0 MiB au total, le maximum accepté pour une importation de site. Choisissez moins de fichiers. Rien n’a été importé.", + "La liste des fichiers de l’archive est bien plus longue que ce dont un site web a besoin, elle n’a donc pas été ouverte. Zippez seulement le dossier qui contient le site terminé, sans dossiers de dépendances comme node_modules, puis importez-le. Rien n’a été importé.", + "Ce zip est la source d’un projet, pas un site terminé : il contient package.json et aucune page HTML. Compilez-le d’abord (en général npm run build), puis zippez le dossier de sortie (souvent dist ou build) et importez-le. Rien n’a été importé.", + "Annulez une fois pour retrouver la section en code, deux fois pour la retirer.", + "{0} fichiers dans des dossiers système et de dépendances sont ignorés.", + "1 fichier dans un dossier système ou de dépendances est ignoré.", + "Choisissez au moins un fichier .html à importer. Rien n’a été importé.", + "Choisissez un fichier .zip qui contient le site. Rien n’a été importé.", + "Ce fichier n’est pas une archive zip que FormWeb peut lire. Rien n’a été importé.", + "L’archive est protégée par un mot de passe. Refaites le zip sans mot de passe. Rien n’a été importé.", + "L’archive dépasse 64.0 MiB, le maximum accepté pour une importation de site. Zippez seulement le dossier qui contient le site terminé, sans les grosses vidéos ni les fichiers qu’il n’utilise pas. Rien n’a été importé.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/hu.ts b/frontend/src/i18n/locales/hu.ts index 8e3f1ad2..c3b470a1 100644 --- a/frontend/src/i18n/locales/hu.ts +++ b/frontend/src/i18n/locales/hu.ts @@ -2899,4 +2899,45 @@ export default [ "1 oldal túl nagy volt az egyszerre történő átalakításhoz, és kódszakasz maradt: alakítsd át részenként az Átalakítás szerkeszthető elemekké paranccsal.", "{0} oldal túl nagy volt az egyszerre történő átalakításhoz, és kódszakasz maradt: alakítsd át mindegyiket részenként az Átalakítás szerkeszthető elemekké paranccsal.", "Nézd meg telefonszélességben az Előnézetben, majd igazítsd az egyes töréspontoknál.", + "HTML-fájlok importálása", + "HTML-fájlok", + "Válassz egy vagy több .html fájlt. Mindegyikből új oldal lesz, vagy egyetlen fájl szakaszként kerülhet erre az oldalra.", + ".html fájlok kiválasztása", + "Egy teljes webhely .zip fájlban", + "HTML-kód beillesztése", + "Illeszd be egy oldal HTML-jét, hogy szakaszként hozzáadd ehhez az oldalhoz. A stílusai és a fő szkriptje is átkerülnek, és a szkript az előnézetben és a közzétett webhelyen fut.", + "Előbb illeszd be egy oldal HTML-jét.", + "Új oldalakként", + "Ennek az oldalnak egy szakaszaként", + "A fájlok behozatala", + "Az oldal egy szakaszként kerül a megnyitott oldalra, a kijelölt szakasz után. A stílusai és a fő szkriptje is átkerülnek.", + "Válassz egy .zip fájlt, vagy egy vagy több .html fájlt.", + "A fájlok együtt nagyobbak 64 MiB-nál, ennyit fogad el legfeljebb egy importálás.", + "A fájlok olvasása", + "Egyik fájl sem importálható HTML-oldal.", + "Minden fájlból új oldal lesz az áttekintésben látható címen, vagy egyetlen fájl szakaszként kerül a megnyitott oldalra.", + "Más fájlok kiválasztása", + "Egy szakasz egy fájlt fogad. Válassz egyetlen fájlt, hogy szakaszként hozzáadd ehhez az oldalhoz.", + "Oldalak importálása", + "Oldalszkript", + "Az előnézetben és a közzétett webhelyen fut, ezen a vásznon nem.", + "Az oldalszkriptnek nincs doboza az oldalon, ezért ezek a beállítások nem vonatkoznak rá.", + "Körvonalak mutatáskor", + "A körvonalak mutatáskor be vannak kapcsolva: ha egy rétegre mutatsz, az eleme körvonalat kap a vásznon, ha pedig egy elemre mutatsz, kiemelődik a rétege.", + "A körvonalak mutatáskor ki vannak kapcsolva.", + "Az importálandó fájlok listája nem érvényes JSON. Semmi sem lett importálva.", + "Válassz legalább egy importálandó .html fájlt.", + "A feltöltés nagyobb 64 MiB-nál, ennyit fogad el legfeljebb egy webhelyimportálás. Csak a kész webhelyet tartalmazó mappát tömörítsd zip fájlba, a nagy videók és a nem használt fájlok nélkül. Semmi sem lett importálva.", + "Az archívum kibontva nagyobb 128.0 MiB-nál, ennyit fogad el legfeljebb egy webhelyimportálás. Hagyd ki a nagy videókat és a webhely által nem használt fájlokat, majd tömörítsd újra zip fájlba. Semmi sem lett importálva.", + "A kiválasztott fájlok együtt nagyobbak 128.0 MiB-nál, ennyit fogad el legfeljebb egy webhelyimportálás. Válassz kevesebb fájlt. Semmi sem lett importálva.", + "Az archívum fájllistája jóval hosszabb, mint amire egy webhelynek szüksége van, ezért nem lett megnyitva. Csak a kész webhelyet tartalmazó mappát tömörítsd zip fájlba, függőségi mappák (például node_modules) nélkül, majd azt importáld. Semmi sem lett importálva.", + "Ez a zip egy projekt forráskódja, nem kész webhely: van benne package.json, de nincs HTML-oldal. Előbb építsd meg (általában npm run build), majd tömörítsd zip fájlba a kimeneti mappát (gyakran dist vagy build), és azt importáld. Semmi sem lett importálva.", + "Egy visszavonással kódként kapod vissza a szakaszt, kettővel eltávolítod.", + "{0} fájl a rendszer- és függőségi mappákban figyelmen kívül marad.", + "1 fájl egy rendszer- vagy függőségi mappában figyelmen kívül marad.", + "Válassz legalább egy importálandó .html fájlt. Semmi sem lett importálva.", + "Válassz egy .zip fájlt, amely a webhelyet tartalmazza. Semmi sem lett importálva.", + "Ez a fájl nem olyan zip archívum, amelyet a FormWeb el tud olvasni. Semmi sem lett importálva.", + "Az archívum jelszóval védett. Készítsd el újra a zip fájlt jelszó nélkül. Semmi sem lett importálva.", + "Az archívum nagyobb 64.0 MiB-nál, ennyit fogad el legfeljebb egy webhelyimportálás. Csak a kész webhelyet tartalmazó mappát tömörítsd zip fájlba, a nagy videók és a nem használt fájlok nélkül. Semmi sem lett importálva.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/id.ts b/frontend/src/i18n/locales/id.ts index e459fec0..549747a1 100644 --- a/frontend/src/i18n/locales/id.ts +++ b/frontend/src/i18n/locales/id.ts @@ -2899,4 +2899,45 @@ export default [ "1 halaman terlalu besar untuk diubah sekaligus dan tetap sebagai bagian kode: ubah satu bagian setiap kali dengan Ubah menjadi elemen yang dapat diedit.", "{0} halaman terlalu besar untuk diubah sekaligus dan tetap sebagai bagian kode: ubah masing-masing satu bagian setiap kali dengan Ubah menjadi elemen yang dapat diedit.", "Periksa di lebar ponsel pada Pratinjau, lalu sesuaikan di setiap breakpoint.", + "Impor file HTML", + "File HTML", + "Pilih satu atau beberapa file .html. Masing-masing menjadi halaman baru, atau satu file bisa masuk ke halaman ini sebagai bagian.", + "Pilih file .html", + "Seluruh situs dalam .zip", + "Tempel kode HTML", + "Tempel HTML satu halaman untuk menambahkannya ke halaman ini sebagai bagian. Gaya dan skrip utamanya ikut terbawa, dan skrip berjalan di Pratinjau dan di situs yang diterbitkan.", + "Tempel dulu HTML sebuah halaman.", + "Sebagai halaman baru", + "Sebagai bagian dari halaman ini", + "Bawa file masuk", + "Halaman masuk ke halaman yang terbuka sebagai satu bagian, setelah bagian yang dipilih. Gaya dan skrip utamanya ikut terbawa.", + "Pilih satu file .zip, atau satu atau beberapa file .html.", + "Total file lebih besar dari 64 MiB, batas maksimal sebuah impor.", + "Membaca file", + "Tidak ada file yang merupakan halaman HTML yang dapat diimpor.", + "Setiap file menjadi halaman baru di alamat yang ditampilkan dalam tinjauan, atau satu file masuk ke halaman yang terbuka sebagai bagian.", + "Pilih file lain", + "Satu bagian hanya menerima satu file. Pilih satu file untuk menambahkannya ke halaman ini sebagai bagian.", + "Impor halaman", + "Skrip halaman", + "Berjalan di Pratinjau dan di situs yang diterbitkan, tidak di kanvas ini.", + "Skrip halaman tidak punya kotak di halaman, jadi pengaturan ini tidak berlaku untuknya.", + "Tampilkan garis saat diarahkan", + "Garis saat diarahkan aktif: mengarahkan ke sebuah layer memberi garis pada elemennya di kanvas, dan mengarahkan ke sebuah elemen menyorot layer-nya.", + "Garis saat diarahkan nonaktif.", + "Daftar file yang akan diimpor bukan JSON yang valid. Tidak ada yang diimpor.", + "Pilih setidaknya satu file .html untuk diimpor.", + "Unggahan lebih besar dari 64 MiB, batas maksimal impor situs. Zip hanya folder yang berisi situs yang sudah jadi, tanpa video besar dan file yang tidak dipakainya. Tidak ada yang diimpor.", + "Arsip menjadi lebih dari 128.0 MiB saat diekstrak, batas maksimal impor situs. Tinggalkan video besar dan file yang tidak dipakai situs, lalu zip lagi. Tidak ada yang diimpor.", + "Total file yang dipilih lebih dari 128.0 MiB, batas maksimal impor situs. Pilih lebih sedikit file. Tidak ada yang diimpor.", + "Daftar file dalam arsip jauh lebih panjang daripada yang dibutuhkan sebuah situs web, jadi arsip tidak dibuka. Zip hanya folder yang berisi situs yang sudah jadi, tanpa folder dependensi seperti node_modules, lalu impor folder itu. Tidak ada yang diimpor.", + "Zip ini adalah kode sumber sebuah proyek, bukan situs yang sudah jadi: isinya package.json dan tidak ada halaman HTML. Build dulu (biasanya npm run build), lalu zip folder hasilnya (sering dist atau build) dan impor folder itu. Tidak ada yang diimpor.", + "Urungkan sekali untuk mendapatkan bagian kembali sebagai kode, dua kali untuk menghapusnya.", + "{0} file di folder sistem dan dependensi diabaikan.", + "1 file di folder sistem atau dependensi diabaikan.", + "Pilih setidaknya satu file .html untuk diimpor. Tidak ada yang diimpor.", + "Pilih file .zip yang berisi situs. Tidak ada yang diimpor.", + "File ini bukan arsip zip yang dapat dibaca FormWeb. Tidak ada yang diimpor.", + "Arsip dilindungi kata sandi. Buat ulang zip tanpa kata sandi. Tidak ada yang diimpor.", + "Arsip lebih besar dari 64.0 MiB, batas maksimal impor situs. Zip hanya folder yang berisi situs yang sudah jadi, tanpa video besar dan file yang tidak dipakainya. Tidak ada yang diimpor.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/it.ts b/frontend/src/i18n/locales/it.ts index 5d345691..7cf5bd1b 100644 --- a/frontend/src/i18n/locales/it.ts +++ b/frontend/src/i18n/locales/it.ts @@ -2899,4 +2899,45 @@ export default [ "1 pagina era troppo grande per essere convertita in una volta ed è rimasta una sezione di codice: convertila una parte alla volta con Converti in elementi modificabili.", "{0} pagine erano troppo grandi per essere convertite in una volta e sono rimaste sezioni di codice: converti ciascuna una parte alla volta con Converti in elementi modificabili.", "Controllala alla larghezza di un telefono in Anteprima, poi regolala in ogni breakpoint.", + "Importa file HTML", + "File HTML", + "Scegli uno o più file .html. Ognuno diventa una nuova pagina, oppure un singolo file può entrare in questa pagina come sezione.", + "Scegli file .html", + "Un sito intero in un .zip", + "Incolla codice HTML", + "Incolla l'HTML di una pagina per aggiungerlo a questa pagina come sezione. I suoi stili e lo script principale vengono inclusi, e lo script viene eseguito nell'anteprima e sul sito pubblicato.", + "Incolla prima l'HTML di una pagina.", + "Come nuove pagine", + "Come sezione di questa pagina", + "Porta i file", + "La pagina entra nella pagina aperta come una sezione, dopo la sezione selezionata. I suoi stili e lo script principale vengono inclusi.", + "Scegli un file .zip, oppure uno o più file .html.", + "I file superano insieme i 64 MiB, il massimo per un'importazione.", + "Lettura dei file", + "Nessuno dei file è una pagina HTML importabile.", + "Ogni file diventa una nuova pagina all'indirizzo mostrato nel riepilogo, oppure un singolo file entra nella pagina aperta come sezione.", + "Scegli altri file", + "Una sezione accetta un solo file. Scegli un singolo file per aggiungerlo a questa pagina come sezione.", + "Importa pagine", + "Script della pagina", + "Funziona nell’anteprima e sul sito pubblicato, non su questa tela.", + "Uno script della pagina non ha un riquadro nella pagina, quindi queste impostazioni non si applicano.", + "Mostra contorni al passaggio del puntatore", + "I contorni al passaggio del puntatore sono attivi: puntando un livello si evidenzia il contorno del suo elemento sulla tela, e puntando un elemento si evidenzia il suo livello.", + "I contorni al passaggio del puntatore sono disattivati.", + "L'elenco dei file da importare non è un JSON valido. Non è stato importato nulla.", + "Scegli almeno un file .html da importare.", + "Il caricamento supera i 64 MiB, il massimo per un'importazione di sito. Comprimi in zip solo la cartella che contiene il sito finito, lasciando fuori video grandi e file che non usa. Non è stato importato nulla.", + "L'archivio supera i 128.0 MiB una volta estratto, il massimo per un'importazione di sito. Lascia fuori video grandi e file che il sito non usa, poi comprimilo di nuovo in zip. Non è stato importato nulla.", + "I file scelti superano insieme i 128.0 MiB, il massimo per un'importazione di sito. Scegli meno file. Non è stato importato nulla.", + "L'elenco dei file dell'archivio è molto più lungo di quanto serva a un sito web, quindi non è stato aperto. Comprimi in zip solo la cartella che contiene il sito finito, senza cartelle di dipendenze come node_modules, poi importala. Non è stato importato nulla.", + "Questo zip è il sorgente di un progetto, non un sito finito: contiene package.json e nessuna pagina HTML. Prima compilalo (di solito con npm run build), poi comprimi in zip la cartella di output (spesso dist o build) e importala. Non è stato importato nulla.", + "Annulla una volta per riavere la sezione come codice, due volte per rimuoverla.", + "{0} file in cartelle di sistema e di dipendenze vengono ignorati.", + "1 file in una cartella di sistema o di dipendenze viene ignorato.", + "Scegli almeno un file .html da importare. Non è stato importato nulla.", + "Scegli un file .zip che contenga il sito. Non è stato importato nulla.", + "Questo file non è un archivio zip che FormWeb può leggere. Non è stato importato nulla.", + "L'archivio è protetto da password. Crea di nuovo lo zip senza password. Non è stato importato nulla.", + "L'archivio supera i 64.0 MiB, il massimo per un'importazione di sito. Comprimi in zip solo la cartella che contiene il sito finito, lasciando fuori video grandi e file che non usa. Non è stato importato nulla.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ja.ts b/frontend/src/i18n/locales/ja.ts index a0a91487..4c1a4dbd 100644 --- a/frontend/src/i18n/locales/ja.ts +++ b/frontend/src/i18n/locales/ja.ts @@ -2899,4 +2899,45 @@ export default [ "1 ページが一度に変換するには大きすぎたため、コードセクションのまま残りました。「編集可能な要素に変換」で 1 部分ずつ変換してください。", "{0} ページが一度に変換するには大きすぎたため、コードセクションのまま残りました。「編集可能な要素に変換」でそれぞれ 1 部分ずつ変換してください。", "プレビューでスマートフォンの幅で確認し、ブレークポイントごとに調整してください。", + "HTML ファイルをインポート", + "HTML ファイル", + "1 つ以上の .html ファイルを選んでください。それぞれが新しいページになるか、1 つのファイルならこのページにセクションとして入れられます。", + ".html ファイルを選択", + "サイト全体を .zip で", + "HTML コードを貼り付け", + "1 ページ分の HTML を貼り付けると、このページにセクションとして追加されます。スタイルとメインスクリプトも一緒に取り込まれ、スクリプトはプレビューと公開サイトで動作します。", + "先にページの HTML を貼り付けてください。", + "新しいページとして", + "このページのセクションとして", + "ファイルの取り込み方", + "ページは開いているページに 1 つのセクションとして、選択したセクションの後に入ります。スタイルとメインスクリプトも一緒に取り込まれます。", + ".zip ファイルを 1 つ、または .html ファイルを 1 つ以上選んでください。", + "ファイルの合計が 64 MiB を超えています。インポートで扱えるのはここまでです。", + "ファイルを読み込んでいます", + "インポートできる HTML ページであるファイルがありません。", + "各ファイルは確認に表示されるアドレスの新しいページになるか、1 つのファイルなら開いているページにセクションとして入ります。", + "別のファイルを選択", + "セクションに入れられるのは 1 ファイルです。このページにセクションとして追加するには、ファイルを 1 つだけ選んでください。", + "ページをインポート", + "ページスクリプト", + "プレビューと公開サイトで動作し、このキャンバスでは動作しません。", + "ページスクリプトはページ上にボックスを持たないため、これらの設定は適用されません。", + "ホバー時の輪郭を表示", + "ホバー時の輪郭がオンです。レイヤーを指すとキャンバス上のその要素に輪郭が付き、要素を指すとそのレイヤーが強調されます。", + "ホバー時の輪郭がオフです。", + "インポートするファイルの一覧が有効な JSON ではありません。何もインポートされませんでした。", + "インポートする .html ファイルを 1 つ以上選んでください。", + "アップロードが 64 MiB を超えています。サイトのインポートで扱えるのはここまでです。完成したサイトのフォルダーだけを zip にし、大きな動画や使っていないファイルは除いてください。何もインポートされませんでした。", + "アーカイブを展開すると 128.0 MiB を超えます。サイトのインポートで扱えるのはここまでです。大きな動画やサイトで使っていないファイルを除き、もう一度 zip にしてください。何もインポートされませんでした。", + "選んだファイルの合計が 128.0 MiB を超えています。サイトのインポートで扱えるのはここまでです。ファイルを減らしてください。何もインポートされませんでした。", + "アーカイブのファイル一覧がウェブサイトに必要な量よりはるかに長いため、開きませんでした。完成したサイトのフォルダーだけを、node_modules などの依存フォルダーなしで zip にし、それをインポートしてください。何もインポートされませんでした。", + "この zip は完成したサイトではなく、プロジェクトのソースです。package.json があり、HTML ページがありません。先にビルドし(通常は npm run build)、出力フォルダー(多くは dist または build)を zip にしてインポートしてください。何もインポートされませんでした。", + "1 回元に戻すとセクションはコードに戻り、2 回元に戻すとセクションが削除されます。", + "システムフォルダーと依存フォルダーにあるファイル {0} 個は無視されます。", + "システムフォルダーまたは依存フォルダーにあるファイル 1 個は無視されます。", + "インポートする .html ファイルを 1 つ以上選んでください。何もインポートされませんでした。", + "サイトが入った .zip ファイルを選んでください。何もインポートされませんでした。", + "このファイルは FormWeb が読める zip アーカイブではありません。何もインポートされませんでした。", + "アーカイブはパスワードで保護されています。パスワードなしで zip を作り直してください。何もインポートされませんでした。", + "アーカイブが 64.0 MiB を超えています。サイトのインポートで扱えるのはここまでです。完成したサイトのフォルダーだけを zip にし、大きな動画や使っていないファイルは除いてください。何もインポートされませんでした。", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ko.ts b/frontend/src/i18n/locales/ko.ts index d84c3804..cd77c4e8 100644 --- a/frontend/src/i18n/locales/ko.ts +++ b/frontend/src/i18n/locales/ko.ts @@ -2899,4 +2899,45 @@ export default [ "페이지 1개가 한 번에 변환하기에는 너무 커서 코드 섹션으로 남았습니다: 편집 가능한 요소로 변환으로 한 부분씩 변환하세요.", "페이지 {0}개가 한 번에 변환하기에는 너무 커서 코드 섹션으로 남았습니다: 편집 가능한 요소로 변환으로 각각 한 부분씩 변환하세요.", "미리 보기에서 휴대폰 너비로 확인한 다음 각 중단점에서 조정하세요.", + "HTML 파일 가져오기", + "HTML 파일", + ".html 파일을 하나 이상 선택하세요. 각 파일은 새 페이지가 되며, 파일 하나는 이 페이지에 섹션으로 넣을 수도 있습니다.", + ".html 파일 선택", + ".zip으로 된 전체 사이트", + "HTML 코드 붙여넣기", + "페이지 하나의 HTML을 붙여넣어 이 페이지에 섹션으로 추가하세요. 스타일과 기본 스크립트도 함께 들어오며, 스크립트는 미리 보기와 게시된 사이트에서 실행됩니다.", + "먼저 페이지의 HTML을 붙여넣으세요.", + "새 페이지로", + "이 페이지의 섹션으로", + "파일 가져오기 방식", + "페이지는 열린 페이지에 선택한 섹션 다음의 섹션 하나로 들어갑니다. 스타일과 기본 스크립트도 함께 들어옵니다.", + ".zip 파일 하나 또는 .html 파일을 하나 이상 선택하세요.", + "파일을 합친 크기가 64 MiB를 넘습니다. 가져오기는 이 크기까지만 받습니다.", + "파일을 읽는 중", + "가져올 수 있는 HTML 페이지인 파일이 없습니다.", + "각 파일은 검토에 표시된 주소의 새 페이지가 되거나, 파일 하나는 열린 페이지에 섹션으로 들어갑니다.", + "다른 파일 선택", + "섹션에는 파일 하나만 들어갑니다. 이 페이지에 섹션으로 추가하려면 파일을 하나만 선택하세요.", + "페이지 가져오기", + "페이지 스크립트", + "미리 보기와 게시된 사이트에서 실행되며 이 캔버스에서는 실행되지 않습니다.", + "페이지 스크립트는 페이지에 상자가 없으므로 이 설정이 적용되지 않습니다.", + "호버 윤곽선 표시", + "호버 윤곽선이 켜져 있습니다. 레이어를 가리키면 캔버스에서 해당 요소에 윤곽선이 표시되고, 요소를 가리키면 해당 레이어가 강조됩니다.", + "호버 윤곽선이 꺼져 있습니다.", + "가져올 파일 목록이 올바른 JSON이 아닙니다. 아무것도 가져오지 않았습니다.", + "가져올 .html 파일을 하나 이상 선택하세요.", + "업로드가 64 MiB를 넘습니다. 사이트 가져오기는 이 크기까지만 받습니다. 완성된 사이트가 있는 폴더만 zip으로 묶고, 큰 동영상과 사용하지 않는 파일은 빼세요. 아무것도 가져오지 않았습니다.", + "아카이브의 압축을 풀면 128.0 MiB를 넘습니다. 사이트 가져오기는 이 크기까지만 받습니다. 큰 동영상과 사이트에서 사용하지 않는 파일을 빼고 다시 zip으로 묶으세요. 아무것도 가져오지 않았습니다.", + "선택한 파일을 합친 크기가 128.0 MiB를 넘습니다. 사이트 가져오기는 이 크기까지만 받습니다. 파일을 더 적게 선택하세요. 아무것도 가져오지 않았습니다.", + "아카이브의 파일 목록이 웹사이트에 필요한 것보다 훨씬 길어서 열지 않았습니다. 완성된 사이트가 있는 폴더만 node_modules 같은 종속성 폴더 없이 zip으로 묶은 다음 가져오세요. 아무것도 가져오지 않았습니다.", + "이 zip은 완성된 사이트가 아니라 프로젝트의 소스입니다. package.json이 있고 HTML 페이지가 없습니다. 먼저 빌드한 다음(보통 npm run build) 출력 폴더(대개 dist 또는 build)를 zip으로 묶어 가져오세요. 아무것도 가져오지 않았습니다.", + "한 번 실행 취소하면 섹션이 코드로 돌아오고, 두 번 하면 섹션이 제거됩니다.", + "시스템 및 종속성 폴더에 있는 파일 {0}개는 무시합니다.", + "시스템 또는 종속성 폴더에 있는 파일 1개는 무시합니다.", + "가져올 .html 파일을 하나 이상 선택하세요. 아무것도 가져오지 않았습니다.", + "사이트가 들어 있는 .zip 파일을 선택하세요. 아무것도 가져오지 않았습니다.", + "이 파일은 FormWeb이 읽을 수 있는 zip 아카이브가 아닙니다. 아무것도 가져오지 않았습니다.", + "아카이브가 암호로 보호되어 있습니다. 암호 없이 zip을 다시 만드세요. 아무것도 가져오지 않았습니다.", + "아카이브가 64.0 MiB를 넘습니다. 사이트 가져오기는 이 크기까지만 받습니다. 완성된 사이트가 있는 폴더만 zip으로 묶고, 큰 동영상과 사용하지 않는 파일은 빼세요. 아무것도 가져오지 않았습니다.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/nb.ts b/frontend/src/i18n/locales/nb.ts index 0f524254..5099d5e3 100644 --- a/frontend/src/i18n/locales/nb.ts +++ b/frontend/src/i18n/locales/nb.ts @@ -2899,4 +2899,45 @@ export default [ "1 side var for stor til å konverteres på én gang og forble en kodeseksjon: konverter den én del om gangen med Konverter til redigerbare elementer.", "{0} sider var for store til å konverteres på én gang og forble kodeseksjoner: konverter hver av dem én del om gangen med Konverter til redigerbare elementer.", "Sjekk den i telefonbredde i Forhåndsvisning, og juster den deretter under hvert brytningspunkt.", + "Importer HTML-filer", + "HTML-filer", + "Velg én eller flere .html-filer. Hver fil blir en ny side, eller én enkelt fil kan komme inn på denne siden som en seksjon.", + "Velg .html-filer", + "Et helt nettsted i en .zip", + "Lim inn HTML-kode", + "Lim inn HTML-en fra én side for å legge den til på denne siden som en seksjon. Stilene og hovedskriptet følger med, og skriptet kjører i forhåndsvisningen og på det publiserte nettstedet.", + "Lim inn HTML-en fra en side først.", + "Som nye sider", + "Som en seksjon på denne siden", + "Hent inn filene", + "Siden kommer inn på den åpne siden som én seksjon, etter den valgte seksjonen. Stilene og hovedskriptet følger med.", + "Velg én .zip-fil, eller én eller flere .html-filer.", + "Filene er til sammen større enn 64 MiB, som er det meste en import tar.", + "Leser filene", + "Ingen av filene er en HTML-side som kan importeres.", + "Hver fil blir en ny side på adressen gjennomgangen viser, eller én enkelt fil kommer inn på den åpne siden som en seksjon.", + "Velg andre filer", + "En seksjon tar én fil. Velg én enkelt fil for å legge den til på denne siden som en seksjon.", + "Importer sider", + "Sideskript", + "Kjører i forhåndsvisningen og på det publiserte nettstedet, ikke på dette lerretet.", + "Et sideskript har ingen boks på siden, så disse innstillingene gjelder ikke for det.", + "Vis konturer ved peking", + "Konturer ved peking er på: når du peker på et lag, får elementet en kontur på lerretet, og når du peker på et element, utheves laget.", + "Konturer ved peking er av.", + "Listen over filer som skal importeres, er ikke gyldig JSON. Ingenting ble importert.", + "Velg minst én .html-fil å importere.", + "Opplastingen er større enn 64 MiB, som er det meste en nettstedsimport tar. Zip bare mappen med det ferdige nettstedet, og utelat store videoer og filer det ikke bruker. Ingenting ble importert.", + "Arkivet blir større enn 128.0 MiB når det pakkes ut, som er det meste en nettstedsimport tar. Utelat store videoer og filer nettstedet ikke bruker, og zip det på nytt. Ingenting ble importert.", + "De valgte filene er til sammen større enn 128.0 MiB, som er det meste en nettstedsimport tar. Velg færre filer. Ingenting ble importert.", + "Fillisten i arkivet er langt lengre enn et nettsted trenger, så det ble ikke åpnet. Zip bare mappen med det ferdige nettstedet, uten avhengighetsmapper som node_modules, og importer den. Ingenting ble importert.", + "Denne zip-filen er kildekoden til et prosjekt, ikke et ferdig nettsted: den har package.json og ingen HTML-side. Bygg den først (vanligvis med npm run build), zip deretter utdatamappen (ofte dist eller build) og importer den. Ingenting ble importert.", + "Angre én gang for å få seksjonen tilbake som kode, to ganger for å fjerne den.", + "{0} filer i system- og avhengighetsmapper ignoreres.", + "1 fil i en system- eller avhengighetsmappe ignoreres.", + "Velg minst én .html-fil å importere. Ingenting ble importert.", + "Velg en .zip-fil som inneholder nettstedet. Ingenting ble importert.", + "Denne filen er ikke et zip-arkiv FormWeb kan lese. Ingenting ble importert.", + "Arkivet er passordbeskyttet. Lag zip-filen på nytt uten passord. Ingenting ble importert.", + "Arkivet er større enn 64.0 MiB, som er det meste en nettstedsimport tar. Zip bare mappen med det ferdige nettstedet, og utelat store videoer og filer det ikke bruker. Ingenting ble importert.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/nl.ts b/frontend/src/i18n/locales/nl.ts index f143e24d..23bd03e0 100644 --- a/frontend/src/i18n/locales/nl.ts +++ b/frontend/src/i18n/locales/nl.ts @@ -2899,4 +2899,45 @@ export default [ "1 pagina was te groot om in één keer om te zetten en bleef een codesectie: zet haar deel voor deel om met Omzetten naar bewerkbare elementen.", "{0} pagina's waren te groot om in één keer om te zetten en bleven codesecties: zet elke pagina deel voor deel om met Omzetten naar bewerkbare elementen.", "Controleer de pagina op telefoonbreedte in Voorbeeld en pas haar daarna per breekpunt aan.", + "HTML-bestanden importeren", + "HTML-bestanden", + "Kies een of meer .html-bestanden. Elk bestand wordt een nieuwe pagina, of één bestand kan als sectie in deze pagina komen.", + ".html-bestanden kiezen", + "Een hele site in een .zip", + "HTML-code plakken", + "Plak de HTML van één pagina om die als sectie aan deze pagina toe te voegen. De stijlen en het hoofdscript komen mee, en het script draait in het voorbeeld en op de gepubliceerde site.", + "Plak eerst de HTML van een pagina.", + "Als nieuwe pagina's", + "Als sectie van deze pagina", + "De bestanden binnenhalen", + "De pagina komt als één sectie in de geopende pagina, na de geselecteerde sectie. De stijlen en het hoofdscript komen mee.", + "Kies één .zip-bestand, of een of meer .html-bestanden.", + "De bestanden zijn samen groter dan 64 MiB, het maximum voor een import.", + "Bestanden lezen", + "Geen van de bestanden is een HTML-pagina die kan worden geïmporteerd.", + "Elk bestand wordt een nieuwe pagina op het adres dat de controle toont, of één bestand komt als sectie in de geopende pagina.", + "Andere bestanden kiezen", + "Een sectie neemt één bestand. Kies één bestand om het als sectie aan deze pagina toe te voegen.", + "Pagina's importeren", + "Paginascript", + "Werkt in het voorbeeld en op de gepubliceerde site, niet op dit canvas.", + "Een paginascript heeft geen vak op de pagina, dus deze instellingen gelden er niet voor.", + "Contouren bij aanwijzen tonen", + "Contouren bij aanwijzen staan aan: een laag aanwijzen geeft het element ervan een contour op het canvas, en een element aanwijzen markeert de laag ervan.", + "Contouren bij aanwijzen staan uit.", + "De lijst met te importeren bestanden is geen geldige JSON. Er is niets geïmporteerd.", + "Kies minstens één .html-bestand om te importeren.", + "De upload is groter dan 64 MiB, het maximum voor een site-import. Zip alleen de map met de afgewerkte site en laat grote video's en bestanden die ze niet gebruikt weg. Er is niets geïmporteerd.", + "Het archief wordt uitgepakt groter dan 128.0 MiB, het maximum voor een site-import. Laat grote video's en bestanden die de site niet gebruikt weg en zip het opnieuw. Er is niets geïmporteerd.", + "De gekozen bestanden zijn samen groter dan 128.0 MiB, het maximum voor een site-import. Kies minder bestanden. Er is niets geïmporteerd.", + "De bestandslijst van het archief is veel langer dan een website nodig heeft, dus het is niet geopend. Zip alleen de map met de afgewerkte site, zonder afhankelijkheidsmappen zoals node_modules, en importeer die. Er is niets geïmporteerd.", + "Deze zip is de broncode van een project, geen afgewerkte site: hij heeft package.json en geen HTML-pagina. Bouw hem eerst (meestal met npm run build), zip daarna de uitvoermap (vaak dist of build) en importeer die. Er is niets geïmporteerd.", + "Maak één keer ongedaan om de sectie terug te krijgen als code, twee keer om haar te verwijderen.", + "{0} bestanden in systeem- en afhankelijkheidsmappen worden genegeerd.", + "1 bestand in een systeem- of afhankelijkheidsmap wordt genegeerd.", + "Kies minstens één .html-bestand om te importeren. Er is niets geïmporteerd.", + "Kies een .zip-bestand dat de site bevat. Er is niets geïmporteerd.", + "Dit bestand is geen zip-archief dat FormWeb kan lezen. Er is niets geïmporteerd.", + "Het archief is met een wachtwoord beveiligd. Maak de zip opnieuw zonder wachtwoord. Er is niets geïmporteerd.", + "Het archief is groter dan 64.0 MiB, het maximum voor een site-import. Zip alleen de map met de afgewerkte site en laat grote video's en bestanden die ze niet gebruikt weg. Er is niets geïmporteerd.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/pl.ts b/frontend/src/i18n/locales/pl.ts index 8bdc330e..4f5e66fe 100644 --- a/frontend/src/i18n/locales/pl.ts +++ b/frontend/src/i18n/locales/pl.ts @@ -2899,4 +2899,45 @@ export default [ "1 strona była za duża, by zamienić ją naraz, i została sekcją kodu: zamieniaj ją po jednej części poleceniem Zamień na edytowalne elementy.", "Strony za duże, by zamienić je naraz: {0}; zostały sekcjami kodu: zamieniaj każdą po jednej części poleceniem Zamień na edytowalne elementy.", "Sprawdź ją przy szerokości telefonu w Podglądzie, a potem dostosuj w każdym punkcie przerwania.", + "Importuj pliki HTML", + "Pliki HTML", + "Wybierz jeden lub kilka plików .html. Każdy staje się nową stroną, a pojedynczy plik może trafić na tę stronę jako sekcja.", + "Wybierz pliki .html", + "Cała witryna w pliku .zip", + "Wklej kod HTML", + "Wklej HTML jednej strony, aby dodać go do tej strony jako sekcję. Jego style i główny skrypt przychodzą razem z nim, a skrypt działa w podglądzie i w opublikowanej witrynie.", + "Najpierw wklej HTML strony.", + "Jako nowe strony", + "Jako sekcja tej strony", + "Przenieś pliki", + "Strona trafia do otwartej strony jako jedna sekcja, po zaznaczonej sekcji. Jej style i główny skrypt przychodzą razem z nią.", + "Wybierz jeden plik .zip albo jeden lub więcej plików .html.", + "Pliki są razem większe niż 64 MiB, czyli limit importu.", + "Odczytywanie plików", + "Żaden z plików nie jest stroną HTML, którą można zaimportować.", + "Każdy plik staje się nową stroną pod adresem pokazanym w przeglądzie, a pojedynczy plik trafia do otwartej strony jako sekcja.", + "Wybierz inne pliki", + "Sekcja przyjmuje jeden plik. Wybierz pojedynczy plik, aby dodać go do tej strony jako sekcję.", + "Importuj strony", + "Skrypt strony", + "Działa w podglądzie i na opublikowanej witrynie, nie na tej kanwie.", + "Skrypt strony nie ma pola na stronie, więc te ustawienia go nie dotyczą.", + "Pokaż kontury po najechaniu", + "Kontury po najechaniu są włączone: wskazanie warstwy obrysowuje jej element na kanwie, a wskazanie elementu wyróżnia jego warstwę.", + "Kontury po najechaniu są wyłączone.", + "Lista plików do zaimportowania nie jest poprawnym JSON-em. Nic nie zostało zaimportowane.", + "Wybierz co najmniej jeden plik .html do zaimportowania.", + "Przesyłane dane są większe niż 64 MiB, czyli limit importu witryny. Spakuj do zip tylko folder z gotową witryną, bez dużych filmów i plików, których ona nie używa. Nic nie zostało zaimportowane.", + "Po rozpakowaniu archiwum ma ponad 128.0 MiB, czyli limit importu witryny. Pomiń duże filmy i pliki, których witryna nie używa, i spakuj je ponownie do zip. Nic nie zostało zaimportowane.", + "Wybrane pliki mają razem ponad 128.0 MiB, czyli limit importu witryny. Wybierz mniej plików. Nic nie zostało zaimportowane.", + "Lista plików w archiwum jest znacznie dłuższa, niż potrzebuje witryna, więc nie zostało ono otwarte. Spakuj do zip tylko folder z gotową witryną, bez folderów zależności takich jak node_modules, i zaimportuj go. Nic nie zostało zaimportowane.", + "Ten zip to kod źródłowy projektu, a nie gotowa witryna: ma package.json i żadnej strony HTML. Najpierw go zbuduj (zwykle npm run build), potem spakuj do zip folder wynikowy (często dist lub build) i zaimportuj go. Nic nie zostało zaimportowane.", + "Cofnij raz, aby odzyskać sekcję jako kod, dwa razy, aby ją usunąć.", + "Zignorowane pliki w folderach systemowych i folderach zależności: {0}.", + "1 plik w folderze systemowym lub folderze zależności zostanie zignorowany.", + "Wybierz co najmniej jeden plik .html do zaimportowania. Nic nie zostało zaimportowane.", + "Wybierz plik .zip zawierający witrynę. Nic nie zostało zaimportowane.", + "Ten plik nie jest archiwum zip, które FormWeb potrafi odczytać. Nic nie zostało zaimportowane.", + "Archiwum jest chronione hasłem. Utwórz zip ponownie bez hasła. Nic nie zostało zaimportowane.", + "Archiwum jest większe niż 64.0 MiB, czyli limit importu witryny. Spakuj do zip tylko folder z gotową witryną, bez dużych filmów i plików, których ona nie używa. Nic nie zostało zaimportowane.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/pt-BR.ts b/frontend/src/i18n/locales/pt-BR.ts index 4face6f4..34bdc8ce 100644 --- a/frontend/src/i18n/locales/pt-BR.ts +++ b/frontend/src/i18n/locales/pt-BR.ts @@ -2899,4 +2899,45 @@ export default [ "1 página era grande demais para converter de uma vez e ficou como seção de código: converta-a parte por parte com Converter em elementos editáveis.", "{0} páginas eram grandes demais para converter de uma vez e ficaram como seções de código: converta cada uma parte por parte com Converter em elementos editáveis.", "Confira-a na largura de um celular em Visualizar e depois ajuste em cada ponto de interrupção.", + "Importar arquivos HTML", + "Arquivos HTML", + "Escolha um ou vários arquivos .html. Cada um vira uma página nova, ou um único arquivo pode entrar nesta página como seção.", + "Escolher arquivos .html", + "Um site inteiro em um .zip", + "Colar código HTML", + "Cole o HTML de uma página para adicioná-lo a esta página como seção. Os estilos e o script principal vêm junto, e o script roda na visualização e no site publicado.", + "Cole primeiro o HTML de uma página.", + "Como páginas novas", + "Como seção desta página", + "Trazer os arquivos", + "A página entra na página aberta como uma seção, depois da seção selecionada. Os estilos e o script principal vêm junto.", + "Escolha um arquivo .zip, ou um ou mais arquivos .html.", + "Os arquivos somam mais de 64 MiB, o máximo que uma importação aceita.", + "Lendo os arquivos", + "Nenhum dos arquivos é uma página HTML que possa ser importada.", + "Cada arquivo vira uma página nova no endereço mostrado na revisão, ou um único arquivo entra na página aberta como seção.", + "Escolher outros arquivos", + "Uma seção aceita um só arquivo. Escolha um único arquivo para adicioná-lo a esta página como seção.", + "Importar páginas", + "Script da página", + "Roda na visualização e no site publicado, não nesta tela.", + "Um script da página não tem caixa na página, então estas configurações não se aplicam a ele.", + "Mostrar contornos ao passar o ponteiro", + "Os contornos ao passar o ponteiro estão ativados: apontar para uma camada contorna o elemento dela na tela, e apontar para um elemento destaca a camada dele.", + "Os contornos ao passar o ponteiro estão desativados.", + "A lista de arquivos a importar não é um JSON válido. Nada foi importado.", + "Escolha pelo menos um arquivo .html para importar.", + "O envio tem mais de 64 MiB, o máximo que uma importação de site aceita. Compacte em zip só a pasta que contém o site pronto, deixando de fora vídeos grandes e arquivos que ele não usa. Nada foi importado.", + "O arquivo compactado ocupa mais de 128.0 MiB descompactado, o máximo que uma importação de site aceita. Deixe de fora vídeos grandes e arquivos que o site não usa e compacte em zip de novo. Nada foi importado.", + "Os arquivos escolhidos somam mais de 128.0 MiB, o máximo que uma importação de site aceita. Escolha menos arquivos. Nada foi importado.", + "A lista de arquivos do arquivo compactado é muito mais longa do que um site precisa, então ele não foi aberto. Compacte em zip só a pasta que contém o site pronto, sem pastas de dependências como node_modules, e importe essa. Nada foi importado.", + "Este zip é o código-fonte de um projeto, não um site pronto: ele tem package.json e nenhuma página HTML. Faça o build primeiro (normalmente npm run build), depois compacte em zip a pasta de saída (geralmente dist ou build) e importe essa. Nada foi importado.", + "Desfaça uma vez para ter a seção de volta como código, duas vezes para removê-la.", + "{0} arquivos em pastas de sistema e de dependências são ignorados.", + "1 arquivo em uma pasta de sistema ou de dependências é ignorado.", + "Escolha pelo menos um arquivo .html para importar. Nada foi importado.", + "Escolha um arquivo .zip que contenha o site. Nada foi importado.", + "Este arquivo não é um arquivo zip que o FormWeb consiga ler. Nada foi importado.", + "O arquivo compactado está protegido por senha. Crie o zip de novo sem senha. Nada foi importado.", + "O arquivo compactado tem mais de 64.0 MiB, o máximo que uma importação de site aceita. Compacte em zip só a pasta que contém o site pronto, deixando de fora vídeos grandes e arquivos que ele não usa. Nada foi importado.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ru.ts b/frontend/src/i18n/locales/ru.ts index faba61ee..94d110aa 100644 --- a/frontend/src/i18n/locales/ru.ts +++ b/frontend/src/i18n/locales/ru.ts @@ -2899,4 +2899,45 @@ export default [ "Страница оказалась слишком большой для преобразования за раз и осталась разделом кода: преобразуйте её по частям командой Преобразовать в редактируемые элементы.", "Страниц, слишком больших для преобразования за раз: {0}; они остались разделами кода: преобразуйте каждую по частям командой Преобразовать в редактируемые элементы.", "Проверьте её на ширине телефона в Просмотре, затем настройте на каждом брейкпоинте.", + "Импорт HTML-файлов", + "HTML-файлы", + "Выберите один или несколько файлов .html. Каждый станет новой страницей, а один файл можно добавить на эту страницу как раздел.", + "Выбрать файлы .html", + "Весь сайт в .zip", + "Вставить HTML-код", + "Вставьте HTML одной страницы, чтобы добавить его на эту страницу как раздел. Стили и основной скрипт переносятся вместе с ним, а скрипт работает в предпросмотре и на опубликованном сайте.", + "Сначала вставьте HTML страницы.", + "Как новые страницы", + "Как раздел этой страницы", + "Перенести файлы", + "Страница попадает в открытую страницу одним разделом, после выбранного раздела. Её стили и основной скрипт переносятся вместе с ней.", + "Выберите один файл .zip или один или несколько файлов .html.", + "Файлы вместе больше 64 MiB, это предел для импорта.", + "Чтение файлов", + "Ни один из файлов не является HTML-страницей, которую можно импортировать.", + "Каждый файл станет новой страницей по адресу, показанному при проверке, или один файл попадёт в открытую страницу как раздел.", + "Выбрать другие файлы", + "В раздел помещается один файл. Выберите один файл, чтобы добавить его на эту страницу как раздел.", + "Импортировать страницы", + "Скрипт страницы", + "Работает в предпросмотре и на опубликованном сайте, но не на этом холсте.", + "У скрипта страницы нет блока на странице, поэтому эти настройки к нему не применяются.", + "Показывать контуры при наведении", + "Контуры при наведении включены: при наведении на слой его элемент обводится на холсте, а при наведении на элемент подсвечивается его слой.", + "Контуры при наведении выключены.", + "Список файлов для импорта не является корректным JSON. Ничего не импортировано.", + "Выберите хотя бы один файл .html для импорта.", + "Загрузка больше 64 MiB, это предел для импорта сайта. Упакуйте в zip только папку с готовым сайтом, без больших видео и файлов, которые он не использует. Ничего не импортировано.", + "В распакованном виде архив больше 128.0 MiB, это предел для импорта сайта. Уберите большие видео и файлы, которые сайт не использует, и снова упакуйте его в zip. Ничего не импортировано.", + "Выбранные файлы вместе больше 128.0 MiB, это предел для импорта сайта. Выберите меньше файлов. Ничего не импортировано.", + "Список файлов в архиве намного длиннее, чем нужно веб-сайту, поэтому архив не открыт. Упакуйте в zip только папку с готовым сайтом, без папок зависимостей вроде node_modules, и импортируйте её. Ничего не импортировано.", + "Этот zip содержит исходный код проекта, а не готовый сайт: в нём есть package.json и нет ни одной HTML-страницы. Сначала соберите его (обычно npm run build), затем упакуйте в zip папку сборки (часто dist или build) и импортируйте её. Ничего не импортировано.", + "Отмените один раз, чтобы вернуть раздел как код, дважды, чтобы удалить его.", + "Файлы в системных папках и папках зависимостей будут проигнорированы: {0}.", + "1 файл в системной папке или папке зависимостей будет проигнорирован.", + "Выберите хотя бы один файл .html для импорта. Ничего не импортировано.", + "Выберите файл .zip, в котором находится сайт. Ничего не импортировано.", + "Этот файл не является zip-архивом, который FormWeb может прочитать. Ничего не импортировано.", + "Архив защищён паролем. Создайте zip заново без пароля. Ничего не импортировано.", + "Архив больше 64.0 MiB, это предел для импорта сайта. Упакуйте в zip только папку с готовым сайтом, без больших видео и файлов, которые он не использует. Ничего не импортировано.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/sv.ts b/frontend/src/i18n/locales/sv.ts index b1904bce..b7ec3508 100644 --- a/frontend/src/i18n/locales/sv.ts +++ b/frontend/src/i18n/locales/sv.ts @@ -2899,4 +2899,45 @@ export default [ "1 sida var för stor för att konverteras på en gång och förblev en kodsektion: konvertera den en del i taget med Konvertera till redigerbara element.", "{0} sidor var för stora för att konverteras på en gång och förblev kodsektioner: konvertera var och en en del i taget med Konvertera till redigerbara element.", "Kontrollera den i telefonbredd i Förhandsgranska och justera den sedan under varje brytpunkt.", + "Importera HTML-filer", + "HTML-filer", + "Välj en eller flera .html-filer. Varje fil blir en ny sida, eller så kan en enda fil komma in på den här sidan som ett avsnitt.", + "Välj .html-filer", + "En hel webbplats i en .zip", + "Klistra in HTML-kod", + "Klistra in HTML-koden för en sida för att lägga till den på den här sidan som ett avsnitt. Dess stilar och huvudskript följer med, och skriptet körs i förhandsgranskningen och på den publicerade webbplatsen.", + "Klistra först in HTML-koden för en sida.", + "Som nya sidor", + "Som ett avsnitt på den här sidan", + "Hämta in filerna", + "Sidan kommer in på den öppna sidan som ett avsnitt, efter det markerade avsnittet. Dess stilar och huvudskript följer med.", + "Välj en .zip-fil, eller en eller flera .html-filer.", + "Filerna är tillsammans större än 64 MiB, det mesta en import tar emot.", + "Läser filerna", + "Ingen av filerna är en HTML-sida som kan importeras.", + "Varje fil blir en ny sida på adressen som granskningen visar, eller så kommer en enda fil in på den öppna sidan som ett avsnitt.", + "Välj andra filer", + "Ett avsnitt tar en fil. Välj en enda fil för att lägga till den på den här sidan som ett avsnitt.", + "Importera sidor", + "Sidskript", + "Körs i förhandsgranskningen och på den publicerade webbplatsen, inte på den här arbetsytan.", + "Ett sidskript har ingen ruta på sidan, så de här inställningarna gäller inte för det.", + "Visa konturer vid pekning", + "Konturer vid pekning är på: när du pekar på ett lager får dess element en kontur på arbetsytan, och när du pekar på ett element markeras dess lager.", + "Konturer vid pekning är av.", + "Listan över filer att importera är inte giltig JSON. Inget importerades.", + "Välj minst en .html-fil att importera.", + "Uppladdningen är större än 64 MiB, det mesta en webbplatsimport tar emot. Zippa bara mappen med den färdiga webbplatsen och utelämna stora videor och filer den inte använder. Inget importerades.", + "Arkivet blir större än 128.0 MiB uppackat, det mesta en webbplatsimport tar emot. Utelämna stora videor och filer som webbplatsen inte använder och zippa det igen. Inget importerades.", + "De valda filerna är tillsammans större än 128.0 MiB, det mesta en webbplatsimport tar emot. Välj färre filer. Inget importerades.", + "Arkivets fillista är mycket längre än en webbplats behöver, så det öppnades inte. Zippa bara mappen med den färdiga webbplatsen, utan beroendemappar som node_modules, och importera den. Inget importerades.", + "Den här zip-filen är ett projekts källkod, inte en färdig webbplats: den har package.json och ingen HTML-sida. Bygg den först (oftast med npm run build), zippa sedan utdatamappen (ofta dist eller build) och importera den. Inget importerades.", + "Ångra en gång för att få tillbaka avsnittet som kod, två gånger för att ta bort det.", + "{0} filer i system- och beroendemappar ignoreras.", + "1 fil i en system- eller beroendemapp ignoreras.", + "Välj minst en .html-fil att importera. Inget importerades.", + "Välj en .zip-fil som innehåller webbplatsen. Inget importerades.", + "Den här filen är inte ett zip-arkiv som FormWeb kan läsa. Inget importerades.", + "Arkivet är lösenordsskyddat. Skapa zip-filen igen utan lösenord. Inget importerades.", + "Arkivet är större än 64.0 MiB, det mesta en webbplatsimport tar emot. Zippa bara mappen med den färdiga webbplatsen och utelämna stora videor och filer den inte använder. Inget importerades.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/th.ts b/frontend/src/i18n/locales/th.ts index b69f8353..a8b0d369 100644 --- a/frontend/src/i18n/locales/th.ts +++ b/frontend/src/i18n/locales/th.ts @@ -2899,4 +2899,45 @@ export default [ "1 หน้าใหญ่เกินกว่าจะแปลงในครั้งเดียวและยังเป็นส่วนโค้ด: แปลงทีละส่วนด้วย แปลงเป็นองค์ประกอบที่แก้ไขได้", "{0} หน้าใหญ่เกินกว่าจะแปลงในครั้งเดียวและยังเป็นส่วนโค้ด: แปลงแต่ละหน้าทีละส่วนด้วย แปลงเป็นองค์ประกอบที่แก้ไขได้", "ตรวจสอบที่ความกว้างโทรศัพท์ในดูตัวอย่าง แล้วปรับในแต่ละเบรกพอยต์", + "นำเข้าไฟล์ HTML", + "ไฟล์ HTML", + "เลือกไฟล์ .html หนึ่งไฟล์หรือหลายไฟล์ แต่ละไฟล์จะกลายเป็นหน้าใหม่ หรือไฟล์เดียวสามารถเข้ามาในหน้านี้เป็นส่วนได้", + "เลือกไฟล์ .html", + "ทั้งไซต์ในไฟล์ .zip", + "วางโค้ด HTML", + "วาง HTML ของหนึ่งหน้าเพื่อเพิ่มลงในหน้านี้เป็นส่วน สไตล์และสคริปต์หลักจะมาด้วย และสคริปต์จะทำงานในตัวอย่างและบนไซต์ที่เผยแพร่", + "วาง HTML ของหน้าก่อน", + "เป็นหน้าใหม่", + "เป็นส่วนของหน้านี้", + "วิธีนำไฟล์เข้ามา", + "หน้านั้นจะเข้ามาในหน้าที่เปิดอยู่เป็นหนึ่งส่วน ต่อจากส่วนที่เลือก สไตล์และสคริปต์หลักจะมาด้วย", + "เลือกไฟล์ .zip หนึ่งไฟล์ หรือไฟล์ .html หนึ่งไฟล์ขึ้นไป", + "ไฟล์รวมกันใหญ่กว่า 64 MiB ซึ่งเป็นขนาดสูงสุดที่การนำเข้ารับได้", + "กำลังอ่านไฟล์", + "ไม่มีไฟล์ใดเป็นหน้า HTML ที่นำเข้าได้", + "แต่ละไฟล์จะกลายเป็นหน้าใหม่ที่ที่อยู่ซึ่งแสดงในการตรวจทาน หรือไฟล์เดียวจะเข้ามาในหน้าที่เปิดอยู่เป็นส่วน", + "เลือกไฟล์อื่น", + "หนึ่งส่วนรับได้หนึ่งไฟล์ เลือกไฟล์เดียวเพื่อเพิ่มลงในหน้านี้เป็นส่วน", + "นำเข้าหน้า", + "สคริปต์ของหน้า", + "ทำงานในตัวอย่างและบนไซต์ที่เผยแพร่ ไม่ทำงานบนแคนวาสนี้", + "สคริปต์ของหน้าไม่มีกล่องบนหน้า การตั้งค่าเหล่านี้จึงใช้กับมันไม่ได้", + "แสดงเส้นขอบเมื่อชี้", + "เปิดเส้นขอบเมื่อชี้อยู่: การชี้ที่เลเยอร์จะแสดงเส้นขอบองค์ประกอบของเลเยอร์นั้นบนแคนวาส และการชี้ที่องค์ประกอบจะเน้นเลเยอร์ของมัน", + "ปิดเส้นขอบเมื่อชี้แล้ว", + "รายการไฟล์ที่จะนำเข้าไม่ใช่ JSON ที่ถูกต้อง ไม่มีสิ่งใดถูกนำเข้า", + "เลือกไฟล์ .html อย่างน้อยหนึ่งไฟล์เพื่อนำเข้า", + "ข้อมูลที่อัปโหลดใหญ่กว่า 64 MiB ซึ่งเป็นขนาดสูงสุดที่การนำเข้าไซต์รับได้ บีบอัดเป็น zip เฉพาะโฟลเดอร์ที่มีไซต์ที่เสร็จแล้ว โดยไม่รวมวิดีโอขนาดใหญ่และไฟล์ที่ไซต์ไม่ได้ใช้ ไม่มีสิ่งใดถูกนำเข้า", + "ไฟล์เก็บถาวรเมื่อแตกไฟล์แล้วใหญ่กว่า 128.0 MiB ซึ่งเป็นขนาดสูงสุดที่การนำเข้าไซต์รับได้ ตัดวิดีโอขนาดใหญ่และไฟล์ที่ไซต์ไม่ได้ใช้ออก แล้วบีบอัดเป็น zip ใหม่ ไม่มีสิ่งใดถูกนำเข้า", + "ไฟล์ที่เลือกรวมกันใหญ่กว่า 128.0 MiB ซึ่งเป็นขนาดสูงสุดที่การนำเข้าไซต์รับได้ เลือกไฟล์ให้น้อยลง ไม่มีสิ่งใดถูกนำเข้า", + "รายการไฟล์ในไฟล์เก็บถาวรยาวกว่าที่เว็บไซต์ต้องใช้มาก จึงไม่ได้เปิด บีบอัดเป็น zip เฉพาะโฟลเดอร์ที่มีไซต์ที่เสร็จแล้ว โดยไม่รวมโฟลเดอร์ dependency เช่น node_modules แล้วนำเข้าไฟล์นั้น ไม่มีสิ่งใดถูกนำเข้า", + "zip นี้เป็นซอร์สโค้ดของโปรเจกต์ ไม่ใช่ไซต์ที่เสร็จแล้ว: มี package.json แต่ไม่มีหน้า HTML ให้ build ก่อน (โดยปกติคือ npm run build) แล้วบีบอัดโฟลเดอร์ผลลัพธ์ (มักเป็น dist หรือ build) เป็น zip และนำเข้าไฟล์นั้น ไม่มีสิ่งใดถูกนำเข้า", + "เลิกทำหนึ่งครั้งเพื่อให้ส่วนกลับเป็นโค้ด สองครั้งเพื่อลบส่วนออก", + "ละเว้นไฟล์ในโฟลเดอร์ระบบและโฟลเดอร์ dependency {0} ไฟล์", + "ละเว้นไฟล์ในโฟลเดอร์ระบบหรือโฟลเดอร์ dependency 1 ไฟล์", + "เลือกไฟล์ .html อย่างน้อยหนึ่งไฟล์เพื่อนำเข้า ไม่มีสิ่งใดถูกนำเข้า", + "เลือกไฟล์ .zip ที่มีไซต์อยู่ ไม่มีสิ่งใดถูกนำเข้า", + "ไฟล์นี้ไม่ใช่ไฟล์เก็บถาวร zip ที่ FormWeb อ่านได้ ไม่มีสิ่งใดถูกนำเข้า", + "ไฟล์เก็บถาวรมีการป้องกันด้วยรหัสผ่าน สร้าง zip ใหม่โดยไม่ใส่รหัสผ่าน ไม่มีสิ่งใดถูกนำเข้า", + "ไฟล์เก็บถาวรใหญ่กว่า 64.0 MiB ซึ่งเป็นขนาดสูงสุดที่การนำเข้าไซต์รับได้ บีบอัดเป็น zip เฉพาะโฟลเดอร์ที่มีไซต์ที่เสร็จแล้ว โดยไม่รวมวิดีโอขนาดใหญ่และไฟล์ที่ไซต์ไม่ได้ใช้ ไม่มีสิ่งใดถูกนำเข้า", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/tr.ts b/frontend/src/i18n/locales/tr.ts index 78f545f6..ead956fe 100644 --- a/frontend/src/i18n/locales/tr.ts +++ b/frontend/src/i18n/locales/tr.ts @@ -2899,4 +2899,45 @@ export default [ "1 sayfa tek seferde dönüştürülemeyecek kadar büyüktü ve kod bölümü olarak kaldı: Düzenlenebilir öğelere dönüştür ile parça parça dönüştür.", "{0} sayfa tek seferde dönüştürülemeyecek kadar büyüktü ve kod bölümü olarak kaldı: her birini Düzenlenebilir öğelere dönüştür ile parça parça dönüştür.", "Önizleme'de telefon genişliğinde kontrol edin, ardından her kesme noktasında ayarlayın.", + "HTML dosyalarını içe aktar", + "HTML dosyaları", + "Bir veya birkaç .html dosyası seçin. Her biri yeni bir sayfa olur ya da tek bir dosya bu sayfaya bölüm olarak girebilir.", + ".html dosyalarını seç", + "Bir .zip içinde bütün bir site", + "HTML kodu yapıştır", + "Bir sayfanın HTML'sini bu sayfaya bölüm olarak eklemek için yapıştırın. Stilleri ve ana betiği de gelir, betik önizlemede ve yayımlanan sitede çalışır.", + "Önce bir sayfanın HTML'sini yapıştırın.", + "Yeni sayfalar olarak", + "Bu sayfanın bir bölümü olarak", + "Dosyaları getir", + "Sayfa, açık sayfaya seçili bölümden sonra tek bir bölüm olarak girer. Stilleri ve ana betiği de gelir.", + "Bir .zip dosyası ya da bir veya daha fazla .html dosyası seçin.", + "Dosyalar toplamda 64 MiB'tan büyük; bir içe aktarma en fazla bu kadarını alır.", + "Dosyalar okunuyor", + "Dosyaların hiçbiri içe aktarılabilecek bir HTML sayfası değil.", + "Her dosya, incelemede gösterilen adreste yeni bir sayfa olur ya da tek bir dosya açık sayfaya bölüm olarak girer.", + "Başka dosyalar seç", + "Bir bölüm tek dosya alır. Bu sayfaya bölüm olarak eklemek için tek bir dosya seçin.", + "Sayfaları içe aktar", + "Sayfa betiği", + "Önizlemede ve yayımlanan sitede çalışır, bu tuvalde çalışmaz.", + "Sayfa betiğinin sayfada bir kutusu yoktur, bu yüzden bu ayarlar ona uygulanmaz.", + "Üzerine gelince ana hatları göster", + "Üzerine gelince ana hatlar açık: bir katmanın üzerine gelmek öğesini tuvalde çerçeveler, bir öğenin üzerine gelmek de katmanını vurgular.", + "Üzerine gelince ana hatlar kapalı.", + "İçe aktarılacak dosyaların listesi geçerli bir JSON değil. Hiçbir şey içe aktarılmadı.", + "İçe aktarmak için en az bir .html dosyası seçin.", + "Yükleme 64 MiB'tan büyük; bir site içe aktarması en fazla bu kadarını alır. Yalnızca bitmiş siteyi içeren klasörü, büyük videoları ve kullanmadığı dosyaları dışarıda bırakarak zip'leyin. Hiçbir şey içe aktarılmadı.", + "Arşiv açıldığında 128.0 MiB'tan büyük oluyor; bir site içe aktarması en fazla bu kadarını alır. Büyük videoları ve sitenin kullanmadığı dosyaları dışarıda bırakıp yeniden zip'leyin. Hiçbir şey içe aktarılmadı.", + "Seçilen dosyalar toplamda 128.0 MiB'tan büyük; bir site içe aktarması en fazla bu kadarını alır. Daha az dosya seçin. Hiçbir şey içe aktarılmadı.", + "Arşivin dosya listesi bir web sitesinin ihtiyacından çok daha uzun, bu yüzden açılmadı. Yalnızca bitmiş siteyi içeren klasörü, node_modules gibi bağımlılık klasörleri olmadan zip'leyin ve onu içe aktarın. Hiçbir şey içe aktarılmadı.", + "Bu zip bir projenin kaynak kodu, bitmiş bir site değil: içinde package.json var ve hiç HTML sayfası yok. Önce derleyin (genellikle npm run build), sonra çıktı klasörünü (çoğunlukla dist veya build) zip'leyip içe aktarın. Hiçbir şey içe aktarılmadı.", + "Bölümü kod olarak geri almak için bir kez, kaldırmak için iki kez geri al.", + "Sistem ve bağımlılık klasörlerindeki {0} dosya yok sayılıyor.", + "Bir sistem veya bağımlılık klasöründeki 1 dosya yok sayılıyor.", + "İçe aktarmak için en az bir .html dosyası seçin. Hiçbir şey içe aktarılmadı.", + "Siteyi içeren bir .zip dosyası seçin. Hiçbir şey içe aktarılmadı.", + "Bu dosya, FormWeb'in okuyabildiği bir zip arşivi değil. Hiçbir şey içe aktarılmadı.", + "Arşiv parola korumalı. Zip'i parolasız olarak yeniden oluşturun. Hiçbir şey içe aktarılmadı.", + "Arşiv 64.0 MiB'tan büyük; bir site içe aktarması en fazla bu kadarını alır. Yalnızca bitmiş siteyi içeren klasörü, büyük videoları ve kullanmadığı dosyaları dışarıda bırakarak zip'leyin. Hiçbir şey içe aktarılmadı.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/uk.ts b/frontend/src/i18n/locales/uk.ts index b4bbb9c1..04c1af98 100644 --- a/frontend/src/i18n/locales/uk.ts +++ b/frontend/src/i18n/locales/uk.ts @@ -2899,4 +2899,45 @@ export default [ "Сторінка була завелика, щоб перетворити її за раз, і лишилася розділом коду: перетворюйте її частинами командою Перетворити на редаговані елементи.", "Сторінок, завеликих для перетворення за раз: {0}; вони лишилися розділами коду: перетворюйте кожну частинами командою Перетворити на редаговані елементи.", "Перевірте її на ширині телефона в Перегляді, потім налаштуйте на кожному брейкпоінті.", + "Імпорт HTML-файлів", + "HTML-файли", + "Виберіть один або кілька файлів .html. Кожен стане новою сторінкою, а один файл можна додати на цю сторінку як розділ.", + "Вибрати файли .html", + "Увесь сайт у .zip", + "Вставити HTML-код", + "Вставте HTML однієї сторінки, щоб додати його на цю сторінку як розділ. Стилі та основний скрипт переносяться разом із ним, а скрипт працює в попередньому перегляді та на опублікованому сайті.", + "Спершу вставте HTML сторінки.", + "Як нові сторінки", + "Як розділ цієї сторінки", + "Перенести файли", + "Сторінка потрапляє у відкриту сторінку одним розділом, після вибраного розділу. Її стилі та основний скрипт переносяться разом із нею.", + "Виберіть один файл .zip або один чи кілька файлів .html.", + "Файли разом більші за 64 MiB, це межа для імпорту.", + "Читання файлів", + "Жоден із файлів не є HTML-сторінкою, яку можна імпортувати.", + "Кожен файл стане новою сторінкою за адресою, показаною під час перевірки, або один файл потрапить у відкриту сторінку як розділ.", + "Вибрати інші файли", + "У розділ поміщається один файл. Виберіть один файл, щоб додати його на цю сторінку як розділ.", + "Імпортувати сторінки", + "Скрипт сторінки", + "Працює в попередньому перегляді та на опублікованому сайті, але не на цьому полотні.", + "Скрипт сторінки не має блоку на сторінці, тому ці налаштування до нього не застосовуються.", + "Показувати контури під час наведення", + "Контури під час наведення увімкнено: наведення на шар обводить його елемент на полотні, а наведення на елемент підсвічує його шар.", + "Контури під час наведення вимкнено.", + "Список файлів для імпорту не є коректним JSON. Нічого не імпортовано.", + "Виберіть хоча б один файл .html для імпорту.", + "Завантаження більше за 64 MiB, це межа для імпорту сайту. Запакуйте в zip лише папку з готовим сайтом, без великих відео та файлів, які він не використовує. Нічого не імпортовано.", + "У розпакованому вигляді архів більший за 128.0 MiB, це межа для імпорту сайту. Приберіть великі відео та файли, які сайт не використовує, і знову запакуйте його в zip. Нічого не імпортовано.", + "Вибрані файли разом більші за 128.0 MiB, це межа для імпорту сайту. Виберіть менше файлів. Нічого не імпортовано.", + "Список файлів в архіві значно довший, ніж потрібно вебсайту, тому архів не відкрито. Запакуйте в zip лише папку з готовим сайтом, без папок залежностей на кшталт node_modules, і імпортуйте її. Нічого не імпортовано.", + "Цей zip містить вихідний код проєкту, а не готовий сайт: у ньому є package.json і немає жодної HTML-сторінки. Спершу зберіть його (зазвичай npm run build), потім запакуйте в zip папку збірки (часто dist або build) та імпортуйте її. Нічого не імпортовано.", + "Скасуйте один раз, щоб повернути розділ як код, двічі, щоб вилучити його.", + "Файли в системних папках і папках залежностей буде проігноровано: {0}.", + "1 файл у системній папці або папці залежностей буде проігноровано.", + "Виберіть хоча б один файл .html для імпорту. Нічого не імпортовано.", + "Виберіть файл .zip, у якому міститься сайт. Нічого не імпортовано.", + "Цей файл не є zip-архівом, який FormWeb може прочитати. Нічого не імпортовано.", + "Архів захищено паролем. Створіть zip заново без пароля. Нічого не імпортовано.", + "Архів більший за 64.0 MiB, це межа для імпорту сайту. Запакуйте в zip лише папку з готовим сайтом, без великих відео та файлів, які він не використовує. Нічого не імпортовано.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/vi.ts b/frontend/src/i18n/locales/vi.ts index b95e6167..146442a5 100644 --- a/frontend/src/i18n/locales/vi.ts +++ b/frontend/src/i18n/locales/vi.ts @@ -2899,4 +2899,45 @@ export default [ "1 trang quá lớn để chuyển một lần và vẫn là phần mã: hãy chuyển từng phần một bằng Chuyển thành phần tử chỉnh sửa được.", "{0} trang quá lớn để chuyển một lần và vẫn là phần mã: hãy chuyển từng trang theo từng phần bằng Chuyển thành phần tử chỉnh sửa được.", "Hãy kiểm tra ở chiều rộng điện thoại trong Xem trước, rồi điều chỉnh ở từng điểm ngắt.", + "Nhập tệp HTML", + "Tệp HTML", + "Chọn một hoặc nhiều tệp .html. Mỗi tệp trở thành một trang mới, hoặc một tệp duy nhất có thể vào trang này dưới dạng một phần.", + "Chọn tệp .html", + "Toàn bộ trang web trong một tệp .zip", + "Dán mã HTML", + "Dán HTML của một trang để thêm vào trang này dưới dạng một phần. Kiểu và tập lệnh chính đi kèm, và tập lệnh chạy trong Xem trước và trên trang web đã xuất bản.", + "Hãy dán HTML của một trang trước.", + "Dưới dạng trang mới", + "Dưới dạng một phần của trang này", + "Đưa các tệp vào", + "Trang được đưa vào trang đang mở dưới dạng một phần, sau phần đã chọn. Kiểu và tập lệnh chính đi kèm.", + "Hãy chọn một tệp .zip, hoặc một hay nhiều tệp .html.", + "Tổng dung lượng các tệp lớn hơn 64 MiB, mức tối đa một lần nhập nhận.", + "Đang đọc các tệp", + "Không tệp nào là trang HTML có thể nhập.", + "Mỗi tệp trở thành một trang mới ở địa chỉ hiển thị khi xem lại, hoặc một tệp duy nhất vào trang đang mở dưới dạng một phần.", + "Chọn tệp khác", + "Một phần chỉ nhận một tệp. Hãy chọn một tệp duy nhất để thêm vào trang này dưới dạng một phần.", + "Nhập các trang", + "Tập lệnh trang", + "Chạy trong Xem trước và trên trang web đã xuất bản, không chạy trên canvas này.", + "Tập lệnh trang không có hộp trên trang, nên các cài đặt này không áp dụng cho nó.", + "Hiện đường viền khi trỏ", + "Đường viền khi trỏ đang bật: trỏ vào một lớp sẽ viền phần tử của lớp đó trên canvas, và trỏ vào một phần tử sẽ làm nổi bật lớp của nó.", + "Đường viền khi trỏ đang tắt.", + "Danh sách tệp cần nhập không phải JSON hợp lệ. Không có gì được nhập.", + "Hãy chọn ít nhất một tệp .html để nhập.", + "Dữ liệu tải lên lớn hơn 64 MiB, mức tối đa một lần nhập trang web nhận. Chỉ nén zip thư mục chứa trang web đã hoàn chỉnh, bỏ ra các video lớn và tệp nó không dùng. Không có gì được nhập.", + "Tệp lưu trữ khi giải nén lớn hơn 128.0 MiB, mức tối đa một lần nhập trang web nhận. Bỏ ra các video lớn và tệp trang web không dùng, rồi nén zip lại. Không có gì được nhập.", + "Tổng dung lượng các tệp đã chọn lớn hơn 128.0 MiB, mức tối đa một lần nhập trang web nhận. Hãy chọn ít tệp hơn. Không có gì được nhập.", + "Danh sách tệp của tệp lưu trữ dài hơn nhiều so với mức một trang web cần, nên nó không được mở. Chỉ nén zip thư mục chứa trang web đã hoàn chỉnh, không kèm các thư mục phụ thuộc như node_modules, rồi nhập thư mục đó. Không có gì được nhập.", + "Tệp zip này là mã nguồn của một dự án, không phải trang web đã hoàn chỉnh: nó có package.json và không có trang HTML nào. Hãy build trước (thường là npm run build), rồi nén zip thư mục đầu ra (thường là dist hoặc build) và nhập nó. Không có gì được nhập.", + "Hoàn tác một lần để lấy lại phần này dưới dạng mã, hai lần để xóa nó.", + "Bỏ qua {0} tệp trong các thư mục hệ thống và thư mục phụ thuộc.", + "Bỏ qua 1 tệp trong một thư mục hệ thống hoặc thư mục phụ thuộc.", + "Hãy chọn ít nhất một tệp .html để nhập. Không có gì được nhập.", + "Hãy chọn một tệp .zip chứa trang web. Không có gì được nhập.", + "Tệp này không phải tệp lưu trữ zip mà FormWeb đọc được. Không có gì được nhập.", + "Tệp lưu trữ được bảo vệ bằng mật khẩu. Hãy tạo lại tệp zip không có mật khẩu. Không có gì được nhập.", + "Tệp lưu trữ lớn hơn 64.0 MiB, mức tối đa một lần nhập trang web nhận. Chỉ nén zip thư mục chứa trang web đã hoàn chỉnh, bỏ ra các video lớn và tệp nó không dùng. Không có gì được nhập.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 6deb25c2..e88961cc 100644 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -2899,4 +2899,45 @@ export default [ "1 个页面太大,无法一次转换,已保留为代码区块:请用“转换为可编辑元素”一次转换一部分。", "{0} 个页面太大,无法一次转换,已保留为代码区块:请用“转换为可编辑元素”逐个一次转换一部分。", "请在预览中以手机宽度检查,然后在各个断点下调整。", + "导入 HTML 文件", + "HTML 文件", + "选择一个或多个 .html 文件。每个文件都会成为一个新页面,也可以把单个文件作为区块放入此页面。", + "选择 .html 文件", + "整个站点打包为 .zip", + "粘贴 HTML 代码", + "粘贴一个页面的 HTML,将其作为区块添加到此页面。其样式和主脚本会一起带入,脚本在预览和已发布的站点中运行。", + "请先粘贴一个页面的 HTML。", + "作为新页面", + "作为此页面的区块", + "导入文件的方式", + "该页面会作为一个区块放入当前打开的页面,位于所选区块之后。其样式和主脚本会一起带入。", + "请选择一个 .zip 文件,或一个或多个 .html 文件。", + "这些文件合计超过 64 MiB,超过了导入的上限。", + "正在读取文件", + "这些文件中没有可导入的 HTML 页面。", + "每个文件都会在检查中显示的地址成为一个新页面,或者单个文件作为区块放入当前打开的页面。", + "选择其他文件", + "一个区块只能容纳一个文件。请只选择一个文件,将其作为区块添加到此页面。", + "导入页面", + "页面脚本", + "在预览和已发布的站点中运行,不在此画布上运行。", + "页面脚本在页面上没有盒子,因此这些设置不适用于它。", + "显示悬停轮廓", + "悬停轮廓已开启:指向图层时会在画布上为其元素显示轮廓,指向元素时会突出显示其图层。", + "悬停轮廓已关闭。", + "要导入的文件列表不是有效的 JSON。未导入任何内容。", + "请至少选择一个要导入的 .html 文件。", + "上传内容大于 64 MiB,超过了站点导入的上限。请只将包含完成站点的文件夹打包为 zip,并去掉大型视频和站点不使用的文件。未导入任何内容。", + "压缩包解压后超过 128.0 MiB,超过了站点导入的上限。请去掉大型视频和站点不使用的文件,然后重新打包为 zip。未导入任何内容。", + "所选文件合计超过 128.0 MiB,超过了站点导入的上限。请选择更少的文件。未导入任何内容。", + "压缩包的文件列表远远超出一个网站的需要,因此未打开。请只将包含完成站点的文件夹打包为 zip,不要包含 node_modules 等依赖文件夹,然后导入它。未导入任何内容。", + "这个 zip 是项目的源代码,不是完成的站点:它包含 package.json,但没有 HTML 页面。请先构建(通常是 npm run build),然后将输出文件夹(通常是 dist 或 build)打包为 zip 并导入。未导入任何内容。", + "撤销一次可将区块恢复为代码,撤销两次可将其删除。", + "将忽略系统和依赖文件夹中的 {0} 个文件。", + "将忽略系统或依赖文件夹中的 1 个文件。", + "请至少选择一个要导入的 .html 文件。未导入任何内容。", + "请选择包含站点的 .zip 文件。未导入任何内容。", + "此文件不是 FormWeb 能读取的 zip 压缩包。未导入任何内容。", + "压缩包受密码保护。请不设密码重新打包 zip。未导入任何内容。", + "压缩包大于 64.0 MiB,超过了站点导入的上限。请只将包含完成站点的文件夹打包为 zip,并去掉大型视频和站点不使用的文件。未导入任何内容。", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index 8cc4e06f..89b8fa15 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -2899,4 +2899,45 @@ export default [ "1 個頁面太大,無法一次轉換,已保留為程式碼區塊:請用「轉換為可編輯元素」一次轉換一部分。", "{0} 個頁面太大,無法一次轉換,已保留為程式碼區塊:請用「轉換為可編輯元素」逐一一次轉換一部分。", "請在預覽中以手機寬度檢查,然後在各個斷點下調整。", + "匯入 HTML 檔案", + "HTML 檔案", + "選擇一個或多個 .html 檔案。每個檔案都會成為新頁面,也可以把單一檔案作為區段放入此頁面。", + "選擇 .html 檔案", + "整個網站打包成 .zip", + "貼上 HTML 程式碼", + "貼上一個頁面的 HTML,將其作為區段加入此頁面。其樣式和主要指令碼會一起帶入,指令碼在預覽和已發布的網站中執行。", + "請先貼上一個頁面的 HTML。", + "作為新頁面", + "作為此頁面的區段", + "匯入檔案的方式", + "該頁面會作為一個區段放入目前開啟的頁面,位於所選區段之後。其樣式和主要指令碼會一起帶入。", + "請選擇一個 .zip 檔案,或一個或多個 .html 檔案。", + "這些檔案合計超過 64 MiB,超過匯入的上限。", + "正在讀取檔案", + "這些檔案中沒有可匯入的 HTML 頁面。", + "每個檔案都會在檢查中顯示的位址成為新頁面,或者單一檔案作為區段放入目前開啟的頁面。", + "選擇其他檔案", + "一個區段只能容納一個檔案。請只選擇一個檔案,將其作為區段加入此頁面。", + "匯入頁面", + "頁面指令碼", + "在預覽和已發布的網站中執行,不在此畫布上執行。", + "頁面指令碼在頁面上沒有方塊,因此這些設定不適用於它。", + "顯示懸停輪廓", + "懸停輪廓已開啟:指向圖層時會在畫布上為其元素顯示輪廓,指向元素時會醒目顯示其圖層。", + "懸停輪廓已關閉。", + "要匯入的檔案清單不是有效的 JSON。未匯入任何內容。", + "請至少選擇一個要匯入的 .html 檔案。", + "上傳內容大於 64 MiB,超過網站匯入的上限。請只將包含完成網站的資料夾打包成 zip,並去掉大型影片和網站不使用的檔案。未匯入任何內容。", + "封存檔解壓縮後超過 128.0 MiB,超過網站匯入的上限。請去掉大型影片和網站不使用的檔案,然後重新打包成 zip。未匯入任何內容。", + "所選檔案合計超過 128.0 MiB,超過網站匯入的上限。請選擇較少的檔案。未匯入任何內容。", + "封存檔的檔案清單遠遠超出一個網站的需要,因此未開啟。請只將包含完成網站的資料夾打包成 zip,不要包含 node_modules 等相依性資料夾,然後匯入它。未匯入任何內容。", + "這個 zip 是專案的原始碼,不是完成的網站:它包含 package.json,但沒有 HTML 頁面。請先建置(通常是 npm run build),然後將輸出資料夾(通常是 dist 或 build)打包成 zip 並匯入。未匯入任何內容。", + "復原一次可將區段恢復為程式碼,復原兩次可將其移除。", + "將忽略系統和相依性資料夾中的 {0} 個檔案。", + "將忽略系統或相依性資料夾中的 1 個檔案。", + "請至少選擇一個要匯入的 .html 檔案。未匯入任何內容。", + "請選擇包含網站的 .zip 檔案。未匯入任何內容。", + "此檔案不是 FormWeb 能讀取的 zip 封存檔。未匯入任何內容。", + "封存檔受密碼保護。請不設密碼重新打包 zip。未匯入任何內容。", + "封存檔大於 64.0 MiB,超過網站匯入的上限。請只將包含完成網站的資料夾打包成 zip,並去掉大型影片和網站不使用的檔案。未匯入任何內容。", ] as readonly string[]; From 08a77c4a7f661c90d32fa10eee8e1200cf5b749d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 17:22:42 -0500 Subject: [PATCH 07/31] fix(import): a project's source is also recognised by build scripts under its src folder, a page with a build placeholder, or a module that imports a package by name with no import map; a loose file holding text that is not valid is refused instead of failing; video segments named .ts are no longer called scripts; and the reader that words a refusal stops after 200,000 records or 16 MiB of file list --- backend/app/authoring_tools.py | 2 +- backend/app/site_import.py | 108 ++++++++++++++++++++++++--------- 2 files changed, 80 insertions(+), 30 deletions(-) diff --git a/backend/app/authoring_tools.py b/backend/app/authoring_tools.py index f27ea772..172a9bcb 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, or a page that loads .ts, .tsx, .jsx, .vue or .svelte scripts) 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, 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 45d6ce09..3b6b2d51 100644 --- a/backend/app/site_import.py +++ b/backend/app/site_import.py @@ -21,7 +21,9 @@ MAX_ENTRIES = 1000 MAX_RAW_ENTRIES = 40000 -MAX_PEEK = 300000 +MAX_PEEK = 200000 +PEEK_BYTES = 16 * 1024 * 1024 +PEEK_KEEP = 100 MAX_LISTING = 2 * 1024 * 1024 MAX_NAME = 255 BUILD_SCRIPTS = ('.ts', '.tsx', '.jsx', '.vue', '.svelte') @@ -84,42 +86,87 @@ def _ignored(parts: list[str]) -> bool: def _peek(data: bytes, end: int, listing: int) -> list[list[str]]: - """Names from the archive's file list, read record by record without zipfile, only to choose the sentence for an - archive that is refused before it is opened.""" - names, position = [], end - listing if 0 < listing <= end else struct.unpack('= PEEK_KEEP: + continue + parts = _parts(data[position - length - extra - comment:position - extra - comment].decode('utf-8' if flags & 0x800 else 'cp437', errors='replace')) + if parts and not _ignored(parts): + kept[kind] += 1 + names.append(parts) return names -def _project(names: list[list[str]], pages: dict | None = None) -> str | None: - """The refusal for a project's source rather than a built site: a package.json at the top or one folder down, and - no HTML page or a page that loads a script needing a build step. Without the pages' text, any such script file counts.""" - if not any(parts[-1].lower() == 'package.json' and len(parts) <= 2 for parts in names): +def _bare(script: str) -> str | None: + """The first package a module script loads by name (a bare specifier), which only a build or an import map resolves.""" + for match in re.finditer(r'''^[ \t]*(?:import\s*["']|import\b[^'"`;()]*?\bfrom\s*["']|export\b[^'"`;()]*?\bfrom\s*["'])([^"'\s]+)["']''', script, re.M): + specifier = match.group(1) + if not specifier.startswith(('.', '/')) and ':' not in specifier: + return specifier + return None + + +def _project(names: list[list[str]], files: dict | None = None) -> str | None: + """The refusal for a project's source rather than a built site. It needs a package.json at the top or one folder + down, and then one of: no HTML page; a .ts, .tsx, .jsx, .vue or .svelte file under that project's src folder; or, + with the pages' text, a page that loads such a script, holds a %PUBLIC_URL% placeholder, or loads a module script + that imports a package by name while no page has an import map. Without the pages' text (a refusal for count or + size), a .tsx, .jsx, .vue or .svelte file anywhere, or a .ts file under any src folder, counts too.""" + homes = [parts[:-1] for parts in names if parts[-1].lower() == 'package.json' and len(parts) <= 2] + if not homes: return None html = [parts for parts in names if _ext(parts[-1]) in ('html', 'htm')] - if pages is None: - found = sorted((parts for parts in names if parts[-1].lower().endswith(BUILD_SCRIPTS)), - key=lambda parts: (parts[-1].rsplit('.', 1)[0].lower() not in ('main', 'index'), len(parts), '/'.join(parts).lower())) - needs = ['/'.join(parts) for parts in found] - else: - needs = [] - for body in pages.values(): - for tag in re.finditer(r']*>', _text(body), re.I): - source = _attrs(tag.group(0)).get('src', '').strip() + builds = [parts for parts in names if parts[-1].lower().endswith(BUILD_SCRIPTS)] + found = [parts for parts in builds if any(parts[:len(home) + 1] == home + ['src'] and len(parts) > len(home) + 1 for home in homes)] + if files is None: + found += [parts for parts in builds if not parts[-1].lower().endswith('.ts') or 'src' in parts[:-1]] + found.sort(key=lambda parts: (parts[-1].rsplit('.', 1)[0].lower() not in ('main', 'index'), len(parts), '/'.join(parts).lower())) + needs, placeholders, packages = ['/'.join(parts) for parts in found], [], [] + if files is not None: + mapped = False + top = names[0][0] + '/' if names and all(len(parts) > 1 for parts in names) and len({parts[0] for parts in names}) == 1 else '' + for path, (kind, body) in files.items(): + if kind != 'page': + continue + document = _text(body) + if '%PUBLIC_URL%' in document: + placeholders.append(top + path) + for tag in re.finditer(r']*>', document, re.I): + attrs = _attrs(tag.group(0)) + sort = attrs.get('type', '').strip().lower() + mapped = mapped or sort == 'importmap' + source = attrs.get('src', '').strip() address = urlsplit(source) - if source and not address.scheme and not address.netloc and unquote(address.path).lower().endswith(BUILD_SCRIPTS): - needs.append(unquote(address.path).lstrip('./')) - if html and not needs: + if not source or address.scheme or address.netloc: + continue + target = unquote(address.path) + target = posixpath.normpath(target.lstrip('/') if target.startswith('/') else posixpath.join(posixpath.dirname(path), target)) + if target.lower().endswith(BUILD_SCRIPTS): + needs.append(top + target) + elif sort == 'module': + script = files.get(target) + if script and script[0] == 'script' and _bare(_text(script[1])): + packages.append(f'{top + target} loads {_bare(_text(script[1]))}') + if mapped: + packages = [] + if html and not needs and not placeholders and not packages: return None - shown = list(dict.fromkeys(_show(item) for item in needs)) - reason = (f'it has package.json and scripts that still need building ({", ".join(shown[:3])}{"..." if len(shown) > 3 else ""})' if needs + shown = list(dict.fromkeys(_show(item) for item in (needs or placeholders or packages))) + listed = f'{", ".join(shown[:3])}{"..." if len(shown) > 3 else ""}' + reason = (f'it has package.json and scripts that still need building ({listed})' if needs + else f'it has package.json and pages with placeholders that a build fills in ({listed})' if placeholders + else f'it has package.json and scripts that load packages by name, which a build bundles ({listed})' if packages else 'it has package.json and no HTML page') built = sorted('/'.join(parts[:-1]) for parts in html if parts[-1].lower() == 'index.html' and 2 <= len(parts) <= 3 and parts[-2].lower() in BUILT) extra = f' The zip also holds a built copy in the {_show(built[0])} folder: zip that folder on its own and import it.' if built else '' @@ -169,7 +216,10 @@ def read_files(payload) -> dict: if folded in seen: raise EngineError(f'Two of the chosen files are named {_show(name)}. Rename one and import again. Nothing was imported.', 400) seen.add(folded) - entries.append((name, item['html'].encode('utf-8'))) + try: + entries.append((name, item['html'].encode('utf-8'))) + except UnicodeEncodeError: + raise EngineError(f'{_show(name)} holds characters that are not valid text. Save the file as UTF-8 and choose it again. Nothing was imported.', 400) if sum(len(body) for _, body in entries) > MAX_UNPACKED: raise EngineError(f'The chosen files add up to more than {_size(MAX_UNPACKED)}, the most a site import takes. Choose fewer files. Nothing was imported.', 413) kept: dict[str, tuple[str, bytes]] = {} @@ -282,7 +332,7 @@ def read_archive(data: bytes) -> dict: skipped.append({'file': path, 'reason': str(error)}) continue files[path] = (kind, body) - source = _project(names, {path: body for path, (kind, body) in files.items() if kind == 'page'}) + source = _project(names, files) if source: raise EngineError(source, 400) return {'files': files, 'skipped': skipped, 'ignored': ignored} From 4c00ff719a7056d03c62eeecb9e51e38a3ed7d87 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 17:22:43 -0500 Subject: [PATCH 08/31] fix(library): a picked .html file is decoded as UTF-8 and then Windows-1252, as a page inside a zip is, so accented letters arrive intact; after a refused pick nothing can be imported until a new pick, and the refusal sentence stays in view --- frontend/src/features/library/site-import.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/frontend/src/features/library/site-import.ts b/frontend/src/features/library/site-import.ts index f10bfdab..2535cbde 100644 --- a/frontend/src/features/library/site-import.ts +++ b/frontend/src/features/library/site-import.ts @@ -15,6 +15,11 @@ 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); +/** 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); } + catch { return new TextDecoder('windows-1252').decode(bytes).replace(/[\u0081\u008d\u008f\u0090\u009d]/g, '�'); } +} /** * Import HTML files or a site from a zip: pick one .zip holding a static site, or one or several loose .html files, @@ -90,7 +95,7 @@ export class SiteImport { button.type = 'button'; label(button, english); button.setAttribute('role', 'radio'); - button.addEventListener('click', () => { if (!button.disabled) { this.use = use; this.paint(); } }); + button.addEventListener('click', () => { if (!button.disabled) { this.use = use; this.paint(); this.reveal(); } }); this.uses.append(button); } this.uses.setAttribute('role', 'radiogroup'); @@ -161,6 +166,11 @@ export class SiteImport { this.note.classList.toggle('is-error', error); } + /** Keeps a refusal sentence in view; the note is the scroller's last child, so this scrolls and moves nothing. */ + private reveal(): void { + if (this.note.classList.contains('is-error') && this.note.textContent) this.note.scrollIntoView({ block: 'nearest' }); + } + /** Work in progress reads on the import button, so the note changes only once, to the result. */ private progress(message: string): void { this.working = message; @@ -192,26 +202,31 @@ export class SiteImport { if (zips.length + pages.length !== files.length || (zips.length && files.length > 1)) { this.paint(); this.say(t('Choose one .zip file, or one or more .html files.'), true); + this.reveal(); return; } if (files.reduce((sum, file) => sum + file.size, 0) > 64 * 1024 * 1024) { this.paint(); this.say(zips.length ? t('The archive is larger than 64 MiB, the most a site import takes.') : t('The files are larger than 64 MiB together, the most an import takes.'), true); + this.reveal(); return; } this.working = zips.length ? t('Reading the archive...') : t('Reading the files...'); this.setBusy(true); try { if (zips.length) this.current = zips[0]; - else this.loose = await Promise.all(pages.map(async file => ({ name: file.name, html: await file.text() }))); + 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()); 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); } catch (error) { this.current = null; + this.loose = null; this.say(error instanceof Error ? error.message : String(error), true); } finally { this.setBusy(false); + this.reveal(); } } From 561f748b00afc326eb64eb2030786e25fd8b1d79 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 17:36:13 -0500 Subject: [PATCH 09/31] test(import): the site import's kept-file count, the bounds checked before an archive is opened, the source-project refusals and the sites that must still import, loose .html files against a zip of the same files, and every refusal ending with nothing imported and the site unchanged (99 cases) --- .../hostile/test_hostile_archive_limits.py | 142 ++++++++++++ .../site_import/test_site_import_counts.py | 108 +++++++++ .../test_site_import_loose_files.py | 216 ++++++++++++++++++ .../test_site_import_source_project.py | 131 +++++++++++ .../test_site_import_source_rule.py | 150 ++++++++++++ 5 files changed, 747 insertions(+) create mode 100644 backend/tests/hostile/test_hostile_archive_limits.py create mode 100644 backend/tests/site_import/test_site_import_counts.py create mode 100644 backend/tests/site_import/test_site_import_loose_files.py create mode 100644 backend/tests/site_import/test_site_import_source_project.py create mode 100644 backend/tests/site_import/test_site_import_source_rule.py diff --git a/backend/tests/hostile/test_hostile_archive_limits.py b/backend/tests/hostile/test_hostile_archive_limits.py new file mode 100644 index 00000000..d75678b5 --- /dev/null +++ b/backend/tests/hostile/test_hostile_archive_limits.py @@ -0,0 +1,142 @@ +import io +import struct +import zipfile + +import pytest + +from site_zips import answered_within, page, zip_of, zip_with_symlink + +REVIEW = "/api/library/import-site/review" +IMPORT = "/api/library/import-site" +BOUND = 30 +NOTHING = "Nothing was imported." +INDEX = page("Home", "

ok

") +BOMB = b"a" * (4 * 1024 * 1024) +SOURCE = {"package.json": '{"name": "app", "scripts": {"build": "vite build"}}', "index.html": page("App", '
', ''), "src/main.tsx": "export {};\n"} + + +@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 state_of(client): + state = client.get("/api/state").json() + return state["revision"], state["site"] + + +def claiming(data, entries): + raw = bytearray(data) + end = raw.rfind(b"PK\x05\x06") + struct.pack_into("= 0: + flags = struct.unpack_from(" 2 * 1024 * 1024 + status, detail = refused(client, route, data) + assert status == 413 + assert "big.css" not in detail + assert "zip only the folder that holds the finished site" in detail.lower() + assert detail.endswith(NOTHING) + + +def test_a_source_project_whose_archive_claims_too_many_entries_gets_the_source_sentence(client, blank): + status, detail = refused(client, REVIEW, claiming(zip_of(SOURCE), 65535)) + assert status == 413 + assert "npm run build" in detail and "src/main.tsx" in detail + assert "40,000" not in detail + assert detail.endswith(NOTHING) + + +def test_a_source_project_whose_file_list_is_over_two_mebibytes_gets_the_source_sentence(client, blank): + data = with_long_file_list(SOURCE) + assert listing_size(data) > 2 * 1024 * 1024 + status, detail = refused(client, REVIEW, data) + assert status == 413 + assert "npm run build" in detail and "src/main.tsx" in detail + assert detail.endswith(NOTHING) + + +REFUSALS = { + "an_empty_body": lambda: b"", + "bytes_that_are_not_a_zip": lambda: b"not a zip" * 10, + "a_symbolic_link_entry": lambda: zip_with_symlink(), + "a_name_climbing_out_of_its_folder": lambda: zip_of({"index.html": INDEX, "../evil.html": INDEX}), + "a_password_protected_entry": lambda: password_flagged(zip_of({"index.html": INDEX})), + "an_entry_that_expands_a_thousand_times": lambda: zip_of({"index.html": INDEX, "big.css": BOMB}), + "a_file_list_over_two_mebibytes": lambda: with_long_file_list({"index.html": INDEX}), + "a_projects_source_with_no_page": lambda: zip_of({"package.json": "{}", "src/app.js": "1"}), +} + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +@pytest.mark.parametrize("case", list(REFUSALS)) +def test_every_refused_archive_ends_by_saying_nothing_was_imported_and_leaves_the_revision_unchanged(client, blank, case, route): + status, detail = refused(client, route, REFUSALS[case]()) + assert detail.endswith(NOTHING), detail + assert "Traceback" not in detail diff --git a/backend/tests/site_import/test_site_import_counts.py b/backend/tests/site_import/test_site_import_counts.py new file mode 100644 index 00000000..e4f0f78c --- /dev/null +++ b/backend/tests/site_import/test_site_import_counts.py @@ -0,0 +1,108 @@ +import pytest + +from site_zips import answered_within, page, zip_of + +REVIEW = "/api/library/import-site/review" +IMPORT = "/api/library/import-site" +BOUND = 30 +NOTHING = "Nothing was imported." + + +@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 state_of(client): + state = client.get("/api/state").json() + return state["revision"], state["site"] + + +def small_site(): + return { + "index.html": page("Home", "

Home

"), + "about.html": page("About", "

About

"), + "gallery.html": page("Gallery", "

Gallery

"), + } + + +def with_extra(files, count, folder="notes"): + return {**files, **{f"{folder}/n{i}.txt": "x" for i in range(count)}} + + +def dependencies(count): + return {f"node_modules/pkg{i % 40}/lib/f{i}.js": "module.exports = 1;\n" for i in range(count)} + + +def refused(client, route, data): + before = state_of(client) + r = answered_within(BOUND, lambda: client.post(route, content=data)) + after = state_of(client) + assert after == before, "a refused import changed the site or its revision" + return r + + +def test_a_zip_of_twelve_hundred_entries_with_eight_hundred_in_node_modules_is_reviewed(client, blank): + files = {**with_extra(small_site(), 397), **dependencies(800)} + assert len(files) == 1200 + before = state_of(client) + r = answered_within(BOUND, lambda: client.post(REVIEW, content=zip_of(files))) + assert r.status_code == 200, r.text[:400] + body = r.json() + assert sorted(p["file"] for p in body["pages"]) == ["about.html", "gallery.html", "index.html"] + assert body["ignored"] == 800 + assert len(body["skipped"]) == 397 + assert state_of(client) == before + + +def test_mac_system_files_and_dot_folders_do_not_count_toward_the_thousand_either(client, blank): + files = with_extra(small_site(), 900) + files.update({f"__MACOSX/._n{i}.txt": "x" for i in range(150)}) + files.update({f".cache/c{i}.txt": "x" for i in range(150)}) + r = answered_within(BOUND, lambda: client.post(REVIEW, content=zip_of(files))) + assert r.status_code == 200, r.text[:400] + assert r.json()["ignored"] == 300 + assert len(r.json()["pages"]) == 3 + + +def test_a_zip_of_five_thousand_dependency_files_beside_a_small_site_is_reviewed_and_imported(client, blank): + data = zip_of({**small_site(), **dependencies(5000)}) + review = answered_within(BOUND, lambda: client.post(REVIEW, content=data)) + assert review.status_code == 200, review.text[:400] + assert review.json()["ignored"] == 5000 + r = answered_within(BOUND, lambda: client.post(f"{IMPORT}?mode=new&revision={review.json()['revision']}", content=data)) + assert r.status_code == 200, r.text[:400] + assert len(r.json()["pages"]) == 3 + assert len(state_of(client)[1]["pages"]) == 4 + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +def test_more_than_a_thousand_files_outside_ignored_folders_is_refused_with_a_sentence_that_says_what_to_zip(client, blank, route): + files = {**with_extra(small_site(), 998), **dependencies(300)} + r = refused(client, route, zip_of(files)) + assert r.status_code == 413, r.text[:400] + detail = r.json()["detail"] + assert "1,001" in detail + assert "zip only the folder that holds the finished site" in detail.lower() + assert detail.endswith(NOTHING) + + +def test_a_folder_deeper_than_twelve_levels_inside_node_modules_does_not_refuse_the_zip(client, blank): + deep = "node_modules/" + "/".join(f"d{i}" for i in range(18)) + "/index.js" + r = answered_within(BOUND, lambda: client.post(REVIEW, content=zip_of({**small_site(), deep: "x"}))) + assert r.status_code == 200, r.text[:400] + assert r.json()["ignored"] == 1 + assert len(r.json()["pages"]) == 3 + + +def test_a_kept_folder_deeper_than_twelve_levels_is_still_refused_when_deep_dependencies_sit_beside_it(client, blank): + deep_dependency = "node_modules/" + "/".join(f"d{i}" for i in range(18)) + "/index.js" + deep_page = "/".join(f"k{i}" for i in range(13)) + "/page.html" + r = refused(client, REVIEW, zip_of({**small_site(), deep_dependency: "x", deep_page: page("Deep", "

deep

")})) + assert r.status_code == 400, r.text[:400] + detail = r.json()["detail"] + assert "12" in detail and "page.html" in detail + assert "node_modules" not in detail + assert detail.endswith(NOTHING) diff --git a/backend/tests/site_import/test_site_import_loose_files.py b/backend/tests/site_import/test_site_import_loose_files.py new file mode 100644 index 00000000..1adc5e27 --- /dev/null +++ b/backend/tests/site_import/test_site_import_loose_files.py @@ -0,0 +1,216 @@ +import zipfile + +import pytest + +from site_zips import page, zip_of + +REVIEW = "/api/library/import-site/review" +IMPORT = "/api/library/import-site" +NOTHING = "Nothing was imported." +OVER_CAP = page("Long", "

" + "".join(f"line {i} of a long page. " for i in range(60000)) + "

") + + +@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 state_of(client): + state = client.get("/api/state").json() + return state["revision"], state["site"] + + +def loose(files): + return {"files": [{"name": name, "html": html} for name, html in files.items()]} + + +def review_of(client, files): + r = client.post(REVIEW, json=loose(files)) + assert r.status_code == 200, r.text[:400] + return r.json() + + +def imported(client, body, mode="new", zipped=False): + send = {"content": body} if zipped else {"json": body} + review = client.post(REVIEW, **send) + assert review.status_code == 200, review.text[:400] + r = client.post(f"{IMPORT}?mode={mode}&revision={review.json()['revision']}", **send) + assert r.status_code == 200, r.text[:400] + return review.json(), r.json() + + +def pages_as_seen(site): + sections = site["extensions"]["code"]["sections"] + seen = [] + for p in site["pages"]: + held = [sections[c]["html"] for c in site["nodes"][p["root"]]["children"] if c in sections] + seen.append((p["slug"], p["seo"]["title"], p["seo"]["description"], held)) + return sorted(seen) + + +def refusal(client, route, **send): + before = state_of(client) + r = client.post(route, **send) + assert state_of(client) == before, "a refused import changed the site or its revision" + assert 400 <= r.status_code < 500, (r.status_code, r.text[:400]) + detail = r.json()["detail"] + assert detail.endswith(NOTHING), detail + return r.status_code, detail + + +def test_one_loose_html_file_is_reviewed_with_its_address_and_imported_as_a_page(client, blank): + body = loose({"about.html": page("About us", "

About

", description="Who we are")}) + review, result = imported(client, body) + assert [(p["file"], p["newRoute"], p["title"]) for p in review["pages"]] == [("about.html", "/about", "About us")] + assert len(result["pages"]) == 1 + slugs = {p["slug"]: p for p in state_of(client)[1]["pages"]} + assert slugs["/about"]["seo"]["description"] == "Who we are" + + +def test_several_loose_files_with_htm_and_upper_case_extensions_all_become_pages(client, blank): + review = review_of(client, {"about.html": page("About", "

a

"), "contact.htm": page("Contact", "

c

"), "PRICES.HTML": page("Prices", "

p

")}) + assert sorted(p["file"] for p in review["pages"]) == ["PRICES.HTML", "about.html", "contact.htm"] + assert {p["title"] for p in review["pages"]} == {"About", "Contact", "Prices"} + assert review["skipped"] == [] + + +@pytest.mark.parametrize("name, base", [("../x.html", "x.html"), ("..\\..\\y.html", "y.html"), ("../../etc/z.html", "z.html"), ("C:\\Users\\me\\site\\w.html", "w.html")]) +def test_a_loose_name_with_path_parts_is_reduced_to_its_base_name(client, blank, name, base): + review = review_of(client, {name: page("T", "

t

")}) + assert [p["file"] for p in review["pages"]] == [base] + + +def test_two_loose_files_whose_names_differ_only_in_letter_case_are_refused(client, blank): + status, detail = refusal(client, REVIEW, json=loose({"About.html": page("A", "

a

"), "about.html": page("B", "

b

")})) + assert status == 400 + assert "about.html" in detail.lower() + + +@pytest.mark.parametrize("name", ["style.css", "app.js", "photo.png", "notes.txt"]) +def test_a_loose_file_that_is_not_html_is_refused_by_name(client, blank, name): + status, detail = refusal(client, IMPORT, json=loose({"index.html": page("H", "

h

"), name: "x"})) + assert status == 400 + assert name in detail + + +@pytest.mark.parametrize("name", ["", ".hidden.html", "folder/"]) +def test_a_loose_file_without_an_ordinary_name_is_refused(client, blank, name): + status, _ = refusal(client, REVIEW, json=loose({name: page("H", "

h

")})) + assert status == 400 + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +def test_an_empty_list_of_loose_files_is_refused(client, blank, route): + status, _ = refusal(client, route, json={"files": []}) + assert status == 400 + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +def test_more_than_a_hundred_loose_files_are_refused(client, blank, route): + status, detail = refusal(client, route, json=loose({f"p{i}.html": page(f"P{i}", "

x

") for i in range(101)})) + assert status == 413 + assert "101" in detail + + +def test_a_hundred_loose_files_are_accepted(client, blank): + review = review_of(client, {f"p{i}.html": page(f"P{i}", "

x

") for i in range(100)}) + assert len(review["pages"]) == 100 + + +@pytest.mark.parametrize("body", ['{"files": [', '{"files": "about.html"}', '[{"name": "a.html", "html": "x"}]', '{"files": [{"name": "a.html"}]}', "[" * 100000], ids=["cut_short", "files_not_a_list", "a_bare_list", "a_file_without_html", "deeply_nested"]) +def test_a_loose_body_that_is_not_the_expected_json_is_refused(client, blank, body): + status, _ = refusal(client, REVIEW, content=body.encode(), headers={"content-type": "application/json"}) + assert status == 400 + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +def test_a_loose_file_whose_html_holds_a_lone_surrogate_is_refused_and_names_the_file(client, blank, route): + body = b'{"files": [{"name": "a.html", "html": "

\\ud800

"}]}' + status, detail = refusal(client, route, content=body, headers={"content-type": "application/json"}) + assert status == 400 + assert "a.html" in detail + + +def test_a_loose_file_whose_html_holds_a_valid_surrogate_pair_is_imported(client, blank): + body = b'{"files": [{"name": "a.html", "html": "

\\ud83d\\ude00

"}]}' + headers = {"content-type": "application/json"} + review = client.post(REVIEW, content=body, headers=headers) + assert review.status_code == 200, review.text[:400] + r = client.post(f"{IMPORT}?mode=new&revision={review.json()['revision']}", content=body, headers=headers) + assert r.status_code == 200, r.text[:400] + html = "".join(h for slug, _, _, held in pages_as_seen(state_of(client)[1]) for h in held) + assert "\U0001F600" in html + + +def test_a_loose_file_over_the_page_cap_is_skipped_with_the_same_reason_a_zip_gives(client, blank): + assert len(OVER_CAP.encode()) > 1024 * 1024 + files = {"index.html": page("Home", "

h

"), "long.html": OVER_CAP} + from_loose = review_of(client, files) + from_zip = client.post(REVIEW, content=zip_of(files, zipfile.ZIP_STORED)).json() + assert [s["file"] for s in from_loose["skipped"]] == ["long.html"] + assert from_loose["skipped"] == from_zip["skipped"] + assert from_loose["skipped"][0]["reason"].endswith(".") + assert [p["file"] for p in from_loose["pages"]] == ["index.html"] + + +EQUIVALENT = { + "index.html": page("Home", '

Home

AboutContact', description="Start here"), + "about.html": page("About", '

About

Home', ''), + "contact.htm": page("Contact", "

Contact

"), + "Caf\u00e9.HTML": page("Caf\u00e9", "

menu

"), + "long.html": OVER_CAP, +} + + +def test_the_review_of_loose_files_equals_the_review_of_a_zip_of_the_same_files(client, blank): + from_loose = review_of(client, EQUIVALENT) + from_zip = client.post(REVIEW, content=zip_of(EQUIVALENT, zipfile.ZIP_STORED)) + assert from_zip.status_code == 200, from_zip.text[:400] + assert from_loose == from_zip.json() + assert len(from_loose["pages"]) == 4 + + +def test_importing_loose_files_gives_the_same_pages_as_importing_a_zip_of_the_same_files(client): + client.post("/api/new", json={"name": "Same", "blank": True}) + _, loose_result = imported(client, loose(EQUIVALENT)) + loose_site = pages_as_seen(state_of(client)[1]) + client.post("/api/new", json={"name": "Same", "blank": True}) + _, zip_result = imported(client, zip_of(EQUIVALENT, zipfile.ZIP_STORED), zipped=True) + zip_site = pages_as_seen(state_of(client)[1]) + assert loose_result["message"] == zip_result["message"] + assert loose_result["skipped"] == zip_result["skipped"] + assert loose_result["warnings"] == zip_result["warnings"] + assert len(loose_site) == 5 + assert loose_site == zip_site + + +def test_an_import_of_loose_files_is_one_undo_step(client, blank): + before = state_of(client)[1] + imported(client, loose({"about.html": page("About", "

a

"), "contact.html": page("Contact", "

c

")})) + assert len(state_of(client)[1]["pages"]) == 3 + client.post("/api/command", json={"command": "history.undo", "params": {}}) + assert state_of(client)[1] == before + + +def test_an_import_of_loose_files_after_the_site_changed_since_the_review_is_refused(client, blank): + body = loose({"about.html": page("About", "

a

")}) + revision = review_of(client, {"about.html": page("About", "

a

")})["revision"] + client.post("/api/command", json={"command": "page.add", "params": {"name": "Meanwhile", "slug": "/meanwhile"}}) + before = state_of(client) + r = client.post(f"{IMPORT}?mode=new&revision={revision}", json=body) + assert r.status_code == 409, r.text[:400] + assert "review" in r.json()["detail"].lower() + assert state_of(client) == before + + +def test_loose_files_imported_again_with_replace_mode_swap_content_without_adding_pages(client, blank): + imported(client, loose({"about.html": page("About", "

About first

")})) + count = len(state_of(client)[1]["pages"]) + review, _ = imported(client, loose({"about.html": page("About", "

About second

")}), mode="replace") + assert review["canReplace"] is True + site = state_of(client)[1] + assert len(site["pages"]) == count + seen = dict((slug, html) for slug, _, _, html in pages_as_seen(site)) + assert "About second" in "".join(seen["/about"]) and "About first" not in "".join(seen["/about"]) diff --git a/backend/tests/site_import/test_site_import_source_project.py b/backend/tests/site_import/test_site_import_source_project.py new file mode 100644 index 00000000..2b329190 --- /dev/null +++ b/backend/tests/site_import/test_site_import_source_project.py @@ -0,0 +1,131 @@ +import json + +import pytest + +from site_zips import answered_within, page, zip_of + +REVIEW = "/api/library/import-site/review" +IMPORT = "/api/library/import-site" +BOUND = 30 +NOTHING = "Nothing was imported." +PACKAGE = json.dumps({"name": "shop", "private": True, "scripts": {"dev": "vite", "build": "vite build"}, "devDependencies": {"vite": "^5.0.0"}}) + + +@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 state_of(client): + state = client.get("/api/state").json() + return state["revision"], state["site"] + + +def source_page(script): + return page("Shop", '
', f'') + + +def refusal(client, route, data): + before = state_of(client) + r = answered_within(BOUND, lambda: client.post(route, content=data)) + assert state_of(client) == before, "a refused import changed the site or its revision" + assert 400 <= r.status_code < 500, (r.status_code, r.text[:400]) + return r.status_code, r.json()["detail"] + + +def says_build_first(detail): + assert "source" in detail.lower(), detail + assert "npm run build" in detail, detail + assert "output folder" in detail, detail + assert detail.endswith(NOTHING), detail + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +def test_a_zip_with_package_json_and_no_html_page_is_refused_as_a_projects_source(client, blank, route): + status, detail = refusal(client, route, zip_of({"package.json": PACKAGE, "src/app.js": "console.log(1);\n", "README.md": "# Shop\n"})) + assert status == 400 + says_build_first(detail) + assert "no HTML page" in detail + + +@pytest.mark.parametrize("script", ["src/main.ts", "src/main.tsx", "src/main.jsx", "src/App.vue", "src/App.svelte"]) +def test_a_page_that_loads_a_script_needing_a_build_is_refused_and_the_script_is_named(client, blank, script): + files = {"package.json": PACKAGE, "index.html": source_page("/" + script), script: "export default 1;\n", "src/style.css": "body{margin:0}"} + status, detail = refusal(client, REVIEW, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert script in detail + + +def test_a_project_folder_one_level_down_is_still_recognised_as_source(client, blank): + files = {"shop/package.json": PACKAGE, "shop/index.html": source_page("./src/main.tsx"), "shop/src/main.tsx": "export {};\n"} + status, detail = refusal(client, IMPORT, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert "src/main.tsx" in detail + + +def test_a_source_zip_that_holds_no_built_copy_does_not_name_one(client, blank): + files = {"package.json": PACKAGE, "index.html": source_page("/src/main.tsx"), "src/main.tsx": "export {};\n"} + _, detail = refusal(client, REVIEW, zip_of(files)) + says_build_first(detail) + assert "dist folder" not in detail and "build folder" not in detail + + +@pytest.mark.parametrize("built", ["dist", "build"]) +def test_a_source_zip_that_also_holds_a_built_copy_names_that_folder(client, blank, built): + files = { + "package.json": PACKAGE, + "index.html": source_page("/src/main.tsx"), + "src/main.tsx": "export {};\n", + f"{built}/index.html": page("Shop", '
', ''), + f"{built}/assets/index-1a2b.js": "console.log(1);\n", + } + status, detail = refusal(client, REVIEW, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert f"{built} folder" in detail + + +def test_a_built_copy_one_folder_down_is_named_with_its_path(client, blank): + files = { + "shop/package.json": PACKAGE, + "shop/index.html": source_page("/src/main.tsx"), + "shop/src/main.tsx": "export {};\n", + "shop/dist/index.html": page("Shop", "

built

"), + } + _, detail = refusal(client, REVIEW, zip_of(files)) + says_build_first(detail) + assert "shop/dist folder" in detail + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +def test_a_source_project_over_the_file_limit_gets_the_source_sentence_instead_of_the_bare_limit(client, blank, route): + files = {"package.json": PACKAGE, "index.html": source_page("/src/main.tsx"), "src/main.tsx": "export {};\n"} + files.update({f"src/components/C{i}.tsx": "export {};\n" for i in range(1100)}) + files.update({f"node_modules/react/f{i}.js": "x" for i in range(400)}) + status, detail = refusal(client, route, zip_of(files)) + assert status == 413 + says_build_first(detail) + assert "main.tsx" in detail + assert "1,103" not in detail and "1,000" not in detail + + +def test_a_finished_static_site_with_a_harmless_package_json_is_reviewed_and_imported(client, blank): + files = { + "package.json": json.dumps({"name": "brochure", "version": "1.0.0", "scripts": {"start": "serve ."}}), + "index.html": page("Brochure", "

Welcome

", ''), + "about.html": page("About", "

About

"), + "app.js": "document.body.dataset.ok = '1';\n", + } + data = zip_of(files) + review = client.post(REVIEW, content=data) + assert review.status_code == 200, review.text[:400] + assert sorted(p["file"] for p in review.json()["pages"]) == ["about.html", "index.html"] + assert [s["file"] for s in review.json()["skipped"]] == ["package.json"] + r = client.post(f"{IMPORT}?mode=new&revision={review.json()['revision']}", content=data) + assert r.status_code == 200, r.text[:400] + assert len(r.json()["pages"]) == 2 + assert {p["seo"]["title"] for p in state_of(client)[1]["pages"]} >= {"Brochure", "About"} diff --git a/backend/tests/site_import/test_site_import_source_rule.py b/backend/tests/site_import/test_site_import_source_rule.py new file mode 100644 index 00000000..70a8e401 --- /dev/null +++ b/backend/tests/site_import/test_site_import_source_rule.py @@ -0,0 +1,150 @@ +import json + +import pytest + +from site_zips import answered_within, page, zip_of + +REVIEW = "/api/library/import-site/review" +IMPORT = "/api/library/import-site" +BOUND = 30 +NOTHING = "Nothing was imported." +PACKAGE = json.dumps({"name": "app", "private": True, "scripts": {"build": "vite build"}}) + + +@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 state_of(client): + state = client.get("/api/state").json() + return state["revision"], state["site"] + + +def refusal(client, route, data): + before = state_of(client) + r = answered_within(BOUND, lambda: client.post(route, content=data)) + assert state_of(client) == before, "a refused import changed the site or its revision" + assert 400 <= r.status_code < 500, (r.status_code, r.text[:400]) + return r.status_code, r.json()["detail"] + + +def says_build_first(detail): + assert "source" in detail.lower(), detail + assert "npm run build" in detail, detail + assert "output folder" in detail, detail + assert detail.endswith(NOTHING), detail + + +def imports(client, files, pages): + data = zip_of(files) + review = client.post(REVIEW, content=data) + assert review.status_code == 200, review.text[:400] + assert "package.json" in [s["file"] for s in review.json()["skipped"]] + r = client.post(f"{IMPORT}?mode=new&revision={review.json()['revision']}", content=data) + assert r.status_code == 200, r.text[:400] + assert len(r.json()["pages"]) == pages + return r.json() + + +def module_page(title="App", extra_head=""): + return page(title, '
', extra_head + '') + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +def test_a_page_with_a_public_url_placeholder_is_refused_as_a_projects_source(client, blank, route): + files = { + "package.json": PACKAGE, + "public/index.html": page("App", '
', ''), + "src/index.js": "document.title = 'x';\n", + } + status, detail = refusal(client, route, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert detail.count("public/index.html") == 1 + + +@pytest.mark.parametrize("script", ["src/util.ts", "src/App.tsx", "src/App.jsx", "src/App.vue", "src/App.svelte"]) +def test_a_script_needing_a_build_under_src_is_refused_even_when_no_page_loads_it(client, blank, script): + files = {"package.json": PACKAGE, "index.html": page("Home", "

h

", ''), "app.js": "1;\n", script: "export default 1;\n"} + status, detail = refusal(client, REVIEW, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert detail.count(script) == 1 + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +def test_a_module_script_that_imports_a_package_by_name_is_refused_and_both_are_named(client, blank, route): + files = {"package.json": PACKAGE, "index.html": module_page(), "src/main.js": 'import confetti from "canvas-confetti";\nconfetti();\n'} + status, detail = refusal(client, route, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert detail.count("src/main.js") == 1 + assert "canvas-confetti" in detail + + +def test_a_module_script_that_imports_a_package_named_in_an_import_map_imports(client, blank): + importmap = '' + files = {"package.json": PACKAGE, "index.html": module_page(extra_head=importmap), "src/main.js": 'import confetti from "canvas-confetti";\nconfetti();\n'} + imports(client, files, 1) + + +def test_a_finished_site_with_package_json_and_a_src_folder_of_plain_js_and_css_using_relative_imports_imports(client, blank): + files = { + "package.json": PACKAGE, + "index.html": module_page("Home", ''), + "about.html": page("About", "

about

", ''), + "src/main.js": 'import { label } from "./util.js";\nexport * from "./util.js";\ndocument.title = label;\n', + "src/util.js": "export const label = 'abc';\nexport default 'abc';\n", + "src/site.css": "body{margin:0}\n", + "js/old.js": "window.old = 1;\n", + } + imports(client, files, 2) + + +def test_a_module_script_that_imports_from_an_https_address_imports(client, blank): + files = {"package.json": PACKAGE, "index.html": module_page(), "src/main.js": 'import confetti from "https://cdn.example.org/confetti.mjs";\nconfetti();\n'} + imports(client, files, 1) + + +NAMED_ONCE = { + "a_page_in_src_loading_a_script_beside_it": ({"package.json": PACKAGE, "src/index.html": page("A", "

a

", ''), "src/main.ts": "export {};\n"}, "src/main.ts"), + "the_same_one_folder_down_with_a_dot_slash": ({"app/package.json": PACKAGE, "app/src/index.html": page("A", "

a

", ''), "app/src/main.ts": "export {};\n"}, "app/src/main.ts"), + "a_top_page_loading_from_the_root": ({"package.json": PACKAGE, "index.html": page("A", "

a

", ''), "src/main.tsx": "export {};\n"}, "src/main.tsx"), + "a_top_page_loading_from_the_root_one_folder_down": ({"p/package.json": PACKAGE, "p/index.html": page("A", "

a

", ''), "p/src/main.tsx": "export {};\n"}, "p/src/main.tsx"), + "a_placeholder_page_one_folder_down": ({"p/package.json": PACKAGE, "p/public/index.html": page("A", "

a

", ''), "p/src/index.js": "1;\n"}, "p/public/index.html"), + "a_by_name_import_one_folder_down": ({"p/package.json": PACKAGE, "p/index.html": module_page(), "p/src/main.js": 'import x from "lib";\n'}, "p/src/main.js"), +} + + +@pytest.mark.parametrize("case", list(NAMED_ONCE)) +def test_each_script_or_page_is_named_once_by_its_path_in_the_archive(client, blank, case): + files, path = NAMED_ONCE[case] + status, detail = refusal(client, REVIEW, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert detail.count(path) == 1, detail + name = path.rsplit("/", 1)[-1] + assert detail.count(name) == 1, detail + + +def test_an_over_limit_zip_of_video_segments_named_ts_outside_src_gets_the_plain_count_sentence(client, blank): + files = {"package.json": PACKAGE, "index.html": page("Video", '')} + files.update({f"video/seg{i}.ts": b"\x47" * 188 for i in range(1200)}) + status, detail = refusal(client, REVIEW, zip_of(files)) + assert status == 413 + assert "1,202" in detail + assert "npm run build" not in detail + assert "zip only the folder that holds the finished site" in detail.lower() + assert detail.endswith(NOTHING) + + +def test_an_over_limit_zip_with_the_same_count_of_ts_files_under_src_gets_the_source_sentence(client, blank): + files = {"package.json": PACKAGE, "index.html": page("App", "

a

")} + files.update({f"src/seg{i}.ts": "export {};\n" for i in range(1200)}) + status, detail = refusal(client, REVIEW, zip_of(files)) + assert status == 413 + says_build_first(detail) + assert "1,202" not in detail From 608c62cb7162ff7fb074d32a24dbbe67269d56b5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 17:36:13 -0500 Subject: [PATCH 10/31] test(editor): which nodes are a page script and what the canvas and the panes show for one, hover outlines for mouse, pen and the blocked cases, and the import view's picks, decoding of picked files and refusals (62 tests) --- .../tests/unit/canvas/hover-outline.test.ts | 228 ++++++++++++ .../tests/unit/canvas/page-script.test.ts | 95 +++++ .../tests/unit/inspector/script-panes.test.ts | 157 +++++++++ .../tests/unit/library/import-view.test.ts | 329 ++++++++++++++++++ 4 files changed, 809 insertions(+) create mode 100644 frontend/tests/unit/canvas/hover-outline.test.ts create mode 100644 frontend/tests/unit/canvas/page-script.test.ts create mode 100644 frontend/tests/unit/inspector/script-panes.test.ts create mode 100644 frontend/tests/unit/library/import-view.test.ts diff --git a/frontend/tests/unit/canvas/hover-outline.test.ts b/frontend/tests/unit/canvas/hover-outline.test.ts new file mode 100644 index 00000000..22ce31a7 --- /dev/null +++ b/frontend/tests/unit/canvas/hover-outline.test.ts @@ -0,0 +1,228 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { installHoverOutline } from '../../../src/features/hover-outline'; +import type { CommandDef } from '../../../src/ui/shell'; + +const KEY = 'formweb.canvas.hover-outline'; +const ON = 'Hover outlines are on: pointing at a layer outlines its element on the canvas, and pointing at an element tints its layer.'; +const OFF = 'Hover outlines are off.'; + +let canvas: Document; +let list: HTMLElement; +let selected: string[]; +let previewing: boolean; +let said: string[]; +let sent: unknown[]; +let command: CommandDef; + +function install(): CommandDef { + canvas = document.implementation.createHTMLDocument('canvas'); + const root = canvas.createElement('main'); + root.dataset.fwId = 'root'; + for (const id of ['title', 'lead', 'call']) { + const node = canvas.createElement(id === 'title' ? 'h1' : 'p'); + node.dataset.fwId = id; + node.textContent = id; + root.append(node); + } + canvas.body.append(root); + list = document.createElement('div'); + for (const id of ['root', 'title', 'lead', 'call']) { + const row = document.createElement('div'); + row.className = 'list-row layer-row'; + row.dataset.key = id; + const name = document.createElement('span'); + name.className = 'row-label'; + name.textContent = id; + row.append(name); + list.append(row); + } + document.body.append(list); + const [toggle] = installHoverOutline({ + frame: { contentDocument: canvas } as unknown as HTMLIFrameElement, + loaded: () => Promise.resolve(), + list, + ready: () => true, + editing: () => !previewing, + busy: () => false, + root: () => 'root', + selectionIds: () => selected, + status: message => { said.push(message); } + }); + return toggle; +} + +const frame = (): Promise => new Promise(resolve => requestAnimationFrame(() => resolve())); +const loaded = (): Promise => new Promise(resolve => setTimeout(resolve, 0)); +const row = (id: string): HTMLElement => list.querySelector(`[data-key="${id}"]`)!; +const node = (id: string): HTMLElement => canvas.querySelector(`[data-fw-id="${id}"]`)!; +const outlined = (): string[] => Array.from(canvas.querySelectorAll('[data-fw-hover]')).map(found => found.dataset.fwId || ''); +const tinted = (): string[] => Array.from(list.querySelectorAll('[data-fw-hover]')).map(found => found.dataset.key || ''); + +async function point(target: Element, pointerType = 'mouse'): Promise { + target.dispatchEvent(new PointerEvent('pointermove', { pointerType, bubbles: true })); + await frame(); +} + +beforeEach(async () => { + document.body.replaceChildren(); + document.body.className = ''; + localStorage.clear(); + selected = ['lead']; + previewing = false; + said = []; + sent = []; + vi.stubGlobal('fetch', (url: unknown) => { sent.push(url); return new Promise(() => undefined); }); + command = install(); + await loaded(); +}); + +afterEach(() => { vi.unstubAllGlobals(); }); + +describe('pointing at a layer row', () => { + it('a mouse resting on a layer row outlines that one element on the canvas', async () => { + await point(row('title').querySelector('.row-label')!); + expect(outlined()).toEqual(['title']); + }); + + it('moving to another row moves the outline, so only one element is ever outlined', async () => { + await point(row('title')); + await point(row('call')); + expect(outlined()).toEqual(['call']); + }); + + it('leaving the list clears the outline', async () => { + await point(row('title')); + list.dispatchEvent(new PointerEvent('pointerleave', { pointerType: 'mouse' })); + expect(outlined()).toEqual([]); + }); + + it('the selected element and the page root are never outlined from their rows', async () => { + await point(row('lead')); + expect(outlined()).toEqual([]); + await point(row('root')); + expect(outlined()).toEqual([]); + }); + + it('a pen or a touch on a layer row outlines nothing', async () => { + await point(row('title'), 'pen'); + expect(outlined()).toEqual([]); + await point(row('title'), 'touch'); + expect(outlined()).toEqual([]); + }); +}); + +describe('pointing at an element on the canvas', () => { + it('a mouse resting on an element outlines it and tints its layer row', async () => { + await point(node('call')); + expect(outlined()).toEqual(['call']); + expect(tinted()).toEqual(['call']); + }); + + it('the selected element shows no hover outline and no tint', async () => { + await point(node('lead')); + expect(outlined()).toEqual([]); + expect(tinted()).toEqual([]); + }); + + it('a pen on the canvas outlines nothing and clears an outline the mouse left', async () => { + await point(node('call')); + await point(node('call'), 'pen'); + expect(outlined()).toEqual([]); + expect(tinted()).toEqual([]); + }); +}); + +describe('when nothing shows', () => { + it('nothing shows while an element is dragged on the canvas, and it shows again once the drag ends', async () => { + canvas.documentElement.setAttribute('data-fw-dragging', ''); + await point(node('call')); + expect(outlined()).toEqual([]); + canvas.documentElement.removeAttribute('data-fw-dragging'); + await point(node('call')); + expect(outlined()).toEqual(['call']); + }); + + it('nothing shows while a layer row is dragged, and it shows again once the drag ends', async () => { + document.body.classList.add('fw-row-dragging'); + await point(row('title')); + expect(outlined()).toEqual([]); + document.body.classList.remove('fw-row-dragging'); + await point(row('title')); + expect(outlined()).toEqual(['title']); + }); + + it('nothing shows while text is being edited on the canvas, and it shows again once editing ends', async () => { + node('title').setAttribute('contenteditable', 'true'); + await point(node('call')); + expect(outlined()).toEqual([]); + node('title').removeAttribute('contenteditable'); + await point(node('call')); + expect(outlined()).toEqual(['call']); + }); + + it('nothing shows while a menu is open, and pointing again once it closes shows the outline', async () => { + const menu = document.createElement('div'); + menu.className = 'fw-menu'; + document.body.append(menu); + await point(row('title')); + expect(outlined()).toEqual([]); + menu.hidden = true; + await point(row('title')); + expect(outlined()).toEqual(['title']); + }); + + it('nothing shows in Preview, and it shows again back in the design view', async () => { + previewing = true; + await point(row('title')); + expect(outlined()).toEqual([]); + previewing = false; + await point(row('title')); + expect(outlined()).toEqual(['title']); + }); +}); + +describe('the Show hover outlines switch', () => { + it('is on by default, with nothing stored', () => { + expect(command.label).toBe('Show hover outlines'); + expect(command.checked?.()).toBe(true); + expect(localStorage.getItem(KEY)).toBeNull(); + }); + + it('switching it off says so, stops the outline and is remembered by a new window', async () => { + command.run(); + expect(said).toEqual([OFF]); + expect(command.checked?.()).toBe(false); + await point(row('title')); + expect(outlined()).toEqual([]); + document.body.replaceChildren(); + const reloaded = install(); + await loaded(); + expect(reloaded.checked?.()).toBe(false); + await point(row('title')); + expect(outlined()).toEqual([]); + }); + + it('switching it off with an outline showing removes the outline at once', async () => { + await point(row('title')); + command.run(); + expect(outlined()).toEqual([]); + }); + + it('switching it back on says so and the outline works again', async () => { + command.run(); + command.run(); + expect(said).toEqual([OFF, ON]); + expect(command.checked?.()).toBe(true); + await point(row('title')); + expect(outlined()).toEqual(['title']); + }); + + it('the choice is kept in this browser only and never sent to the site', async () => { + command.run(); + expect(localStorage.getItem(KEY)).toBe('0'); + command.run(); + expect(localStorage.getItem(KEY)).toBe('1'); + await point(row('title')); + expect(sent).toEqual([]); + }); +}); diff --git a/frontend/tests/unit/canvas/page-script.test.ts b/frontend/tests/unit/canvas/page-script.test.ts new file mode 100644 index 00000000..02cdb74d --- /dev/null +++ b/frontend/tests/unit/canvas/page-script.test.ts @@ -0,0 +1,95 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { Canvas, codeKind } from '../../../src/ui/canvas'; +import type { Site } from '../../../src/types'; +import { makeSite } from '../site'; + +const SCRIPT = 'document.querySelector("#out").textContent = "ran";'; + +function pageWith(sections: Record>, instances: Record = {}): Site { + return makeSite([{ id: 'home', name: 'Home', slug: '/', root: 'root' }], { + root: { tag: 'main', children: ['heading', 'script', 'block', 'widget'] }, + heading: { tag: 'h1' }, + script: { tag: 'div', styles: { display: 'contents' } }, + block: { tag: 'div' }, + widget: { tag: 'div' } + }, { code: { allowSections: true, sections, instances, components: { card: { name: 'Card' } } } }); +} + +let stage: HTMLElement | undefined; +afterEach(() => { stage?.remove(); stage = undefined; }); + +async function drawn(site: Site, posters: Record): Promise<{ canvas: Canvas; doc: Document }> { + stage = document.createElement('div'); + const canvas = new Canvas(stage, () => undefined, () => undefined); + document.body.append(stage); + canvas.setPosters(posters); + canvas.render(site, site.pages[0], '', 1280, 'en', ''); + await canvas.loaded(); + return { canvas, doc: canvas.frame.contentDocument! }; +} + +const placeholder = (doc: Document, id: string): HTMLElement | null => doc.querySelector(`[data-fw-id="${id}"] > div[data-fw-poster]`); +const words = (poster: HTMLElement | null): string[] => !poster ? [] : poster.children.length ? Array.from(poster.children).filter(part => !(part as HTMLElement).hidden).map(part => part.textContent ?? '') : [poster.textContent ?? '']; + +describe('which nodes are a page script', () => { + const site = pageWith({ script: { html: '', css: '', js: SCRIPT }, block: { html: '

waiting

', css: '', js: SCRIPT } }); + + it('a code section with a script and no HTML is a page script', () => { + expect(codeKind(site, 'script')).toBe('script'); + }); + + it('a code section with HTML is a code section, not a page script, even when it also has a script', () => { + expect(codeKind(site, 'block')).toBe('code'); + }); + + it('a code section with HTML and no script is a code section', () => { + const plain = pageWith({ block: { html: '

Hello

', css: 'p{color:red}', js: '' } }); + expect(codeKind(plain, 'block')).toBe('code'); + }); + + it('a node with no code section is neither a page script nor a code section', () => { + expect(codeKind(site, 'heading')).toBe(''); + }); +}); + +describe('the canvas placeholder of a code section', () => { + it('a script-only code section says Page script and that it runs in Preview and on the published site', async () => { + const { doc } = await drawn(pageWith({ script: { html: '', css: '', js: SCRIPT } }), { script: '' }); + const poster = placeholder(doc, 'script'); + expect(poster?.getAttribute('data-fw-poster')).toBe('script'); + expect(words(poster)).toEqual(['Page script', 'Runs in Preview and on the published site, not on this canvas.']); + }); + + it('a code section with HTML says Code section and nothing more', async () => { + const { doc } = await drawn(pageWith({ block: { html: '

waiting

', css: '', js: SCRIPT } }), { block: '' }); + expect(words(placeholder(doc, 'block'))).toEqual(['Code section']); + }); + + it('a component without a picture still says Component', async () => { + const { doc } = await drawn(pageWith({}, { widget: { component: 'card' } }), { widget: '' }); + expect(words(placeholder(doc, 'widget'))).toEqual(['Component']); + }); + + it('a script that gains HTML keeps the same placeholder on the canvas and only its words change, and back again', async () => { + const scriptOnly = pageWith({ script: { html: '', css: '', js: SCRIPT } }); + const { canvas, doc } = await drawn(scriptOnly, { script: '' }); + const before = placeholder(doc, 'script')!; + const parts = Array.from(before.children); + const withHtml = pageWith({ script: { html: '

waiting

', css: '', js: SCRIPT } }); + canvas.render(withHtml, withHtml.pages[0], '', 1280, 'en', ''); + expect(placeholder(doc, 'script')).toBe(before); + expect(Array.from(before.children)).toEqual(parts); + expect(words(before)).toEqual(['Code section']); + canvas.render(scriptOnly, scriptOnly.pages[0], '', 1280, 'en', ''); + expect(placeholder(doc, 'script')).toBe(before); + expect(words(before)).toEqual(['Page script', 'Runs in Preview and on the published site, not on this canvas.']); + }); + + it('a page script stored the way sites were converted before 0.32.0 is shown as a page script and the site is not changed', async () => { + const old = pageWith({ script: { js: SCRIPT } }); + const stored = structuredClone(old); + const { doc } = await drawn(old, { script: '' }); + expect(words(placeholder(doc, 'script'))[0]).toBe('Page script'); + expect(old).toEqual(stored); + }); +}); diff --git a/frontend/tests/unit/inspector/script-panes.test.ts b/frontend/tests/unit/inspector/script-panes.test.ts new file mode 100644 index 00000000..2af4206e --- /dev/null +++ b/frontend/tests/unit/inspector/script-panes.test.ts @@ -0,0 +1,157 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { installScriptPanes, isPageScript, layerGlyph, paintGlyph } from '../../../src/features/inspector/script-note'; +import type { Site } from '../../../src/types'; +import { makeSite } from '../site'; + +const NOTE = 'A page script has no box on the page, so these settings do not apply to it.'; + +function siteWith(sections: Record>): Site { + return makeSite([{ id: 'home', name: 'Home', slug: '/', root: 'root' }], { + root: { tag: 'main', children: ['heading', 'node'] }, + heading: { tag: 'h1' }, + node: { tag: 'div', styles: { display: 'contents' } } + }, { code: { allowSections: true, sections } }); +} + +describe('the layer icon of a page script', () => { + it('a page script row shows the script icon, a code section the code icon and any other element the box icon', () => { + const glyph = layerGlyph(); + paintGlyph(glyph, siteWith({ node: { html: '', css: '', js: 'run()' } }), 'node'); + expect(glyph.dataset.glyph).toBe('script'); + paintGlyph(glyph, siteWith({ node: { html: '

Hi

', css: '', js: '' } }), 'node'); + expect(glyph.dataset.glyph).toBe('code'); + paintGlyph(glyph, siteWith({}), 'heading'); + expect(glyph.dataset.glyph).toBe('box'); + }); + + it('the icon element and its pictures stay the same nodes when the kind of the layer changes', () => { + const glyph = layerGlyph(); + const row = document.createElement('div'); + row.append(glyph); + const pictures = Array.from(glyph.children); + const changes: MutationRecord[] = []; + const watch = new MutationObserver(found => changes.push(...found)); + watch.observe(row, { childList: true, subtree: true }); + const kinds: Record>[] = [{ node: { html: '', css: '', js: 'run()' } }, { node: { html: '

Hi

', css: '', js: '' } }, {}]; + for (const sections of kinds) paintGlyph(row.children[0], siteWith(sections), 'node'); + changes.push(...watch.takeRecords()); + watch.disconnect(); + expect(row.children[0]).toBe(glyph); + expect(Array.from(glyph.children)).toEqual(pictures); + expect(changes).toEqual([]); + }); +}); + +describe('which selection is a page script for the inspector', () => { + it('a code section with a script and no HTML is a page script', () => { + expect(isPageScript(siteWith({ node: { html: '', css: '', js: 'run()' } }), 'node')).toBe(true); + }); + + it('a code section with HTML is not a page script, even with a script', () => { + expect(isPageScript(siteWith({ node: { html: '

Hi

', css: '', js: 'run()' } }), 'node')).toBe(false); + }); + + it('an element with no code section is not a page script', () => { + expect(isPageScript(siteWith({ node: { html: '', css: '', js: 'run()' } }), 'heading')).toBe(false); + }); + + it('a script stored the way sites were converted before 0.32.0, with no HTML field at all, is a page script and the site is not changed', () => { + const old = siteWith({ node: { js: 'run()' } }); + const stored = structuredClone(old); + expect(isPageScript(old, 'node')).toBe(true); + paintGlyph(layerGlyph(), old, 'node'); + expect(old).toEqual(stored); + }); +}); + +describe('the Design and Motion panes while a page script is selected', () => { + let scroller: HTMLElement; + let design: HTMLElement; + let motion: HTMLElement; + let controls: HTMLElement[]; + let panes: ReturnType; + + beforeEach(() => { + document.body.replaceChildren(); + scroller = document.createElement('div'); + design = document.createElement('div'); + motion = document.createElement('div'); + const content = document.createElement('div'); + const code = document.createElement('div'); + code.dataset.codeSection = ''; + content.append(code); + controls = ['Background', 'Spacing', 'Animation'].map(name => { + const section = document.createElement('div'); + section.className = 'inspector-section'; + section.textContent = name; + return section; + }); + design.append(controls[0], controls[1]); + motion.append(controls[2]); + scroller.append(design, motion, content); + document.body.append(scroller); + panes = installScriptPanes([design, motion]); + }); + + const notes = (): HTMLElement[] => [design, motion].map(pane => pane.querySelector('.fw-script-note')!); + const visible = (pane: HTMLElement, child: HTMLElement): boolean => !child.hidden && (child.classList.contains('fw-script-note') || !pane.classList.contains('fw-pane-script')); + const shown = (pane: HTMLElement): string[] => Array.from(pane.children).filter(child => visible(pane, child as HTMLElement)).map(child => child.textContent ?? ''); + + it('with a page script selected, Design and Motion each say the settings do not apply and show no controls', () => { + panes.update(true, 'design'); + expect(shown(design)).toEqual([NOTE]); + expect(shown(motion)).toEqual([NOTE]); + }); + + it('selecting another element hides the note and brings the controls back', () => { + panes.update(true, 'design'); + panes.update(false, 'content'); + expect(notes().map(note => note.hidden)).toEqual([true, true]); + expect(shown(design)).toEqual(['Background', 'Spacing']); + expect(shown(motion)).toEqual(['Animation']); + }); + + it('before any page script is selected the panes show only their controls', () => { + panes.update(false, 'design'); + expect(shown(design)).toEqual(['Background', 'Spacing']); + expect(shown(motion)).toEqual(['Animation']); + }); + + it('selecting a page script from Motion moves the inspector to Content, and selecting an element after it returns to Motion', () => { + expect(panes.update(true, 'motion')).toBe('content'); + expect(panes.update(false, 'content')).toBe('motion'); + }); + + it('selecting a page script from Design moves to Content, and returns to Design afterwards', () => { + expect(panes.update(true, 'design')).toBe('content'); + expect(panes.update(false, 'content')).toBe('design'); + }); + + it('a person who leaves Content for another tab while the script is selected stays on that tab', () => { + expect(panes.update(true, 'motion')).toBe('content'); + expect(panes.update(false, 'design')).toBe('design'); + }); + + it('selecting a page script from Content or Page keeps that tab', () => { + expect(panes.update(true, 'content')).toBe('content'); + expect(panes.update(false, 'content')).toBe('content'); + expect(panes.update(true, 'page')).toBe('page'); + expect(panes.update(false, 'page')).toBe('page'); + }); + + it('going in and out of a page script keeps every control mounted: no node is added or removed', () => { + const before = [Array.from(design.children), Array.from(motion.children)]; + const changes: MutationRecord[] = []; + const watch = new MutationObserver(found => changes.push(...found.filter(record => record.type === 'childList'))); + watch.observe(scroller, { childList: true, subtree: true }); + panes.update(true, 'motion'); + panes.update(false, 'content'); + panes.update(true, 'design'); + panes.update(false, 'design'); + changes.push(...watch.takeRecords().filter(record => record.type === 'childList')); + watch.disconnect(); + expect(changes).toEqual([]); + expect([Array.from(design.children), Array.from(motion.children)]).toEqual(before); + expect(controls.every(control => control.isConnected)).toBe(true); + }); +}); diff --git a/frontend/tests/unit/library/import-view.test.ts b/frontend/tests/unit/library/import-view.test.ts new file mode 100644 index 00000000..0951e8a0 --- /dev/null +++ b/frontend/tests/unit/library/import-view.test.ts @@ -0,0 +1,329 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { SiteImport } from '../../../src/features/library/site-import'; +import type { LibraryHooks, SiteReview } from '../../../src/features/library/types'; + +const REFUSED = 'Choose one .zip file, or one or more .html files.'; +const ONE_FILE = 'A section takes one file. Choose a single file to add it to this page as a section.'; +const STOPWATCH = 'Pocket Lap Timer

Lap timer

'; +const ABOUT = 'About

About us

'; + +type Sent = { path: string; body: unknown }; +let sent: Sent[]; +let view: SiteImport; +let shown: number; + +function reviewOf(files: { name: string }[]): SiteReview { + return { + pages: files.map(file => { + const route = '/' + file.name.replace(/\.html?$/i, ''); + return { file: file.name, name: file.name, title: file.name, description: '', route, newRoute: route, replaces: null, bytes: 100, warnings: [] }; + }), + assets: { count: 0, bytes: 0 }, supportFiles: 0, skipped: [], ignored: 0, canReplace: false, replaceNote: '', notes: [], revision: 3 + }; +} + +function answer(body: unknown): Promise { + return Promise.resolve({ ok: true, status: 200, statusText: 'OK', json: () => Promise.resolve(body) } as Response); +} + +function refusal(detail: string): Promise { + return Promise.resolve({ ok: false, status: 400, statusText: 'Bad Request', json: () => Promise.resolve({ detail }) } as Response); +} + +let refuse: string; +let noPages: boolean; + +beforeEach(() => { + document.body.replaceChildren(); + sent = []; + shown = 0; + refuse = ''; + noPages = false; + vi.stubGlobal('fetch', (url: string, init?: RequestInit) => { + if (url.endsWith('/api/window/key')) return answer({ key: 'window-key' }); + const body = typeof init?.body === 'string' ? JSON.parse(init.body) : init?.body; + sent.push({ path: url, body }); + if (url.endsWith('/api/library/import-site/review')) { + if (refuse) return refusal(refuse); + return answer(noPages ? reviewOf([]) : reviewOf((body as { files: { name: string }[] }).files)); + } + if (url.includes('/api/library/import-site?') || url.endsWith('/api/library/import-html')) return answer({ pages: [] }); + return new Promise(() => undefined); + }); + const hooks: LibraryHooks = { + placement: () => ({ page: 'home', parent: 'root' }), + select: () => undefined, + openPage: () => undefined, + notify: () => undefined, + url: path => path, + convert: () => Promise.resolve({ message: '', root: null }) + }; + view = new SiteImport(hooks, () => undefined, () => { shown += 1; }); + document.body.append(view.element); +}); + +afterEach(() => { vi.unstubAllGlobals(); }); + +const picker = (): HTMLInputElement => view.element.querySelector('input[type="file"]')!; +const note = (): HTMLElement => view.element.querySelector('[role="status"]')!; +const button = (words: string): HTMLButtonElement => Array.from(view.element.querySelectorAll('button')).find(found => found.textContent?.trim() === words)!; +const chosen = (): string[] => Array.from(view.element.querySelectorAll('.fw-lib-site-chosen')).map(row => row.firstElementChild?.textContent ?? ''); +const review = (): HTMLElement => view.element.querySelector('.fw-lib-site-review')!; +const importButton = (): HTMLButtonElement => view.element.querySelector('.fw-lib-foot button')!; +const reviews = (): Sent[] => sent.filter(entry => entry.path.endsWith('/api/library/import-site/review')); + +async function pick(files: File[]): Promise { + Object.defineProperty(picker(), 'files', { configurable: true, value: files }); + picker().dispatchEvent(new Event('change')); + await Promise.resolve(); +} + +const html = (name: string, body: string): File => new File([body], name, { type: 'text/html' }); + +async function reviewed(files: File[]): Promise { + await pick(files); + await vi.waitFor(() => expect(review().hidden).toBe(false)); +} + +describe('what the pickers accept', () => { + it('Import HTML files asks the system picker for .html files and allows several at once', () => { + view.choose('html'); + expect(picker().accept).toBe('.html,.htm,text/html'); + expect(picker().multiple).toBe(true); + }); + + it('Import site from zip asks for a zip and also allows loose .html files', () => { + view.choose('site'); + expect(picker().accept).toBe('.zip,application/zip,.html,.htm,text/html'); + expect(picker().multiple).toBe(true); + }); +}); + +describe('which picks are refused', () => { + it('a zip picked together with an .html file is refused with a reason and nothing is sent to the service', async () => { + view.choose('site'); + await pick([new File(['PK'], 'site.zip', { type: 'application/zip' }), html('stopwatch.html', STOPWATCH)]); + expect(note().textContent).toBe(REFUSED); + expect(note().classList.contains('is-error')).toBe(true); + expect(sent).toEqual([]); + expect(importButton().disabled).toBe(true); + }); + + it('a file that is not HTML picked through Import HTML files is refused with the same reason', async () => { + view.choose('html'); + await pick([new File(['shopping list'], 'notes.txt', { type: 'text/plain' })]); + expect(note().textContent).toBe(REFUSED); + expect(sent).toEqual([]); + expect(importButton().disabled).toBe(true); + }); +}); + +describe('loose .html files', () => { + it('one picked file is named in the view and sent for review as its name and text, with no zip', async () => { + view.choose('html'); + await reviewed([html('stopwatch.html', STOPWATCH)]); + expect(chosen()).toEqual(['stopwatch.html']); + expect(reviews()).toEqual([{ path: '/api/library/import-site/review', body: { files: [{ name: 'stopwatch.html', html: STOPWATCH }] } }]); + expect(review().textContent).toContain('stopwatch.html'); + expect(importButton().disabled).toBe(false); + expect(importButton().textContent).toBe('Import 1 page'); + }); + + it('for one file both ways are offered and As new pages is chosen first', async () => { + view.choose('html'); + await reviewed([html('stopwatch.html', STOPWATCH)]); + expect(button('As new pages').getAttribute('aria-checked')).toBe('true'); + expect(button('As a section of this page').disabled).toBe(false); + expect(button('As a section of this page').getAttribute('aria-checked')).toBe('false'); + }); + + it('for two files both are named, As a section is turned off and the note says a section takes one file', async () => { + view.choose('html'); + await reviewed([html('stopwatch.html', STOPWATCH), html('about.html', ABOUT)]); + expect(chosen()).toEqual(['stopwatch.html', 'about.html']); + expect(button('As a section of this page').disabled).toBe(true); + expect(view.element.textContent).toContain(ONE_FILE); + expect(importButton().textContent).toBe('Import 2 pages'); + }); + + it('choosing As a section hides the page review and offers to import a section', async () => { + view.choose('html'); + await reviewed([html('stopwatch.html', STOPWATCH)]); + button('As a section of this page').click(); + expect(review().hidden).toBe(true); + expect(importButton().textContent).toBe('Import as section'); + expect(importButton().disabled).toBe(false); + }); + + it('the view comes forward once files are chosen', async () => { + view.choose('html'); + await reviewed([html('stopwatch.html', STOPWATCH)]); + expect(shown).toBe(1); + }); +}); + +describe('the bring choice', () => { + const heading = (): string => view.element.querySelector('[data-bring="elements"]')!.parentElement!.previousElementSibling!.textContent ?? ''; + + it('there is exactly one choice of editable elements or code sections in the view', async () => { + view.choose('html'); + await reviewed([html('stopwatch.html', STOPWATCH)]); + expect(view.element.querySelectorAll('[data-bring="elements"]').length).toBe(1); + button('As a section of this page').click(); + expect(view.element.querySelectorAll('[data-bring="elements"]').length).toBe(1); + }); + + it('its heading reads Bring pages in as for pages and Bring it in as for a section, on the same mounted choice', async () => { + view.choose('html'); + await reviewed([html('stopwatch.html', STOPWATCH)]); + const choice = view.element.querySelector('[data-bring="elements"]'); + expect(heading()).toBe('Bring pages in as'); + button('As a section of this page').click(); + expect(heading()).toBe('Bring it in as'); + button('As new pages').click(); + expect(heading()).toBe('Bring pages in as'); + expect(view.element.querySelector('[data-bring="elements"]')).toBe(choice); + }); +}); + +describe('starting a new pick', () => { + it('a new pick after a review starts from the clean waiting view: no files, no review, no note', async () => { + view.choose('html'); + await reviewed([html('stopwatch.html', STOPWATCH), html('about.html', ABOUT)]); + view.choose('site'); + expect(chosen()).toEqual([]); + expect(review().hidden).toBe(true); + expect(note().textContent).toBe(''); + expect(importButton().textContent).toBe('Import site'); + expect(importButton().disabled).toBe(true); + }); + + it('a new pick after a refusal clears the refusal', async () => { + view.choose('html'); + await pick([new File(['x'], 'notes.txt')]); + expect(note().textContent).toBe(REFUSED); + view.choose('html'); + expect(note().textContent).toBe(''); + expect(note().classList.contains('is-error')).toBe(false); + }); + + it('the review rows of the earlier pick are replaced by those of the next pick, and the view itself stays mounted', async () => { + const scroller = view.element.firstElementChild; + view.choose('html'); + await reviewed([html('stopwatch.html', STOPWATCH)]); + view.choose('html'); + await reviewed([html('about.html', ABOUT)]); + expect(chosen()).toEqual(['about.html']); + expect(review().textContent).toContain('about.html'); + expect(review().textContent).not.toContain('stopwatch.html'); + expect(view.element.firstElementChild).toBe(scroller); + }); +}); + +describe('the text of a picked page in any of the usual encodings', () => { + const PAGE = 'Café

Crème brûlée à €4,50

“Déjà vu” – naïve façade, Œuvre, señor, Zürich, ‘quoted’.

'; + const WINDOWS_1252: Record = { '€': 0x80, 'Œ': 0x8c, '‘': 0x91, '’': 0x92, '“': 0x93, '”': 0x94, '–': 0x96 }; + const windows1252 = (source: string): Uint8Array => Uint8Array.from(Array.from(source), char => { + const code = char.codePointAt(0)!; + if (code < 0x80 || (code >= 0xa0 && code <= 0xff)) return code; + if (char in WINDOWS_1252) return WINDOWS_1252[char]; + throw new Error(`${char} has no Windows-1252 byte`); + }); + const utf8 = (source: string): Uint8Array => Uint8Array.from(new TextEncoder().encode(source)); + const withMark = (source: string): Uint8Array => Uint8Array.from([0xef, 0xbb, 0xbf, ...utf8(source)]); + const page = (bytes: Uint8Array): File => new File([bytes], 'cafe.html', { type: 'text/html' }); + const parts = (source: string): string[] => { + const read = new DOMParser().parseFromString(source, 'text/html'); + return ['title', 'h1', 'p'].map(tag => read.querySelector(tag)?.textContent ?? ''); + }; + const sentText = (): string => (reviews()[0].body as { files: { html: string }[] }).files[0].html; + + it('a page saved as Windows-1252 is sent for review with its accents, euro sign and curly quotes intact', async () => { + view.choose('html'); + await reviewed([page(windows1252(PAGE))]); + expect(parts(sentText())).toEqual(parts(PAGE)); + expect(sentText()).toBe(PAGE); + expect(sentText()).not.toContain(String.fromCharCode(0xfffd)); + }); + + it('a page saved as UTF-8 is sent unchanged', async () => { + view.choose('html'); + await reviewed([page(utf8(PAGE))]); + expect(parts(sentText())).toEqual(parts(PAGE)); + expect(sentText()).toBe(PAGE); + }); + + it('a page saved as UTF-8 with a byte order mark is sent without the mark', async () => { + view.choose('html'); + await reviewed([page(withMark(PAGE))]); + expect(parts(sentText())).toEqual(parts(PAGE)); + expect(sentText()).toBe(PAGE); + expect(sentText().charCodeAt(0)).not.toBe(0xfeff); + }); + + it('a Windows-1252 page brought in as a section sends the same correctly decoded text', async () => { + view.choose('html'); + await reviewed([page(windows1252(PAGE))]); + button('As a section of this page').click(); + importButton().click(); + await vi.waitFor(() => expect(sent.some(entry => entry.path.endsWith('/api/library/import-html'))).toBe(true)); + const section = (sent.find(entry => entry.path.endsWith('/api/library/import-html'))!.body as { html: string }).html; + expect(parts(section)).toEqual(parts(PAGE)); + expect(section).toBe(PAGE); + }); +}); + +describe('after the review of loose files is refused', () => { + const HIDDEN = 'The file name .hidden.html cannot be imported. Give the file an ordinary name such as about.html. Nothing was imported.'; + const NONE = 'None of the files is an HTML page that can be imported.'; + const imports = (): Sent[] => sent.filter(entry => entry.path.includes('/api/library/import-site?') || entry.path.endsWith('/api/library/import-html')); + const settled = (): Promise => new Promise(resolve => setTimeout(resolve, 0)); + const force = async (): Promise => { + const go = importButton(); + go.dispatchEvent(new MouseEvent('click', { bubbles: true })); + const was = go.disabled; + go.disabled = false; + go.click(); + go.disabled = was; + await settled(); + }; + + async function triedEveryWay(sentence: string): Promise { + await vi.waitFor(() => expect(note().textContent).toBe(sentence)); + expect(importButton().disabled).toBe(true); + await force(); + button('As a section of this page').click(); + expect(importButton().disabled).toBe(true); + await force(); + button('As new pages').click(); + await force(); + expect(imports()).toEqual([]); + expect(note().textContent).toBe(sentence); + } + + it('when the service refuses the review, neither the import button nor the section path sends anything', async () => { + refuse = HIDDEN; + view.choose('html'); + await pick([html('.hidden.html', STOPWATCH)]); + await triedEveryWay(HIDDEN); + }); + + it('when the review finds no importable page, neither the import button nor the section path sends anything', async () => { + noPages = true; + view.choose('html'); + await pick([html('huge.html', STOPWATCH)]); + await triedEveryWay(NONE); + }); + + it('a new pick after a refusal can be imported again', async () => { + refuse = HIDDEN; + view.choose('html'); + await pick([html('.hidden.html', STOPWATCH)]); + await vi.waitFor(() => expect(note().textContent).toBe(HIDDEN)); + refuse = ''; + view.choose('html'); + await reviewed([html('stopwatch.html', STOPWATCH)]); + importButton().click(); + await vi.waitFor(() => expect(imports().map(entry => entry.path.split('?')[0])).toEqual(['/api/library/import-site'])); + }); +}); From b3880e19d3817cf725617a9bdb57b9576b15ac34 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 17:36:13 -0500 Subject: [PATCH 11/31] test(window): Import HTML files from the menu and the Start screen as pages and as a section, a file that is not UTF-8 against the same file in a zip, a refused pick, the Page script block and its panes, and hover outlines with their switch (34 tests) --- frontend/tests/window/test_hover_outline.py | 251 +++++++++++++ .../tests/window/test_import_html_files.py | 351 ++++++++++++++++++ frontend/tests/window/test_page_script.py | 191 ++++++++++ 3 files changed, 793 insertions(+) create mode 100644 frontend/tests/window/test_hover_outline.py create mode 100644 frontend/tests/window/test_import_html_files.py create mode 100644 frontend/tests/window/test_page_script.py diff --git a/frontend/tests/window/test_hover_outline.py b/frontend/tests/window/test_hover_outline.py new file mode 100644 index 00000000..0040790c --- /dev/null +++ b/frontend/tests/window/test_hover_outline.py @@ -0,0 +1,251 @@ +import re + +from playwright.sync_api import expect + +FRAMES = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))" + + +def centre(box, dx=0, dy=0): + return box["x"] + box["width"] / 2 + dx, box["y"] + box["height"] / 2 + dy + + +def on_canvas(editor, key): + return editor.canvas.locator(f'[data-fw-id="{key}"]') + + +def marked(editor): + return editor.canvas.locator("[data-fw-hover]") + + +def marked_rows(editor): + return editor.page.locator("#fw-layers-list .layer-row[data-fw-hover]") + + +def marked_keys(editor): + return marked(editor).evaluate_all("els => els.map(e => e.dataset.fwId)") + + +def settle(editor): + editor.page.evaluate(FRAMES) + + +def nothing_marked(editor, what): + settle(editor) + assert marked_keys(editor) == [], f"{what}: the canvas shows a hover outline on {marked_keys(editor)}" + rows = marked_rows(editor).evaluate_all("rows => rows.map(r => r.dataset.key)") + assert rows == [], f"{what}: the Layers list tints {rows}" + + +def point_at_row(editor, key, dx=0): + editor.layer_row(key).scroll_into_view_if_needed() + editor.page.mouse.move(*centre(editor.layer_row(key).bounding_box(), dx)) + + +def point_at_element(editor, key, dx=0): + editor.page.mouse.move(*centre(on_canvas(editor, key).bounding_box(), dx)) + + +def outline(locator): + return locator.evaluate("e => { const s = getComputedStyle(e); return { style: s.outlineStyle, width: parseFloat(s.outlineWidth) }; }") + + +def layout(editor): + return { + "boxes": editor.canvas.locator("[data-fw-id]").evaluate_all("els => els.slice(0, 80).map(e => { const r = e.getBoundingClientRect(); return [e.dataset.fwId, r.x, r.y, r.width, r.height]; })"), + "scroll": editor.canvas.locator("html").evaluate("e => e.ownerDocument.scrollingElement.scrollTop"), + "selected": editor.page.locator('#fw-layers-list .layer-row[aria-selected="true"]').evaluate_all("rows => rows.map(r => r.dataset.key)"), + "inspector": editor.page.locator(".inspector-name").inner_text(), + } + + +def hover_menu_item(editor): + editor.page.locator('[data-menu="View"]').click() + return editor.page.locator('[role="menu"]:visible [data-command="view.hover-outline"]') + + +def test_resting_on_a_layer_row_outlines_exactly_its_element_thinner_than_the_selection_and_moves_nothing(coldmere): + coldmere.canvas.locator('[data-fw-id="hm-eyebrow"]').click() + expect(coldmere.layer_row("hm-eyebrow")).to_have_attribute("aria-selected", "true") + coldmere.layer_row("hm-lead").scroll_into_view_if_needed() + before = layout(coldmere) + point_at_row(coldmere, "hm-lead") + expect(marked(coldmere)).to_have_count(1) + assert marked_keys(coldmere) == ["hm-lead"] + hover = outline(on_canvas(coldmere, "hm-lead")) + selection = outline(on_canvas(coldmere, "hm-eyebrow")) + assert hover["style"] != "none" and hover["width"] > 0, hover + assert hover["width"] < selection["width"], f"hover outline {hover} is not thinner than the selection outline {selection}" + assert layout(coldmere) == before + coldmere.page.mouse.move(720, 890) + expect(marked(coldmere)).to_have_count(0) + + +def test_resting_on_a_canvas_element_outlines_it_and_tints_its_layer_row_without_scrolling_the_list(coldmere): + row = coldmere.layer_row("hm-lead") + top = coldmere.layer_row("root").bounding_box() + plain = row.evaluate("r => getComputedStyle(r).backgroundColor") + point_at_element(coldmere, "hm-lead") + expect(marked(coldmere)).to_have_count(1) + assert marked_keys(coldmere) == ["hm-lead"] + expect(marked_rows(coldmere)).to_have_count(1) + expect(row).to_have_attribute("data-fw-hover", "") + assert row.evaluate("r => getComputedStyle(r).backgroundColor") != plain + assert coldmere.layer_row("root").bounding_box() == top + point_at_element(coldmere, "hm-h1") + expect(row).not_to_have_attribute("data-fw-hover", "") + assert marked_keys(coldmere) == ["hm-h1"] + + +def test_the_selected_element_never_gets_a_hover_outline(coldmere): + coldmere.canvas.locator('[data-fw-id="hm-lead"]').click() + expect(coldmere.layer_row("hm-lead")).to_have_attribute("aria-selected", "true") + point_at_element(coldmere, "hm-h1") + expect(marked(coldmere)).to_have_count(1) + point_at_element(coldmere, "hm-lead") + expect(marked(coldmere)).to_have_count(0) + nothing_marked(coldmere, "pointing at the selected element") + point_at_row(coldmere, "hm-h1") + expect(marked(coldmere)).to_have_count(1) + point_at_row(coldmere, "hm-lead") + expect(marked(coldmere)).to_have_count(0) + nothing_marked(coldmere, "pointing at the selected row") + + +def test_nothing_is_marked_during_a_canvas_drag(coldmere): + coldmere.canvas.locator('[data-fw-id="hm-lead"]').click() + lead, h1 = on_canvas(coldmere, "hm-lead").bounding_box(), on_canvas(coldmere, "hm-h1").bounding_box() + pointer = coldmere.canvas_pointer() + pointer.move(lead["x"] + 12, lead["y"] + 8) + pointer.down() + pointer.move(h1["x"] + 6, h1["y"] + h1["height"] * 0.3, steps=15, held=True) + expect(coldmere.page.locator("body")).to_have_class(re.compile(r"\bfw-canvas-dragging\b")) + pointer.move(*centre(h1), steps=3, held=True) + nothing_marked(coldmere, "during a canvas drag") + coldmere.page.keyboard.press("Escape") + pointer.up() + expect(coldmere.status).to_have_text("Drag cancelled. Nothing moved.") + pointer.move(*centre(h1, 3), steps=2) + expect(marked(coldmere)).to_have_count(1) + assert marked_keys(coldmere) == ["hm-h1"] + + +def test_nothing_is_marked_during_a_layer_drag(coldmere): + coldmere.layer_row("hm-eyebrow").scroll_into_view_if_needed() + source, target = coldmere.layer_row("hm-lead").bounding_box(), coldmere.layer_row("hm-eyebrow").bounding_box() + coldmere.page.mouse.move(source["x"] + 60, source["y"] + source["height"] / 2) + coldmere.page.mouse.down() + coldmere.page.mouse.move(target["x"] + 60, target["y"] + 4, steps=10) + expect(coldmere.page.locator(".fw-drop-line")).to_be_visible() + coldmere.page.mouse.move(target["x"] + 62, target["y"] + 5) + nothing_marked(coldmere, "during a layer drag") + start = coldmere.site()["site"] + coldmere.page.mouse.up() + coldmere.changed_from(start) + point_at_row(coldmere, "hm-h1", 4) + expect(marked(coldmere)).to_have_count(1) + assert marked_keys(coldmere) == ["hm-h1"] + + +def test_nothing_is_marked_while_text_is_being_edited(coldmere): + coldmere.canvas.locator('[data-fw-id="hm-h1"]').dblclick() + editing = coldmere.canvas.locator('[data-fw-text="hm-h1"][contenteditable="true"]') + expect(editing).to_be_visible() + point_at_element(coldmere, "hm-lead") + nothing_marked(coldmere, "pointing at an element while text is edited") + point_at_row(coldmere, "hm-eyebrow") + nothing_marked(coldmere, "pointing at a row while text is edited") + coldmere.canvas.locator('[data-fw-id="hm-lead"]').click() + expect(coldmere.canvas.locator('[contenteditable="true"]')).to_have_count(0) + point_at_row(coldmere, "hm-eyebrow", 4) + expect(marked(coldmere)).to_have_count(1) + assert marked_keys(coldmere) == ["hm-eyebrow"] + + +def test_nothing_is_marked_while_a_context_menu_is_open(coldmere): + coldmere.canvas.locator('[data-fw-id="hm-h1"]').click(button="right") + expect(coldmere.menu()).to_be_visible() + point_at_row(coldmere, "hm-lead") + nothing_marked(coldmere, "pointing at a row with the canvas menu open") + coldmere.page.keyboard.press("Escape") + expect(coldmere.page.locator('[role="menu"]:visible')).to_have_count(0) + point_at_row(coldmere, "hm-lead", 4) + expect(marked(coldmere)).to_have_count(1) + assert marked_keys(coldmere) == ["hm-lead"] + + +def test_nothing_is_marked_while_quick_insert_is_open(coldmere): + coldmere.page.get_by_role("button", name="Insert element").click() + flyout = coldmere.page.locator('.fw-flyout[aria-label="Quick insert"]') + expect(flyout).to_be_visible() + point_at_element(coldmere, "hm-lead") + nothing_marked(coldmere, "pointing at an element with Quick insert open") + point_at_row(coldmere, "hm-eyebrow") + nothing_marked(coldmere, "pointing at a row with Quick insert open") + coldmere.page.keyboard.press("Escape") + expect(flyout).to_be_hidden() + point_at_element(coldmere, "hm-lead", 4) + expect(marked(coldmere)).to_have_count(1) + assert marked_keys(coldmere) == ["hm-lead"] + + +def test_nothing_is_marked_in_preview_as_published(coldmere): + overlay = coldmere.page.get_by_role("dialog", name="Preview as published") + lead = on_canvas(coldmere, "hm-lead").bounding_box() + row = coldmere.layer_row("hm-h1") + row.scroll_into_view_if_needed() + coldmere.page.locator('[data-cmd="view.preview-full"]').click() + expect(overlay).to_be_visible() + coldmere.page.mouse.move(*centre(lead)) + coldmere.page.mouse.move(*centre(row.bounding_box())) + nothing_marked(coldmere, "in Preview as published") + coldmere.page.keyboard.press("Escape") + expect(overlay).to_be_hidden() + point_at_row(coldmere, "hm-h1", 4) + expect(marked(coldmere)).to_have_count(1) + assert marked_keys(coldmere) == ["hm-h1"] + + +def test_a_pen_pointer_never_marks_anything_where_the_mouse_does(coldmere): + lead = centre(on_canvas(coldmere, "hm-lead").bounding_box()) + coldmere.layer_row("hm-eyebrow").scroll_into_view_if_needed() + row = centre(coldmere.layer_row("hm-eyebrow").bounding_box()) + pen = coldmere.pen() + pen.move(*lead, steps=4) + nothing_marked(coldmere, "a pen resting on an element") + pen.move(*row, steps=4) + nothing_marked(coldmere, "a pen resting on a row") + mouse = coldmere.canvas_pointer() + mouse.move(lead[0] + 3, lead[1], steps=2) + expect(marked(coldmere)).to_have_count(1) + assert marked_keys(coldmere) == ["hm-lead"] + + +def test_show_hover_outlines_is_on_at_first_switches_the_marks_off_survives_a_reload_and_is_never_in_the_site(coldmere): + item = hover_menu_item(coldmere) + expect(item).to_have_attribute("aria-checked", "true") + coldmere.page.keyboard.press("Escape") + point_at_element(coldmere, "hm-lead") + expect(marked(coldmere)).to_have_count(1) + start = coldmere.site() + hover_menu_item(coldmere).click() + expect(coldmere.status).to_have_text("Hover outlines are off.") + point_at_element(coldmere, "hm-h1") + nothing_marked(coldmere, "with hover outlines off") + point_at_row(coldmere, "hm-eyebrow") + nothing_marked(coldmere, "pointing at a row with hover outlines off") + coldmere.page.reload() + coldmere.page.get_by_role("button", name="Back to Editor").click() + coldmere.page_row("services").wait_for() + coldmere.canvas.locator('[data-fw-id="root"]').wait_for() + expect(on_canvas(coldmere, "hm-lead")).to_be_visible() + expect(hover_menu_item(coldmere)).to_have_attribute("aria-checked", "false") + coldmere.page.keyboard.press("Escape") + point_at_element(coldmere, "hm-lead", 3) + nothing_marked(coldmere, "after a reload with hover outlines off") + assert coldmere.site() == start + hover_menu_item(coldmere).click() + expect(coldmere.status).to_contain_text("Hover outlines are on") + point_at_element(coldmere, "hm-h1", 3) + expect(marked(coldmere)).to_have_count(1) + assert coldmere.site() == start + diff --git a/frontend/tests/window/test_import_html_files.py b/frontend/tests/window/test_import_html_files.py new file mode 100644 index 00000000..22da404b --- /dev/null +++ b/frontend/tests/window/test_import_html_files.py @@ -0,0 +1,351 @@ +import io +import json +import urllib.error +import urllib.request +import zipfile + +import pytest +from playwright.sync_api import expect + + +def html_page(title, heading): + return f"""{title}

{heading}

From 1 October the Gull Island boat sails at weekends only.

""" + + +def html_file(tmp_path, name, title, heading=None): + path = tmp_path / name + path.write_text(html_page(title, heading or title), "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 code_sections(site): + return (site.get("extensions", {}).get("code") or {}).get("sections") or {} + + +def parents(site): + return {child: node["id"] for node in site["nodes"].values() for child in node["children"]} + + +def added_tops(before, after): + new = set(after["nodes"]) - set(before["nodes"]) + up = parents(after) + return [key for key in new if up.get(key) not in new] + + +def open_page(editor, site): + key = editor.page.locator('#fw-pages-list .list-row[aria-current="page"]').get_attribute("data-key") + return next(p for p in site["pages"] if p["id"] == key) + + +def pick(editor, command, *paths): + 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 service_review(editor, path): + request = urllib.request.Request(editor.base + "/api/library/import-site/review", data=path.read_bytes(), method="POST", headers={"Content-Type": "application/zip", "X-FormWeb-Window-Key": editor.window_key}) + try: + with urllib.request.urlopen(request, timeout=30) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as error: + return error.code, json.loads(error.read())["detail"] + + +def box(locator): + found = locator.bounding_box() + return found["y"], found["height"] + + +def expect_clean_site_view(view): + expect(view).to_be_visible() + expect(view.locator(".fw-lib-site-review")).to_be_hidden() + expect(view.locator(".fw-lib-site-chosen")).to_have_count(0) + expect(view.locator(".fw-lib-note")).to_have_text("") + expect(view.locator(".fw-lib-insert")).not_to_contain_text("Imported") + expect(view.locator(".fw-lib-insert")).to_be_disabled() + + +def test_file_import_html_files_from_the_menu_opens_the_file_picker_for_several_html_files_with_the_library_behind_it(harbour): + harbour.page.locator('[data-menu="File"]').click() + with harbour.page.expect_file_chooser() as chooser: + harbour.page.locator('[role="menu"]:visible [data-command="file.import-html"]').click() + assert chooser.value.is_multiple() + accepted = chooser.value.element.get_attribute("accept").split(",") + assert ".html" in accepted and ".zip" not in accepted + expect(harbour.page.locator(".fw-lib-import-part").first).to_be_visible() + + +def test_from_the_start_screen_one_html_file_becomes_a_new_page_at_its_own_address_and_one_undo_of_the_code_import_takes_it_away(editor, tmp_path): + expect(editor.page.locator('[data-demo="harbour-ferries"]')).to_be_visible() + before = editor.site()["site"] + view = pick(editor, "file.import-html", html_file(tmp_path, "opening-hours.html", "Opening hours")) + expect(editor.page.locator('[data-demo="harbour-ferries"]')).to_be_hidden() + review = view.locator(".fw-lib-site-review") + expect(review).to_be_visible() + expect(review.locator(".fw-lib-site-item")).to_have_count(1) + expect(review.locator(".fw-lib-site-item")).to_contain_text("Opening hours") + expect(review.locator(".fw-lib-site-item")).to_contain_text("opening-hours.html") + expect(review.locator(".fw-lib-site-item")).to_contain_text("/opening-hours") + view.locator('[data-bring="code"]').click() + view.locator(".fw-lib-insert:not([disabled])").click() + expect(view.locator(".fw-lib-note")).to_contain_text("Imported 1 page") + after = editor.until(lambda s: len(s["pages"]) == len(before["pages"]) + 1, "one more page") + assert "Opening hours" in editor.page_names(after) + editor.page.evaluate("window.formweb.run('edit.undo')") + editor.restored_to(before) + expect_clean_site_view(view) + + +def test_two_html_files_picked_at_once_become_two_new_pages_and_as_a_section_is_not_offered(harbour, tmp_path): + before = harbour.site()["site"] + view = pick(harbour, "file.import-html", html_file(tmp_path, "winter-timetable.html", "Winter timetable"), html_file(tmp_path, "lost-property.html", "Lost property")) + expect(view.locator(".fw-lib-site-chosen")).to_have_count(2) + expect(view.get_by_role("radio", name="As a section of this page")).to_be_disabled() + expect(view.get_by_role("radio", name="As new pages", exact=True)).to_have_attribute("aria-checked", "true") + rows = view.locator(".fw-lib-site-review .fw-lib-site-item") + expect(rows).to_have_count(2) + expect(view.locator(".fw-lib-site-review")).to_contain_text("/winter-timetable") + expect(view.locator(".fw-lib-site-review")).to_contain_text("/lost-property") + view.locator('[data-bring="code"]').click() + view.locator(".fw-lib-insert:not([disabled])").click() + expect(view.locator(".fw-lib-note")).to_contain_text("Imported 2 pages") + after = harbour.until(lambda s: len(s["pages"]) == len(before["pages"]) + 2, "two more pages") + assert {"Winter timetable", "Lost property"} <= set(harbour.page_names(after)) + + +def test_one_html_file_as_a_section_lands_in_the_open_page_in_view_and_the_note_speaks_of_the_section(harbour, tmp_path): + before = harbour.site()["site"] + page = open_page(harbour, before) + last = before["nodes"][page["root"]]["children"][-1] + expect(harbour.canvas.locator(f'[data-fw-id="{last}"]')).not_to_be_in_viewport() + view = pick(harbour, "file.import-html", html_file(tmp_path, "winter-notice.html", "Winter notice", "Winter timetable")) + 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") + view.locator(".fw-lib-insert:not([disabled])").click() + expect(view.locator(".fw-lib-note")).to_contain_text("section") + expect(view.locator(".fw-lib-note")).not_to_contain_text("pages") + after = harbour.until(lambda s: len(added_tops(before, s)) == 1 and any(n["text"] == "Winter timetable" for n in s["nodes"].values()), "one new section") + assert len(after["pages"]) == len(before["pages"]), "a section import must not add a page" + section = added_tops(before, after)[0] + up = parents(after) + top = section + while top in up: + top = up[top] + assert top == page["root"], f"the new section belongs to the page with root {top}, not the open page {page['name']}" + branch = section + while up[branch] != page["root"]: + branch = up[branch] + order = after["nodes"][page["root"]]["children"] + assert order.index(branch) > order.index(last), "the section was expected below the part of the page that was off screen" + expect(harbour.canvas.locator(f'[data-fw-id="{section}"]')).to_be_in_viewport() + expect(harbour.canvas.locator(f'[data-fw-id="{section}"]')).to_have_attribute("data-fw-selected", "") + + +def test_import_site_from_zip_takes_a_loose_html_file_and_makes_it_a_new_page(harbour, tmp_path): + before = harbour.site()["site"] + with harbour.page.expect_file_chooser() as chooser: + harbour.page.evaluate("window.formweb.run('file.import-site')") + accepted = chooser.value.element.get_attribute("accept").split(",") + assert ".zip" in accepted and ".html" in accepted + chooser.value.set_files(str(html_file(tmp_path, "ferry-tickets.html", "Ferry tickets"))) + view = harbour.page.locator(".fw-lib-site") + expect(view.locator(".fw-lib-site-review")).to_contain_text("/ferry-tickets") + view.locator('[data-bring="code"]').click() + view.locator(".fw-lib-insert:not([disabled])").click() + after = harbour.until(lambda s: len(s["pages"]) == len(before["pages"]) + 1, "one more page") + assert "Ferry tickets" in harbour.page_names(after) + + +def test_the_library_import_view_has_html_files_a_site_zip_and_pasted_html_and_the_paste_part_still_imports_a_section(harbour): + before = harbour.site()["site"] + with harbour.page.expect_file_chooser(): + harbour.page.evaluate("window.formweb.run('file.import-html')") + harbour.page.keyboard.press("Escape") + parts = harbour.page.locator(".fw-lib-import:not(.fw-lib-site) .fw-lib-import-part") + expect(parts).to_have_count(3) + expect(parts.locator("> h3")).to_have_text(["HTML files", "A whole site in a .zip", "Paste HTML code"]) + expect(parts.nth(0).get_by_role("button", name="Choose .html files...")).to_be_visible() + expect(parts.nth(1).get_by_role("button", name="Choose a .zip file...")).to_be_visible() + paste = parts.nth(2) + paste.get_by_placeholder("").fill(html_page("Winter notice", "Winter timetable")) + paste.locator('[data-bring="code"]').click() + paste.get_by_role("button", name="Import as section").click() + expect(paste.locator(".fw-lib-note")).to_have_text("HTML section imported.") + after = harbour.until(lambda s: len(code_sections(s)) == len(code_sections(before)) + 1, "one new code section") + assert len(after["pages"]) == len(before["pages"]) + + +def test_a_zip_of_a_projects_source_is_refused_with_the_services_own_sentence_and_the_site_is_unchanged(harbour, tmp_path): + source = zip_file(tmp_path, "shop-source.zip", { + "package.json": json.dumps({"name": "shop", "scripts": {"build": "vite build"}}), + "index.html": '
', + "src/main.tsx": "export const app = 1;", + }) + before = harbour.site() + with harbour.page.expect_file_chooser() as chooser: + harbour.page.evaluate("window.formweb.run('file.import-site')") + chooser.value.set_files(str(source)) + view = harbour.page.locator(".fw-lib-site") + expect(view.locator(".fw-lib-note")).to_contain_text("Nothing was imported.") + status, sentence = service_review(harbour, source) + assert status == 400, f"the service accepted a project's source: {sentence}" + assert "Build it first" in sentence and sentence.endswith("Nothing was imported.") + expect(view.locator(".fw-lib-note")).to_have_text(sentence) + expect(view.locator(".fw-lib-site-review")).to_be_hidden() + expect(view.locator(".fw-lib-insert")).to_be_disabled() + assert harbour.site() == before, "the refused zip changed the site" + + +def test_a_pick_that_mixes_a_zip_with_an_html_file_is_refused_with_one_sentence_and_nothing_is_sent(harbour, tmp_path): + site_zip = zip_file(tmp_path, "site.zip", {"index.html": html_page("Home", "Welcome")}) + loose = html_file(tmp_path, "extra.html", "Extra") + sent = [] + harbour.page.on("request", lambda r: sent.append(r.url) if "/api/library/import-site" in r.url else None) + before = harbour.site() + view = pick(harbour, "file.import-site", site_zip, loose) + expect(view.locator(".fw-lib-note")).to_have_text("Choose one .zip file, or one or more .html files.") + expect(view.locator(".fw-lib-site-review")).to_be_hidden() + expect(view.locator(".fw-lib-insert")).to_be_disabled() + assert sent == [], f"the mixed pick was sent to the service: {sent}" + assert harbour.site() == before, "the refused pick changed the site" + + +def test_the_review_of_a_zip_says_how_many_files_in_system_and_dependency_folders_were_ignored(harbour, tmp_path): + archive = zip_file(tmp_path, "with-folders.zip", { + "index.html": html_page("Home", "Welcome"), + "node_modules/left/index.js": "module.exports = 1;", + "node_modules/right/index.js": "module.exports = 2;", + "__MACOSX/._index.html": "x", + }) + view = pick(harbour, "file.import-site", archive) + expect(view.locator(".fw-lib-site-review")).to_contain_text("3 files in system and dependency folders are ignored.") + + +def test_a_second_import_starts_from_a_clean_view_with_no_earlier_review_note_or_greyed_button_behind_the_picker(harbour, tmp_path): + before = harbour.site()["site"] + view = pick(harbour, "file.import-site", zip_file(tmp_path, "first.zip", {"timetable.html": html_page("Timetable", "Sailings")})) + view.locator('[data-bring="code"]').click() + view.locator(".fw-lib-insert:not([disabled])").click() + expect(view.locator(".fw-lib-insert")).to_contain_text("Imported") + harbour.until(lambda s: len(s["pages"]) == len(before["pages"]) + 1, "the first import") + with harbour.page.expect_file_chooser() as chooser: + harbour.page.evaluate("window.formweb.run('file.import-site')") + expect_clean_site_view(view) + chooser.value.set_files(str(zip_file(tmp_path, "second.zip", {"fares.html": html_page("Fares", "Prices")}))) + rows = view.locator(".fw-lib-site-review .fw-lib-site-item") + expect(rows).to_have_count(1) + expect(rows).to_contain_text("fares.html") + expect(view.locator(".fw-lib-note")).to_have_text("") + with harbour.page.expect_file_chooser(): + harbour.page.evaluate("window.formweb.run('file.import-html')") + expect(view).to_be_hidden() + expect(harbour.page.locator(".fw-lib-import:not(.fw-lib-site) .fw-lib-import-part").first).to_be_visible() + + +def test_nothing_above_the_review_or_a_refusal_moves_when_it_appears(harbour, tmp_path): + with harbour.page.expect_file_chooser() as chooser: + harbour.page.evaluate("window.formweb.run('file.import-site')") + view = harbour.page.locator(".fw-lib-site") + choose = view.locator(".fw-lib-choose:not(.fw-lib-site-back)") + files = view.locator(".fw-lib-site-files") + button = view.locator(".fw-lib-insert") + expect(choose).to_be_visible() + places = lambda: {"choose button (top, height)": box(choose), "chosen-file list top": box(files)[0], "import button (top, height)": box(button)} + waiting = places() + chooser.value.set_files(str(zip_file(tmp_path, "two.zip", {"a.html": html_page("Alpha", "A"), "b.html": html_page("Beta", "B")}))) + expect(view.locator(".fw-lib-site-review .fw-lib-site-item")).to_have_count(2) + assert places() == waiting, "something above the review moved when the review appeared" + refused = zip_file(tmp_path, "notes.zip", {"package.json": "{}", "src/app.js": "x"}) + with harbour.page.expect_file_chooser() as chooser: + harbour.page.evaluate("window.formweb.run('file.import-site')") + assert places() == waiting, "the view behind the second picker is not laid out as the first waiting view" + chooser.value.set_files(str(refused)) + expect(view.locator(".fw-lib-note")).to_contain_text("Nothing was imported.") + assert places() == waiting, "something moved when the refusal appeared" + + +HEADING = "Crème brûlée à €4,50" +PARAGRAPH = "“Déjà vu” – naïve façade, Œuvre, señor, Zürich, ‘quoted’." + + +def encoded_page(title, encoding): + return f"{title}

{HEADING}

{PARAGRAPH}

".encode(encoding) + + +def import_as_code(editor, view, what): + before = code_sections(editor.site()["site"]) + 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) + 1, what) + added = [record for key, record in code_sections(site).items() if key not in before] + return site, added[0]["html"] + + +@pytest.mark.parametrize("encoding", ["windows-1252", "utf-8-sig"]) +def test_a_picked_html_file_not_in_plain_utf8_arrives_with_the_same_text_as_inside_a_zip_as_a_page_and_as_a_section(harbour, tmp_path, encoding): + title = "Café " + encoding + data = encoded_page(title, encoding) + assert data.startswith(b"\xef\xbb\xbf") if encoding == "utf-8-sig" else b"\x80" in data and b"\x93" in data + archive = tmp_path / "zipped.zip" + with zipfile.ZipFile(archive, "w") as handle: + handle.writestr("zipped.html", data) + loose = tmp_path / "loose.html" + loose.write_bytes(data) + _, zipped = import_as_code(harbour, pick(harbour, "file.import-site", archive), "the zipped page") + site, as_page = import_as_code(harbour, pick(harbour, "file.import-html", loose), "the picked file as a page") + view = pick(harbour, "file.import-html", loose) + view.get_by_role("radio", name="As a section of this page").click() + _, as_section = import_as_code(harbour, view, "the picked file as a section") + for path, html in (("inside a zip", zipped), ("picked as a page", as_page), ("picked as a section", as_section)): + assert HEADING in html and PARAGRAPH in html, f"{path}, the text did not arrive as written: {html[:300]!r}" + assert "�" not in html and "" not in html, f"{path}, a replacement or byte order mark character was stored: {html[:300]!r}" + assert as_page == zipped, "the picked page differs from the same bytes imported inside a zip" + assert [name for name in harbour.page_names(site) if name.startswith("Caf")] == [title, title] + + +def test_after_the_service_refuses_a_picked_file_the_sentence_stays_in_view_nothing_can_be_imported_and_a_new_pick_works(harbour, tmp_path): + hidden = tmp_path / ".hidden.html" + hidden.write_text(html_page("Hidden", "Hidden"), "utf-8") + before = harbour.site() + view = pick(harbour, "file.import-html", hidden) + note = view.locator(".fw-lib-note") + expect(note).to_contain_text("Nothing was imported.") + request = urllib.request.Request(harbour.base + "/api/library/import-site/review", data=json.dumps({"files": [{"name": ".hidden.html", "html": hidden.read_text("utf-8")}]}).encode(), method="POST", headers={"Content-Type": "application/json", "X-FormWeb-Window-Key": harbour.window_key}) + try: + urllib.request.urlopen(request, timeout=30) + raise AssertionError("the service accepted a file whose name starts with a dot") + except urllib.error.HTTPError as error: + sentence = json.loads(error.read())["detail"] + expect(note).to_have_text(sentence) + expect(note).to_be_in_viewport() + button = view.locator(".fw-lib-insert") + expect(button).to_be_disabled() + 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(button).to_be_disabled() + expect(note).to_have_text(sentence) + expect(note).to_be_in_viewport() + assert harbour.site() == before, "the refused file changed the site" + with harbour.page.expect_file_chooser() as chooser: + view.locator(".fw-lib-choose:not(.fw-lib-site-back)").click() + chooser.value.set_files(str(html_file(tmp_path, "harbour-walk.html", "Harbour walk"))) + expect(note).to_have_text("") + expect(view.locator(".fw-lib-site-review")).to_contain_text("/harbour-walk") + view.locator('[data-bring="code"]').click() + view.locator(".fw-lib-insert:not([disabled])").click() + after = harbour.until(lambda s: len(s["pages"]) == len(before["site"]["pages"]) + 1, "the new pick to import one page") + assert "Harbour walk" in harbour.page_names(after) diff --git a/frontend/tests/window/test_page_script.py b/frontend/tests/window/test_page_script.py new file mode 100644 index 00000000..f469963c --- /dev/null +++ b/frontend/tests/window/test_page_script.py @@ -0,0 +1,191 @@ +import re + +import pytest +from playwright.sync_api import expect + +SCRIPT = "document.getElementById('ps-target').textContent = 'The page script ran'" +NOTE = "A page script has no box on the page, so these settings do not apply to it." +CONTROLS = "input:visible, select:visible, textarea:visible, button:visible" + + +def element(key, name, tag="div", text="", attrs=None, styles=None): + return {"id": key, "tag": tag, "name": name, "text": text, "children": [], "attrs": attrs or {}, "styles": styles or {}, "breakpoints": {}} + + +@pytest.fixture +def old_script(coldmere): + coldmere.command(None, [ + {"command": "code.sections.allow", "params": {"enabled": True}}, + {"command": "node.add", "params": {"parent": "hm-hero-copy", "node": element("ps-target", "Target", "p", "Waiting", {"id": "ps-target"})}}, + {"command": "node.add", "params": {"parent": "hm-hero-copy", "node": element("old-script", "Old script", styles={"display": "contents"})}}, + {"command": "code.section.set", "params": {"node": "old-script", "value": {"enabled": True, "html": "", "js": SCRIPT}}}, + {"command": "node.add", "params": {"parent": "hm-hero-copy", "node": element("old-code", "Old code", styles={"display": "contents"})}}, + {"command": "code.section.set", "params": {"node": "old-code", "value": {"enabled": True, "html": "

Kept as code

", "css": ""}}}, + ], batch=True) + coldmere.until(lambda site: "old-code" in site["nodes"], "the old-way page script and code section") + expect(block(coldmere, "old-script")).to_be_visible() + expect(coldmere.layer_row("old-script")).to_be_visible() + return coldmere + + +def block(editor, key): + return editor.canvas.locator(f'[data-fw-id="{key}"] > [data-fw-poster]') + + +def click_block(editor, key, button="left"): + box = block(editor, key).bounding_box() + editor.page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2, button=button) + + +def tab(editor, name): + return editor.page.locator(".inspector button.quiet", has_text=name) + + +def is_open(editor, name): + expect(tab(editor, name)).to_have_class(re.compile(r"\bactive\b")) + + +def selected(editor): + return editor.page.locator('#fw-layers-list .layer-row[aria-selected="true"]').evaluate_all("rows => rows.map(r => r.dataset.key)") + + +def drawn_icon(editor, key): + return editor.layer_row(key).locator(":scope > .icon").evaluate("i => [...i.querySelectorAll('svg')].filter(s => s.getClientRects().length).map(s => s.innerHTML)") + + +def outline(locator): + return locator.evaluate("e => { const s = getComputedStyle(e); return [s.outlineStyle, s.outlineWidth, s.outlineColor]; }") + + +def script_box(editor): + boxes = editor.page.locator(".inspector-scroll textarea") + values = boxes.evaluate_all("ts => ts.map(t => t.value)") + assert SCRIPT in values, f"no field in the right panel holds the script; the text fields hold {values}" + return boxes.nth(values.index(SCRIPT)) + + +def menu_entries(editor): + return [item.inner_text().split("\n")[0] for item in editor.menu().locator('[role="menuitem"]').all()] + + +def test_a_script_only_code_section_made_the_old_way_is_shown_on_the_canvas_as_a_page_script_block(old_script): + words = block(old_script, "old-script").inner_text().split("\n") + assert words[0] == "Page script" + assert "Runs in Preview and on the published site, not on this canvas." in words + expect(old_script.canvas.locator("#ps-target")).to_have_text("Waiting") + + +def test_clicking_the_page_script_block_selects_its_layer_and_the_block_shows_the_selection_outline(old_script): + start = old_script.site()["site"] + old_script.canvas.locator('[data-fw-id="hm-lead"]').click() + expect(old_script.layer_row("hm-lead")).to_have_attribute("aria-selected", "true") + selection = outline(old_script.canvas.locator('[data-fw-id="hm-lead"]')) + assert outline(block(old_script, "old-script")) != selection + click_block(old_script, "old-script") + expect(old_script.layer_row("old-script")).to_have_attribute("aria-selected", "true") + expect(old_script.page.locator(".inspector-name")).to_have_text("Old script") + assert selected(old_script) == ["old-script"] + assert outline(block(old_script, "old-script")) == selection + after = old_script.site()["site"] + assert after["nodes"]["old-script"] == start["nodes"]["old-script"] + assert after["extensions"]["code"]["sections"]["old-script"] == start["extensions"]["code"]["sections"]["old-script"] + + +def test_the_page_script_layer_row_shows_its_own_icon_and_ordinary_rows_do_not(old_script): + script = drawn_icon(old_script, "old-script") + ordinary = [drawn_icon(old_script, key) for key in ("hm-lead", "hm-btns", "ps-target")] + assert len(script) == 1 and all(len(icon) == 1 for icon in ordinary) + assert all(icon == ordinary[0] for icon in ordinary) + assert script != ordinary[0], "the Page script row draws the same icon as an ordinary element" + assert script != drawn_icon(old_script, "old-code"), "the Page script row draws the same icon as a code section with HTML" + + +def test_a_selected_page_script_shows_its_code_on_content_and_only_the_note_on_design_and_motion(old_script): + old_script.canvas.locator('[data-fw-id="hm-h1"]').click() + tab(old_script, "Motion").click() + is_open(old_script, "Motion") + click_block(old_script, "old-script") + expect(old_script.layer_row("old-script")).to_have_attribute("aria-selected", "true") + is_open(old_script, "Content") + expect(script_box(old_script)).to_be_in_viewport() + for name in ("Design", "Motion"): + tab(old_script, name).click() + is_open(old_script, name) + expect(old_script.page.locator(".inspector-scroll").locator(CONTROLS)).to_have_count(0) + shown = old_script.page.locator(".inspector-scroll").inner_text().strip() + assert shown == NOTE, f"{name} shows {shown[:300]!r}" + + +def test_selecting_an_ordinary_element_after_the_page_script_brings_the_controls_and_the_earlier_tab_back(old_script): + old_script.canvas.locator('[data-fw-id="hm-h1"]').click() + tab(old_script, "Motion").click() + is_open(old_script, "Motion") + controls = old_script.page.locator(".inspector-scroll").locator(CONTROLS) + expect(controls.first).to_be_visible() + click_block(old_script, "old-script") + is_open(old_script, "Content") + old_script.canvas.locator('[data-fw-id="hm-lead"]').click() + expect(old_script.layer_row("hm-lead")).to_have_attribute("aria-selected", "true") + is_open(old_script, "Motion") + expect(controls.first).to_be_visible() + expect(old_script.page.locator(".inspector-scroll").get_by_text(NOTE, exact=True).locator("visible=true")).to_have_count(0) + tab(old_script, "Design").click() + is_open(old_script, "Design") + expect(controls.first).to_be_visible() + expect(old_script.page.locator(".inspector-scroll").get_by_text(NOTE, exact=True).locator("visible=true")).to_have_count(0) + + +def test_the_page_script_menu_has_no_background_spacing_or_size_while_an_ordinary_elements_menu_has_them(old_script): + design = {"Background", "Spacing", "Size"} + click_block(old_script, "old-script", button="right") + expect(old_script.menu()).to_be_visible() + script = menu_entries(old_script) + old_script.page.keyboard.press("Escape") + assert selected(old_script) == ["old-script"] + assert {"Copy", "Delete", "Rename", "Select parent"} <= set(script), script + assert not design & set(script), script + old_script.canvas.locator('[data-fw-id="hm-lead"]').click(button="right") + expect(old_script.menu()).to_be_visible() + ordinary = menu_entries(old_script) + old_script.page.keyboard.press("Escape") + assert design <= set(ordinary), ordinary + + +def test_a_code_section_with_html_reads_code_section_and_a_click_on_its_block_goes_to_the_element_around_it(old_script): + expect(block(old_script, "old-code")).to_have_text("Code section") + click_block(old_script, "old-code") + expect(old_script.layer_row("hm-hero-copy")).to_have_attribute("aria-selected", "true") + assert selected(old_script) == ["hm-hero-copy"] + + +def test_a_heading_dragged_onto_the_page_script_block_is_never_dropped_inside_it(old_script): + start = old_script.site()["site"] + old_script.canvas.locator('[data-fw-id="hm-h1"]').click() + expect(old_script.layer_row("hm-h1")).to_have_attribute("aria-selected", "true") + source = old_script.canvas.locator('[data-fw-id="hm-h1"]').bounding_box() + target = block(old_script, "old-script").bounding_box() + pointer = old_script.canvas_pointer() + pointer.move(source["x"] + 12, source["y"] + 8) + pointer.down() + pointer.move(target["x"] + target["width"] / 2, target["y"] + target["height"] / 2, steps=15, held=True) + where = old_script.page.locator(".fw-canvas-proxy-where") + expect(where).to_have_text(re.compile(r"\S")) + landing = where.inner_text() + assert not landing.startswith("Inside Old script"), landing + pointer.up() + expect(old_script.page.locator("body")).not_to_have_class(re.compile(r"\bfw-canvas-dragging\b")) + if landing == "Stays where it is": + assert old_script.site()["site"] == start + else: + old_script.changed_from(start) + assert old_script.site()["site"]["nodes"]["old-script"]["children"] == [] + + +def test_the_page_script_runs_in_preview_as_published(old_script): + expect(old_script.canvas.locator("#ps-target")).to_have_text("Waiting") + old_script.page.locator('[data-cmd="view.preview-full"]').click() + overlay = old_script.page.get_by_role("dialog", name="Preview as published") + expect(overlay).to_be_visible() + shown = overlay.locator("iframe.fw-fp-frame:visible") + expect(shown).to_have_count(1) + expect(overlay.frame_locator("iframe.fw-fp-frame:visible").locator("#ps-target")).to_have_text("The page script ran") From 7796fe08c5c3389df9adc564f7f80ccf3dc614f0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 17:36:13 -0500 Subject: [PATCH 12/31] test(desktop): the start-up line names four times in milliseconds, a service found already running and each moment that was not reached (6 tests) --- src-tauri/src/start_times.rs | 64 ++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/src-tauri/src/start_times.rs b/src-tauri/src/start_times.rs index e906d67a..bcf99045 100644 --- a/src-tauri/src/start_times.rs +++ b/src-tauri/src/start_times.rs @@ -28,3 +28,67 @@ pub fn line(started: Option, ready: Option, editor: Option Option { + Some(Duration::from_millis(value)) + } + + #[test] + fn the_start_up_line_names_the_four_moments_in_milliseconds_in_order() { + assert_eq!( + line(ms(140), ms(1980), ms(2510), ms(2735)), + "[formweb] start-up: service started 140 ms, service ready 1980 ms, editor ready 2510 ms, window shown 2735 ms" + ); + } + + #[test] + fn a_service_found_already_running_is_said_to_be_already_running() { + assert_eq!( + line(None, ms(40), ms(610), ms(830)), + "[formweb] start-up: service already running, service ready 40 ms, editor ready 610 ms, window shown 830 ms" + ); + } + + #[test] + fn an_editor_that_never_reported_ready_is_named_as_not_reached_when_the_fallback_shows_the_window() { + assert_eq!( + line(ms(118), ms(2201), None, ms(22150)), + "[formweb] start-up: service started 118 ms, service ready 2201 ms, editor ready not reached, window shown 22150 ms" + ); + } + + #[test] + fn every_moment_that_was_never_reached_is_named_as_not_reached() { + assert_eq!( + line(None, None, None, None), + "[formweb] start-up: service started not reached, service ready not reached, editor ready not reached, window shown not reached" + ); + assert_eq!( + line(ms(90), None, None, None), + "[formweb] start-up: service started 90 ms, service ready not reached, editor ready not reached, window shown not reached" + ); + } + + #[test] + fn a_part_of_a_millisecond_is_cut_off_and_never_rounded_up() { + assert_eq!( + line(Some(Duration::from_micros(99_999)), ms(0), ms(1), ms(2)), + "[formweb] start-up: service started 99 ms, service ready 0 ms, editor ready 1 ms, window shown 2 ms" + ); + } + + #[test] + fn a_moment_already_recorded_keeps_its_first_time_when_it_is_marked_again() { + let moment = OnceLock::new(); + moment.set(Duration::from_secs(86_400)).unwrap(); + mark(&moment); + assert_eq!(moment.get(), Some(&Duration::from_secs(86_400))); + let fresh = OnceLock::new(); + mark(&fresh); + assert!(fresh.get().is_some()); + } +} From c76f5e4937513a6154c1bb0c944aa6bef9353829 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 17:36:13 -0500 Subject: [PATCH 13/31] docs(changelog): 0.32.0, Import HTML files, the site import's counting and source-project advice, the Page script, hover outlines and the desktop start --- CHANGELOG.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64ae8c5c..9ac4d94b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 0.32.0 · 2026-11-26 + +- The first of five releases that answer the follow-up on issue #36: what the reporter ran into when importing, on the canvas and at start-up. +- File > Import HTML files... (the menu item was Import HTML...) opens the file picker at once, from the File menu and from the command search, also while the Start screen is showing and when the left panel is closed. You can pick one or several `.html` files. They become new pages through the same review and one-undo-step import as a site zip, so no zip is needed; or, when you pick exactly one file, it can go into the open page as a section (As new pages or As a section of this page). A section brought in this way, or pasted, is selected and scrolled into view on the canvas, and so is a section inserted from the Library. Each file is read as UTF-8, or as Windows-1252 when it is not valid UTF-8, the same as a page inside a zip. +- The Library's import view is now three separate parts, each with one sentence: HTML files, A whole site in a .zip, and Paste HTML code. Import site from zip... also takes loose `.html` files. +- A site import counts only the files outside system and dependency folders (`node_modules`, `__MACOSX` and folders whose name starts with a dot): at most 1,000 such files, out of at most 40,000 entries in the whole zip. The 12-folder depth limit also applies only to those files, so a zip that holds a site and its dependencies is reviewed instead of refused, and the review says how many files in system and dependency folders it ignored. The other limits are unchanged: 64 MiB of zip, 100 pages and 128 MiB unpacked. +- A zip of a project's source rather than a finished site is refused with advice. That is a zip with a `package.json` and something only a build turns into a page: no HTML page, `.ts`, `.tsx`, `.jsx`, `.vue` or `.svelte` files in its `src` folder or loaded by a page, a `%PUBLIC_URL%` placeholder in a page, or a script that loads a package by name with no import map. The advice is: build it first, then zip the output folder (often `dist` or `build`) and import that. When the zip already holds a built copy in such a folder, the sentence names it. A finished site that only has a `package.json` beside its pages, or plain `.js` files, is imported, with `package.json` skipped. +- A refusal for too many files or too large a zip now says what to do, for example zip only the folder that holds the finished site. +- A script imported without any HTML of its own is now a Page script, with one name on the layer and on the canvas and its own icon in Layers. On the canvas it is a block that reads Page script, with "Runs in Preview and on the published site, not on this canvas." under it; click it to select its layer, and it shows the selection outline. The right panel then opens the Content tab on its code, and Design and Motion say that these settings do not apply to it. Its right-click menu no longer offers Text style, Background, Spacing or Size. Other code sections on the canvas now read Code section instead of Component. +- Hover outlines: 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, the element is outlined and its layer row is tinted. Nothing scrolls and nothing is selected. Nothing shows while you drag, edit text, have a menu open or are in Preview. View > Show hover outlines turns them off or on again; they are on at first and the choice is remembered in this browser. +- Desktop app: the window shows as soon as the editor is ready, after a minimum of 0.5 s instead of 2.6 s. The app writes one start-up line to its error output, `[formweb] start-up:` with the times at which the service started, the service was ready, the editor was ready and the window was shown; `docs/DESKTOP_TESTING.md` says how to read it on Windows and macOS. +- Agents: the `library_import_site` tool now states the new limits (1,000 files outside `node_modules`, `__MACOSX` and dot folders, 40,000 entries in all) and that a project's source is refused, and `file.import-html` in the command list describes the picker and the two choices. +- Fixed: a site zip that held its `node_modules` folder was refused as having too many entries, or folders nested too deep, although those folders are left out of the import. +- Fixed: a long warning in the site import review ran out of its box; it now wraps. +- Every refusal of a site import now ends by saying that nothing was imported. +- Automated tests at four layers: 182 engine tests, 612 service tests, 391 editor function tests and 205 tests that drive the real editor window. Of these, 99 service tests, 62 editor function tests and 34 window tests are new and cover this release. Each was written after its feature had been run and seen to work, and each was seen to fail against 0.31.2 before it was accepted. Six more tests in the desktop shell cover the start-up line. +- Known gaps: the desktop shell's changes were checked only by compiling them for Windows, and its six new unit tests are not run by CI or by `./formweb test` yet (they were run in a separate crate that includes the real file); the 0.5 s minimum, showing the window when the editor is ready and the 20 s fallback were not run in a launched app on any system; nothing in this release was run on Windows or macOS; the new strings are machine translated; an imported page whose look comes from files on the web (stylesheets or scripts on another site) still arrives unstyled, which a later release addresses; and five pictures in the user guide still show the earlier import view and the earlier block labels on the canvas, and will be retaken in a later release. + ## 0.31.2 · 2026-11-25 - The editor no longer falls back to an older state of the site. When a change from outside the window (the assistant, the command line, another window) landed just after one of your own, the window could show the site as it was before the outside change, and stay that way until the next change. It now keeps the newest state it has received. From a2718e3de9b32422230e3ced7044ed01c1427a15 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 17:36:13 -0500 Subject: [PATCH 14/31] docs(hashout): frontend v0.32.0, the import view's shared picker, reset and decoding, the Page script recognised from stored data, hover outlines attached from outside the canvas, and the shell's start-up times --- frontend/HASHOUT_LOG.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 74ff76fc..51848a8a 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -1,5 +1,19 @@ # Frontend context map +## Import HTML files, the Page script, hover outlines and a faster desktop start · v0.32.0 (2026-11-26) + +The first of five releases (0.32.0 to 0.36.0) that answer the follow-up on issue #36. `backend/HASHOUT_LOG.md`, same version, has the service side of the import (loose files, the new counting, the source-project refusal). + +Import HTML files (`features/library/importer.ts`, `site-import.ts`, `index.ts`, `styles/library.css`): File > Import HTML files... (`file.import-html`, the id is unchanged, the label was Import HTML...) and File > Import site from zip... share one hidden `multiple` file input in `SiteImport`. `choose(kind)` only sets `accept` (`.html,.htm,text/html`, or `.zip,application/zip` plus those) and calls `click()`. The click must stay synchronous inside the command's run, because a browser opens a picker only inside the person's click or key press: never put an await or a timer before `choose()`. `importHtml()` shows the three-part import view (HTML files, A whole site in a .zip, Paste HTML code) behind the picker and moves to the review view through the `show` callback only once files are chosen, so cancelling leaves the person among the three ways in. `importSite()` still shows the review view behind its picker, because `test_convert.py` expects `.fw-lib-site-back` to be visible there. Loose files are read in the page and sent as `{"files": [{name, html}]}` to the same two routes as zip bytes (`request()` and `libraryMutate()` already send a plain object as JSON); a pick that mixes a zip with anything else, or holds another file type, is refused in the page with one sentence, and every refusal from the service is shown as sent. A picked file is read as bytes and decoded by `decode()` the way the service's `_text()` decodes a page inside a zip: strict UTF-8 (TextDecoder drops a byte order mark, as `utf-8-sig` does), else Windows-1252 with its five unassigned bytes (0x81, 0x8D, 0x8F, 0x90, 0x9D) as U+FFFD, as Python's `errors='replace'` makes them. It used `File.text()`, UTF-8 only, until review found that a Windows-1252 page lost every accented letter on this path and not in a zip; keep the two decoders in step, or the loose form and the zip stop giving the same page. When the review is refused, or finds no page, the files held in memory are dropped (`loose = null`), so neither As new pages nor As a section of this page can import a file the service has just refused; a new pick makes files importable again. A JSON body is somewhat larger than the files, so the service's 64 MiB cap can refuse what the page's own 64 MiB check let through. As a section of this page needs no review: it calls `importSection()` (exported from `importer.ts`) with the first file's text and its name without `.html`, and the paste part calls the same function, so the two cannot drift apart. The review scroller is a flex column; without `flex-shrink: 0` on its children the chosen-file list shrank by 5 px the moment the review made the scroller overflow, so keep that rule for any child added there. The chosen list keeps a 30 px minimum and the review comes after it, so nothing above it moves when the service answers. + +Fixes after the feature run (same version). `choose()` calls `reset()` inside the same click, before the picker opens: files, review, result note and the Imported state are cleared and the view is scrolled to the top, so an earlier import's review is never left behind the picker and the next review appears once, in place (`read()` no longer clears a review on screen itself). `index.ts` `settle()` also resets a finished import when the person comes back to it (Back, the Import HTML tab clicked from another tab, the Library shown again). The result or refusal note lives at the end of the scroller, not in the footer, and work in progress ("Reading the archive...", "Importing...", "Converting...") is written on the import button (`progress()`), so the footer keeps one height and the note changes only once, to the result; after an import the note is scrolled into view with `block: 'nearest'`. The view mounts one Bring ... in as choice, between the review and the skipped list, whose heading `bringChoice().heading()` switches between Bring pages in as and Bring it in as; it serves pages and a section alike. Keep it single: `test_convert.py` reads `[data-bring="elements"]` inside `.fw-lib-site` with a strict locator, which fails when two match, and the skipped list sits in its own `.fw-lib-site-skipped` block so `.fw-lib-site-review` still matches one element. `importSection()` ends with "Undo once to get the section back as code, twice to remove it." and selects the converted root; the Library's `select` hook in `main.ts` now also calls `canvas.bring(id)`, so the new section is scrolled into view; the same hook serves every Library insert (`features/library/index.ts`), so a section inserted from the Library scrolls into view too. "The pages stayed code sections: {0}" still says pages on the section path, because `test_convert.py` checks that text on the paste path. The ignored count reads "{0} files in system and dependency folders are ignored." + +Page script (`ui/canvas.ts`, `features/inspector/script-note.ts`, `styles/page-script.css`, `features/canvas-menu.ts`, the `script` icon in `ui/icons.ts`): a node is a Page script when its code section has JavaScript and no HTML, read from stored data by `codeKind(site, id)` (`'script'`, `'code'` or `''`), so sites imported before this version need no migration; the layer glyph, the canvas words, the inspector notes and the canvas menu's Design links all use that one helper. The text placeholder holds a title and a smaller line and carries `data-fw-poster="script|code|component"`; `syncPoster` writes the text nodes and the attribute only when they change. The script node is `display: contents` and has no box, so its placeholder is what you click and what shows the selection: only `[data-fw-poster=script]` takes pointer events (component and code placeholders stay `pointer-events: none`, so their clicks still fall through to the node with a box), `html[data-fw-dragging]` turns pointer events off on every placeholder so `elementFromPoint` cannot drop anything into the script, and `[data-fw-selected]>[data-fw-poster=script]` draws the selection outline. The dashed placeholder outline moved from the inline style into the canvas stylesheet, so neither needs `!important` and the reveal pulse still animates. `Canvas.find` falls back to the placeholder, so reveal and bring-into-view reach a node with no box. The Design and Motion panes are hidden by the class `fw-pane-script` plus one note per pane, not by setting `hidden` on each section, so inspector search and other code keep their own `hidden` state. The tab moves to Content only from Design or Motion, and goes back only if the person is still on Content when they select an ordinary element; the scroll position is restored in a microtask, before paint. The layer row icon holds all three glyphs (box, code, script) and switches with `data-glyph`; nothing is swapped through `innerHTML`. Not seen in a run: the text Component placeholder (every demo component has a poster picture), and the Menu key on a Page script (its anchor uses the node's box, and this node has none). + +Hover outlines (`features/hover-outline.ts`, `styles/hover-outline.css`, `view.hover-outline`): the marker is the attribute `data-fw-hover` on at most one canvas node and one layer row, never a class, so exact-class assertions and `keyed()` updates keep working, and `ui/canvas.ts` never removes it because the canvas removes only attributes it set itself. The iframe rule lives in a `

Winter timetable

From 1 October the Gull Island boat sails at weekends only.

@@ -35,9 +45,9 @@ Import HTML turns a whole HTML page, with its styles and first script, into a se ![The Import HTML view after pasting: the HTML box holds the pasted code, showing its last characters, and the orange Import as section button waits at the bottom of the panel](images/import-html-pasted.webp) -4. Click **Import as section** at the bottom of the panel. The status line says "HTML section imported." and the new section, here **Winter timetable notice**, is selected. With the page itself selected, as here, it goes at the end of the page. With **Editable elements** the panel says instead what was converted, for example "Converted 4 elements.", and the notice's heading and paragraph are layers you can click. +4. Click **Import as section** under the paste part. The status line says "HTML section imported." and the new section, here **Winter timetable notice**, is selected. With the page itself selected, as here, it goes at the end of the page. With **Editable elements** the panel says instead what was converted, for example "Converted 4 elements.", and the notice's heading and paragraph are layers you can click. -On the canvas a code section is drawn as a plain strip labelled Component, because its code does not run there: +On the canvas a code section is drawn as a plain block labelled Code section, because its code does not run there: ![The bottom of Harbour Ferries on the canvas: the dark footer, and under it a thin strip labelled Component, which is the imported code section, selected](images/import-html-canvas.webp) @@ -47,12 +57,16 @@ On the canvas a code section is drawn as a plain strip labelled Component, becau Import HTML turns on code sections for the site if they were off. Pictures and scripts that the pasted page loads by a relative path (such as `img/photo.png`) are not brought along: upload them separately, or use Import site from zip. +### A page script + +When a code section holds only a script and no HTML, as when a page converted to elements keeps its script, it is a **Page script**. Its layer has a page icon with code brackets, and on the canvas its block reads **Page script**, with "Runs in Preview and on the published site, not on this canvas." under it. Click the block to select it; it gets the orange outline. The right panel then opens the **Content** tab on its **Code section** settings, where you edit the script. A script has no box on the page, so the **Design** and **Motion** tabs only say that their settings do not apply to it, and its right-click menu has no Text style, Background, Spacing or Size. If you were on Design or Motion before, selecting another element takes you back there. + ## A whole site: Import site from zip This brings in a static site built elsewhere: every HTML file becomes a page. -1. Choose **File > Import site from zip...**, or click **Import site from zip...** at the top of the Import HTML view. -2. Click **Choose a .zip file** and pick your zip. +1. Choose **File > Import site from zip...**, or click **Choose a .zip file...** in the **A whole site in a .zip** part of the Import HTML view. +2. The file picker opens; pick your zip. If you close the picker, click **Choose a .zip file** in the view behind it. This picker also takes loose `.html` files, which then come in as described under [HTML files](#html-files-import-html-files). ![The Import site from zip view: a back button to Import HTML, the explanation of what an import does, and the Choose a .zip file button](images/import-site-panel.webp) @@ -90,7 +104,11 @@ Pictures (PNG, JPEG, GIF, WebP, SVG), MP4 and WebM videos and WOFF2 fonts go int Left out, with a note in the review: the rest of the page head, stylesheets and scripts loaded from other websites, scripts after the first one, scripts that are not JavaScript (such as JSON-LD structured data; Import HTML leaves them out the same way), other font formats, icons in ICO format, and any other kind of file. -The zip may be up to 64 MiB, with at most 1,000 files and 100 pages. A zip with a password, links, or files outside its own folder is refused as a whole. System files such as `__MACOSX` folders are ignored, and a single top folder is stripped. +The zip may be up to 64 MiB and 128 MiB unpacked, with at most 1,000 files and 100 pages. System and dependency folders (`__MACOSX`, `node_modules` and folders whose name starts with a dot) are ignored and do not count toward the 1,000, though the whole zip may hold at most 40,000 entries with them. A zip with a password, links, or files outside its own folder is refused as a whole, and a single top folder is stripped. When a zip is refused for its size or its number of files, the message says what to do: usually, zip only the folder that holds the finished site. + +### A project's source is refused + +A site made with a build tool has two forms: its source, which a browser cannot show as it is, and the finished site the build writes, often into a folder called `dist` or `build`. A zip of the source is refused with a message, and nothing is imported. FormWeb takes a zip as source when it has a `package.json` at the top (or one folder down) and something only a build can turn into a page: no HTML page at all, source files such as `.ts`, `.tsx`, `.jsx`, `.vue` or `.svelte` in its `src` folder or loaded by a page, a placeholder such as `%PUBLIC_URL%` in a page, or a script that loads a package by its name. The message says which of these it found. Build the project first (usually `npm run build`), then zip the output folder and import that zip. When the zip already holds a built copy in a `dist` or `build` folder, the message names that folder: zip that folder on its own. A finished site that only has a `package.json` beside its pages is imported as usual, and `package.json` is listed as skipped. ## Convert a code section to elements @@ -136,7 +154,7 @@ Five small sites were imported as editable elements and compared at 1440 px with | Site | Exported page | On the canvas | | --- | --- | --- | -| One-page landing page (header, hero, three feature columns in a flex row, footer) | 0.0% | 0.0% (plus the thin Component strip of the kept script below the footer) | +| One-page landing page (header, hero, three feature columns in a flex row, footer) | 0.0% | 0.0% (plus the thin Page script block of the kept script below the footer) | | Three pages with a shared stylesheet, a CSS grid gallery of six pictures and links between the pages | 0.0% on each page | 0.0% on each page | | An old editor's page: tables for layout, inline styles, `` and `
` tags | 1.1% | 1.3% | | A small-business page styled with a CSS framework's classes: navigation bar, hero photo as a CSS background under a dark gradient, three cards, four footer columns | 0.0% | not measured; looks the same | diff --git a/docs/guide/12-coming-from-other-builders.md b/docs/guide/12-coming-from-other-builders.md index 161d6432..baffbeca 100644 --- a/docs/guide/12-coming-from-other-builders.md +++ b/docs/guide/12-coming-from-other-builders.md @@ -14,7 +14,7 @@ If you have built sites with Dreamweaver or a similar visual editor, most of wha | Editing text in the page | Double-click the text on the canvas. | | Media queries | Breakpoints: Desktop, Tablet and Mobile in the second row of the top bar. You pick the one you edit, and styles set there apply to that range of widths only. | | A live view of the real page | **Preview** (Preview as published, Ctrl+Shift+P) for the whole site over the window, or **View > Live responsive preview** inside the canvas. See [Preview](06-preview.md). | -| Code view | There is no code view of the whole page: the page is a tree of elements that FormWeb writes out as HTML and CSS when you export. For your own code, use a code section (**File > Import HTML...**, see [Importing](09-importing.md)) or the **Custom code** section of the Page tab. | +| Code view | There is no code view of the whole page: the page is a tree of elements that FormWeb writes out as HTML and CSS when you export. For your own code, use a code section (Paste HTML code in **Library > Import HTML**, see [Importing](09-importing.md#pasted-code-paste-html-code)) or the **Custom code** section of the Page tab. | | Site-wide colors and fonts | Design tokens: **Window > Design system...**. A token such as `var(--paper)` used everywhere changes everywhere at once. See [Page background and theme colors](05-background-and-theme-colors.md). | | Templates or repeating regions | Components: build a part once (for example a header) and place linked instances on every page; a change to the original changes them all. To start a whole site from a design, use **New site** with **Start from**, or a demo such as Coldmere Plumbing. See [Components and the Library](10-components-and-library.md). | | Snippets or a library of ready-made blocks | The **Library**: finished sections, design presets and starter sites. | diff --git a/docs/guide/README.md b/docs/guide/README.md index aaf9af42..4784fd65 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -36,13 +36,13 @@ A demo opens as a new site that is not saved yet. Your saved projects are not to 1. [Your first site](01-first-site.md): from an empty page to an exported zip, every step pictured. Start here. 2. [Pages and layers](02-pages-and-layers.md): add, rename, reorder and fold pages and layers, set the home page, select several layers at once. -3. [Working on the canvas](03-canvas.md): select, the right-click menu, drag to move, wrap in a container, copy and paste styles. +3. [Working on the canvas](03-canvas.md): select, the right-click menu, drag to move, hover outlines, wrap in a container, copy and paste styles. 4. [The right panel](04-right-panel.md): the tabs, Search properties, and editing a breakpoint. 5. [Page background and theme colors](05-background-and-theme-colors.md): why a new page is white, the site background every page can share, starting a page with the home page's background, matching another page, one page or all pages, the site's theme colors. 6. [Preview](06-preview.md): Preview as published, and the Live responsive preview on the canvas. 7. [Audit](07-audit.md): what the audit checks and how Select takes you to the problem. 8. [Export and publishing](08-export-and-publish.md): the zip file, where it goes, and Send to FormPublisher. -9. [Importing](09-importing.md): one HTML page, a whole site from a zip, and .fweb and .fpub files. +9. [Importing](09-importing.md): HTML files as pages or a section, pasted HTML, a whole site from a zip, and .fweb and .fpub files. 10. [Components and the Library](10-components-and-library.md): reusable parts and ready-made sections. 11. [Keyboard shortcuts](11-keyboard-shortcuts.md): every shortcut the app registers. 12. [Coming from Dreamweaver or another visual builder](12-coming-from-other-builders.md): where to find the things you already know. From 5a659bac146a4ca45e395c2987605b80b0c154e6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 26 Nov 2026 17:36:19 -0500 Subject: [PATCH 17/31] chore(release): bump version to 0.32.0 --- .agents/skills/formweb-harness/SKILL.md | 2 +- .claude/skills/formweb-harness/SKILL.md | 2 +- .docs/wiki/Home.md | 2 +- README.md | 2 +- VERSION | 2 +- backend/app/config.py | 2 +- frontend/package-lock.json | 4 ++-- frontend/package.json | 2 +- native/Cargo.lock | 8 ++++---- native/Cargo.toml | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- 13 files changed, 17 insertions(+), 17 deletions(-) diff --git a/.agents/skills/formweb-harness/SKILL.md b/.agents/skills/formweb-harness/SKILL.md index 6ed094a4..90c370d2 100644 --- a/.agents/skills/formweb-harness/SKILL.md +++ b/.agents/skills/formweb-harness/SKILL.md @@ -5,7 +5,7 @@ license: Apache-2.0 compatibility: "Project skill for Claude Code and other clients with the FormWeb MCP server connected. Requires a running local FormWeb FastAPI service and explicit Agents enablement." metadata: author: "nodemode-ai" - version: "0.31.2" + version: "0.32.0" --- # FormWeb Harness diff --git a/.claude/skills/formweb-harness/SKILL.md b/.claude/skills/formweb-harness/SKILL.md index 6ed094a4..90c370d2 100644 --- a/.claude/skills/formweb-harness/SKILL.md +++ b/.claude/skills/formweb-harness/SKILL.md @@ -5,7 +5,7 @@ license: Apache-2.0 compatibility: "Project skill for Claude Code and other clients with the FormWeb MCP server connected. Requires a running local FormWeb FastAPI service and explicit Agents enablement." metadata: author: "nodemode-ai" - version: "0.31.2" + version: "0.32.0" --- # FormWeb Harness diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index 03d92535..3dbcd4d5 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -2,7 +2,7 @@ FormWeb is the form family's visual website authoring application. A Rust engine owns editable sites and exports browser-native HTML, CSS and JavaScript. A Python/FastAPI service supplies projects, local publications, forms and MCP. A vanilla TypeScript/Vite window displays and changes the same engine state. -Release version: 0.31.2. Author: nodemode-ai. The repository README and changelog record this release. +Release version: 0.32.0. Author: nodemode-ai. The repository README and changelog record this release. | Surface | Current boundary | | --- | --- | diff --git a/README.md b/README.md index 7dd955e9..47667b17 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

- version 0.31.2 + version 0.32.0 TypeScript 7 Rust engine macOS, Linux, Windows diff --git a/VERSION b/VERSION index c415e1c6..9eb2aa3f 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.31.2 +0.32.0 diff --git a/backend/app/config.py b/backend/app/config.py index 655021b9..30f7c3b1 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -11,7 +11,7 @@ if FROZEN: ROOT.mkdir(parents=True, exist_ok=True) load_dotenv(ROOT / 'backend' / '.env') -VERSION = '0.31.2' +VERSION = '0.32.0' PORT = int(os.getenv('FORMWEB_PORT', '8240')) CORE_NAME = 'formweb-core.exe' if os.name == 'nt' else 'formweb-core' CORE_BIN = Path(os.getenv('FORMWEB_CORE_BIN', str(BUNDLE / 'bin' / CORE_NAME if FROZEN else ROOT / 'native/target/release' / CORE_NAME))) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 813e54f6..cca022de 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formweb-frontend", - "version": "0.31.2", + "version": "0.32.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formweb-frontend", - "version": "0.31.2", + "version": "0.32.0", "dependencies": { "@fontsource/inter": "5.3.0", "@fontsource/jetbrains-mono": "5.3.0", diff --git a/frontend/package.json b/frontend/package.json index 26e74be3..97f27aed 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formweb-frontend", "private": true, - "version": "0.31.2", + "version": "0.32.0", "type": "module", "engines": { "node": ">=22.12.0" diff --git a/native/Cargo.lock b/native/Cargo.lock index ecdac498..623ee1fe 100644 --- a/native/Cargo.lock +++ b/native/Cargo.lock @@ -54,7 +54,7 @@ dependencies = [ [[package]] name = "formweb-core" -version = "0.31.2" +version = "0.32.0" dependencies = [ "formweb-engine", "formweb-export", @@ -64,7 +64,7 @@ dependencies = [ [[package]] name = "formweb-engine" -version = "0.31.2" +version = "0.32.0" dependencies = [ "formweb-model", "getrandom", @@ -73,7 +73,7 @@ dependencies = [ [[package]] name = "formweb-export" -version = "0.31.2" +version = "0.32.0" dependencies = [ "formweb-model", "serde_json", @@ -82,7 +82,7 @@ dependencies = [ [[package]] name = "formweb-model" -version = "0.31.2" +version = "0.32.0" dependencies = [ "serde", "serde_json", diff --git a/native/Cargo.toml b/native/Cargo.toml index 48b23704..98aaaa0f 100644 --- a/native/Cargo.toml +++ b/native/Cargo.toml @@ -5,7 +5,7 @@ exclude = ["crates/formweb-render"] resolver = "2" [workspace.package] -version = "0.31.2" +version = "0.32.0" edition = "2021" license = "Apache-2.0" diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 44479eb2..7828debf 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1124,7 +1124,7 @@ dependencies = [ [[package]] name = "formweb" -version = "0.31.2" +version = "0.32.0" dependencies = [ "formweb-render", "objc2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 853d959f..4980a7d3 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formweb" -version = "0.31.2" +version = "0.32.0" description = "FormWeb desktop shell" authors = ["nodemode-ai"] license = "Apache-2.0" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 58365223..39a0c907 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormWeb", - "version": "0.31.2", + "version": "0.32.0", "identifier": "ai.nodemode.formweb", "build": { "frontendDist": "../frontend/dist" From 9ae7c7c534f3f152fe199b41654bff08ce7505a2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 00:24:15 -0500 Subject: [PATCH 18/31] fix(inspector): a click on the name of a Design field that has a value puts the cursor in the field instead of pressing its Reset link --- frontend/src/main.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frontend/src/main.ts b/frontend/src/main.ts index bb9f4ba2..98bf6c37 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -577,7 +577,9 @@ function addStyle(container: HTMLElement, label: string, key: string, choices?: control.setAttribute('data-style', key); control.addEventListener('change', () => void run(() => setStyle(key, control.value))); styleFields.set(key, control); - const wrapper = field(label, control, full); + const wrapper = field(label, control, full) as HTMLLabelElement; + control.id = `fw-style-${key}`; + wrapper.htmlFor = control.id; wrapper.querySelector('.field-label')!.append(resetButton(label, key)); container.append(wrapper); } From c85f68fdd169a940478015c1f648217e10c1ec3d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 00:24:20 -0500 Subject: [PATCH 19/31] fix(stage): the selection path above the canvas is shown at every window width, the selected name starts at its first letter and ends in an ellipsis when it does not fit, and the address, width note and scrubber give way first --- frontend/src/features/crumbs.ts | 3 ++- frontend/src/styles/shell.css | 6 ++++-- frontend/src/styles/stage-head.css | 24 +++++++++++++++--------- 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/frontend/src/features/crumbs.ts b/frontend/src/features/crumbs.ts index 8eeb395a..aef54133 100644 --- a/frontend/src/features/crumbs.ts +++ b/frontend/src/features/crumbs.ts @@ -63,11 +63,12 @@ export function installCrumbs(nav: HTMLElement, hooks: CrumbHooks): Crumbs { if (!item) return more; const crumb = element('button', 'fw-crumb'); crumb.type = 'button'; + crumb.append(element('span', 'fw-crumb-name')); crumb.addEventListener('click', () => hooks.pick(crumb.dataset.key!)); return crumb; }, (crumb, item) => { if (!item) return; - text(crumb, item.name); + text(crumb.firstElementChild as HTMLElement, item.name); crumb.title = `Select ${item.name} <${item.tag}>`; const on = item.id === current; crumb.classList.toggle('is-current', on); diff --git a/frontend/src/styles/shell.css b/frontend/src/styles/shell.css index ba7f7975..b4806d1b 100644 --- a/frontend/src/styles/shell.css +++ b/frontend/src/styles/shell.css @@ -273,11 +273,13 @@ a.fw-home-action { text-decoration: none; } .fw-reset:hover { background: var(--accent-soft); } .fw-reset[hidden] { display: none; } .fw-crumbs { display: flex; flex: 1 1 0; align-items: center; gap: 2px; min-width: 0; overflow: hidden; margin-left: var(--space-2); } -.fw-crumb { min-height: 0; height: 24px; padding: 0 6px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text-muted); font-size: var(--fs-11); white-space: nowrap; flex: none; min-width: 0; max-width: 12em; overflow: hidden; text-align: start; text-overflow: ellipsis; } +.fw-crumb { display: inline-flex; align-items: center; justify-content: flex-start; min-height: 0; height: 24px; padding: 0 6px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text-muted); font-size: var(--fs-11); white-space: nowrap; flex: none; min-width: 0; max-width: 12em; overflow: hidden; text-align: start; text-overflow: ellipsis; } +.fw-crumb::before { flex: none; } +.fw-crumb-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .fw-crumb[hidden] { display: none; } .fw-crumb:not([hidden]) ~ .fw-crumb::before { content: "/"; margin-right: 6px; color: var(--line-3); } .fw-crumb.is-current { max-width: 20em; } -.fw-crumbs.is-tight > .fw-crumb.is-current { flex: 0 1 auto; min-width: 5em; } +.fw-crumbs.is-tight > .fw-crumb.is-current { flex: 0 1 auto; min-width: 0; } .fw-crumb-more { display: inline-flex; align-items: center; gap: 0; overflow: visible; } .fw-crumb-more .icon { width: 14px; height: 14px; } .fw-crumb:hover { color: var(--text-primary); background: var(--bg-hover); } diff --git a/frontend/src/styles/stage-head.css b/frontend/src/styles/stage-head.css index 65fbfcf4..0d49ff1e 100644 --- a/frontend/src/styles/stage-head.css +++ b/frontend/src/styles/stage-head.css @@ -1,12 +1,18 @@ .stage-panel > .stage-head { container: fw-stage / inline-size; } -.stage-panel > .stage-head > .stage-page { flex: 0 0 auto; max-width: 18cqi; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.stage-panel > .stage-head > .stage-page { flex: 0 1 auto; min-width: 2em; max-width: 18cqi; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.stage-panel > .stage-head > .stage-path { flex: 0 1000 auto; min-width: 2em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.stage-panel > .stage-head > .fw-crumbs { min-width: clamp(8.5rem, 24cqi, 14rem); } +.stage-panel > .stage-head > .viewport-hint { flex: 0 4 23em; min-width: 8em; -webkit-line-clamp: 3; line-clamp: 3; line-height: 1.2; } .stage-panel > .stage-head > .icon, .stage-panel > .stage-head > .fw-theme-switch, .stage-panel > .stage-head > .fw-scrub, .stage-panel > .stage-head > .viewport-readout { flex: none; } .stage-panel > .stage-head > .viewport-readout { min-width: 176px; overflow: visible; white-space: nowrap; } .stage-panel > .stage-head .readout-width::before { content: " \00B7 "; } .stage-head .fw-scrub .fw-seg-btn:last-child { min-width: 84px; } @container fw-stage (max-width: 1100px) { .stage-head:has(> .fw-scrub:not([hidden])) .fw-scrub .fw-seg-btn:not(:last-child), .stage-head:has(> .fw-scrub:not([hidden])) .fw-scrub output { display: none; } - .stage-head:has(> .fw-scrub:not([hidden])) > .viewport-hint { flex-shrink: 1; min-width: 12em; -webkit-line-clamp: 3; line-clamp: 3; line-height: 1.2; } + .stage-head .fw-scrub input[type="range"] { width: 64px; } +} +@container fw-stage (max-width: 900px) { + .stage-panel > .stage-head:has(> .fw-scrub:not([hidden])) > .viewport-hint { display: none; } } @container fw-stage (max-width: 760px) { .stage-head .fw-scrub .fw-seg-btn:not(:last-child) { display: none; } @@ -20,16 +26,16 @@ .stage-panel > .stage-head > .viewport-hint { flex: 0 1 23em; min-width: 0; -webkit-line-clamp: 3; line-clamp: 3; line-height: 1.2; } .stage-panel > .stage-head:has(> .fw-scrub:not([hidden])) > .viewport-hint { display: none; } .stage-panel > .stage-head > .stage-page { margin-right: auto; max-width: 30cqi; } + .stage-panel > .stage-head > .fw-crumbs { min-width: max(5.5rem, 28cqi); } .stage-head .fw-scrub { gap: var(--space-1); } - .stage-head .fw-scrub output { display: none; } - .stage-head .fw-scrub input[type="range"] { width: 64px; } - .stage-head .fw-scrub select { max-width: 72px; } + .stage-head .fw-scrub output, .stage-head .fw-scrub select { display: none; } + .stage-head .fw-scrub input[type="range"] { width: 44px; } } @container fw-stage (max-width: 400px) { - .stage-panel > .stage-head > .icon, .stage-panel > .stage-head > .fw-crumbs { display: none; } - .stage-panel > .stage-head > .stage-page { flex: 0 1 auto; min-width: 0; max-width: none; } + .stage-panel > .stage-head > .icon { display: none; } + .stage-panel > .stage-head > .stage-page { flex: 0 1000 auto; min-width: 0; max-width: 30cqi; } .stage-panel > .stage-head:has(> .fw-scrub:not([hidden]):not([data-single])) > .stage-page { visibility: hidden; } .stage-panel > .stage-head > .viewport-readout { min-width: 4.5em; } - .stage-head .fw-scrub input[type="range"] { width: 48px; } - .stage-head .fw-scrub select { max-width: 52px; } + .stage-head .fw-scrub input[type="range"] { display: none; } + .stage-panel > .stage-head > .fw-crumbs { min-width: max(5.5rem, 40cqi); } } From 1db4846741dc678a0ff608f575fb4fedf5c114e3 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 00:37:12 -0500 Subject: [PATCH 20/31] feat(inspector): Design fields can carry a control beside their text input, starting with a slider and unit chooser on thirteen size and spacing fields; the typed value stays the one stored value, one drag or held key is one undo step, a value the control cannot show is left as typed, and a switch in the field's label, a Preferences setting and View > Show controls in Design fields turn the controls off --- frontend/src/commands/catalogue.ts | 1 + frontend/src/commands/keymap.ts | 5 +- .../src/features/inspector/controls/index.ts | 334 ++++++++++++++++++ .../src/features/inspector/controls/number.ts | 90 +++++ .../src/features/inspector/controls/slider.ts | 216 +++++++++++ .../src/features/inspector/controls/types.ts | 42 +++ frontend/src/main.ts | 22 +- frontend/src/styles/control-slider.css | 11 + frontend/src/styles/controls.css | 22 ++ 9 files changed, 739 insertions(+), 4 deletions(-) create mode 100644 frontend/src/features/inspector/controls/index.ts create mode 100644 frontend/src/features/inspector/controls/number.ts create mode 100644 frontend/src/features/inspector/controls/slider.ts create mode 100644 frontend/src/features/inspector/controls/types.ts create mode 100644 frontend/src/styles/control-slider.css create mode 100644 frontend/src/styles/controls.css diff --git a/frontend/src/commands/catalogue.ts b/frontend/src/commands/catalogue.ts index 87591d60..6d40cf4f 100644 --- a/frontend/src/commands/catalogue.ts +++ b/frontend/src/commands/catalogue.ts @@ -81,6 +81,7 @@ const META: Record = { 'view.refresh': { description: 'Refresh the live responsive preview.' }, 'view.preview-full': { description: 'Open or close the full-window preview of the compiled site as visitors will see it, with a page picker, device widths from the site breakpoints, locale, refresh and open in browser. While it is open every other window command is disabled.', when: 'Use when the person wants to see the finished site; it changes nothing.' }, 'view.theme': { description: 'Switch between the light and dark editor theme.' }, + '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.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.' }, diff --git a/frontend/src/commands/keymap.ts b/frontend/src/commands/keymap.ts index af6f449a..1d2ec252 100644 --- a/frontend/src/commands/keymap.ts +++ b/frontend/src/commands/keymap.ts @@ -1,6 +1,7 @@ import { comboOf, type Commands } from './registry'; const TYPING = 'input, textarea, select, [contenteditable=""], [contenteditable="true"], .xterm, .ft-dock, .ft-consent, .ft-tour, [data-no-keys]'; +const OWN_KEYS = '[data-own-keys]'; export function installKeymap(registry: Commands, ready: () => boolean): void { document.addEventListener('keydown', event => { @@ -9,8 +10,10 @@ export function installKeymap(registry: Commands, ready: () => boolean): void { if (!command) return; if (!command.global && !ready()) return; const mod = comboOf(event).includes('Mod+'); - const typing = !!(event.target as Element | null)?.closest?.(TYPING); + const target = event.target as Element | null; + const typing = !!target?.closest?.(TYPING); if (typing && !(command.global && mod)) return; + if (!mod && target?.closest?.(OWN_KEYS)) return; if (command.native?.()) return; if (event.repeat && !command.repeat) { if (mod) event.preventDefault(); return; } if (!mod && !registry.enabled(command)) return; diff --git a/frontend/src/features/inspector/controls/index.ts b/frontend/src/features/inspector/controls/index.ts new file mode 100644 index 00000000..cbe375d4 --- /dev/null +++ b/frontend/src/features/inspector/controls/index.ts @@ -0,0 +1,334 @@ +import type { EditorState } from '../../../types'; +import { labelAttr } from '../../../i18n'; +import { element } from '../../../ui/dom'; +import { icon } from '../../../ui/icons'; +import { readBrand } from '../../brand-kit'; +import type { ColorToken, Control, ControlFactory, ControlHost, ControlKit, StyleField } from './types'; +import { register as registerSlider } from './slider'; +import '../../../styles/controls.css'; + +const factories = new Map(); + +export function registerControl(keys: readonly string[], factory: ControlFactory): void { + for (const key of keys) { + if (factories.has(key)) throw new Error(`control already registered for ${key}`); + factories.set(key, factory); + } +} + +export interface ControlOptions { + fields: ReadonlyMap; + overlay: HTMLElement; + state(): EditorState | undefined; + values(key: string): { value: string; inherited: string }; + setStyle(key: string, value: string): Promise; + status(message: string, error?: boolean): void; + changed?(): void; + setStyles?(styles: Record): Promise; + scope(key: string): string; +} + +export interface InstalledKit extends ControlKit { + own(): number; + clearRaw(): void; + track(key: string, value: string, work: Promise): Promise; + shown(key: string, stored: string): string; +} + +type Mode = 'controls' | 'css'; +interface Stored { default?: Mode; fields?: Record } +const STORE_KEY = 'formweb.design-controls'; +const PASS = 'input, select, textarea, a[href], summary'; + +function load(): Stored { + try { + const parsed = JSON.parse(localStorage.getItem(STORE_KEY) || '{}') as Stored; + return parsed && typeof parsed === 'object' ? parsed : {}; + } catch { return {}; } +} + +function save(stored: Stored): void { + try { localStorage.setItem(STORE_KEY, JSON.stringify(stored)); } catch { } +} + +function isColor(value: string): boolean { + const text = value.trim(); + return !!text && !/var\(/i.test(text) && typeof CSS !== 'undefined' && CSS.supports('color', text); +} + +function englishLabel(head: HTMLElement | null, key: string): string { + const own = head ? Array.from(head.childNodes).filter(node => node.nodeType === 3).map(node => node.textContent).join('').trim() : ''; + return own || key; +} + +interface Gesture { scope: string; held: string; values: Set; dead: boolean; released: boolean } +interface Upgraded { field: StyleField; control: Control; toggle: HTMLButtonElement; shown: boolean; gesture: Gesture | null; stale: Set } + +let installed = false; + +export function installControls(options: ControlOptions): InstalledKit { + if (!installed) { + installed = true; + registerSlider(); + } + const stored = load(); + stored.fields = stored.fields && typeof stored.fields === 'object' ? stored.fields : {}; + const host: ControlHost & { commitStyles?(styles: Record): Promise } = { + commitStyles: options.setStyles ? async styles => { await options.setStyles!(styles); } : undefined, + overlay: options.overlay, + state: options.state, + colors(): ColorToken[] { + const state = options.state(); + if (!state) return []; + const seen = new Set(); + const out: ColorToken[] = []; + const add = (token: ColorToken): void => { if (!seen.has(token.css)) { seen.add(token.css); out.push(token); } }; + const brand = readBrand(state); + for (const item of brand.colors) add({ name: item.name, value: item.value, css: `var(--${item.token})`, group: 'brand' }); + for (const item of brand.teamColors) add({ name: item.name, value: item.value, css: `var(--${item.token})`, group: 'team' }); + for (const [name, content] of Object.entries(state.site.tokens || {})) { + const bare = name.replace(/^--/, ''); + if (isColor(content)) add({ name: bare, value: content, css: `var(--${bare})`, group: 'site' }); + } + return out; + }, + restricted: () => { const state = options.state(); return !!state && readBrand(state).restricted; }, + status: (message, error = false) => options.status(message, error) + }; + const upgraded = new Map(); + const inflight = new Map(); + let identity: string | null = null; + const held = (key: string): string | null => { + const gesture = upgraded.get(key)?.gesture; + return gesture && !gesture.dead && gesture.scope === options.scope(key) ? gesture.held : null; + }; + const committed = (key: string, stored: string): string => inflight.get(options.scope(key))?.at(-1)?.value ?? stored; + const shown = (key: string, stored: string): string => held(key) ?? committed(key, stored); + function settle(key: string, scope: string): void { + const list = inflight.get(scope); + if (!list || list.length) return; + inflight.delete(scope); + const entry = upgraded.get(key); + if (entry && entry.gesture) { later(entry); return; } + if (!entry || options.scope(key) !== scope || document.activeElement === entry.field.input) return; + entry.field.restore(); + syncOne(entry); + } + function later(entry: Upgraded): void { + const gesture = entry.gesture; + window.setTimeout(() => { + const key = entry.field.key; + if (!gesture || entry.gesture !== gesture || gesture.dead || gesture.scope !== options.scope(key) || inflight.get(gesture.scope)?.length) return; + if (!gesture.released && gesture.held !== entry.field.value()) return; + entry.field.restore(); + syncOne(entry); + }); + } + const release = (event: Event): void => { + upgraded.forEach(entry => { + if (!entry.gesture) return; + if (event.type !== 'keyup') entry.gesture.released = true; + later(entry); + }); + }; + for (const type of ['pointerup', 'pointercancel', 'keyup']) window.addEventListener(type, release, true); + function moved(): boolean { + const now = options.scope(''); + if (identity === now) return false; + const first = identity === null; + identity = now; + if (first) return false; + upgraded.forEach(entry => { + const cancel = entry.control.cancel; + const gesture = entry.gesture; + if (gesture) gesture.dead = true; + if (cancel) { try { cancel.call(entry.control); } catch { } } + entry.stale = new Set(); + if (!gesture) return; + if (cancel) { entry.stale = gesture.values; entry.gesture = null; } else gesture.dead = true; + }); + return true; + } + + const defaultRaw = (): boolean => stored.default === 'css'; + const raw = (key: string): boolean => { const own = stored.fields![key]; return own ? own === 'css' : defaultRaw(); }; + + function paint(entry: Upgraded): void { + const isRaw = raw(entry.field.key); + const mode = isRaw ? 'raw' : entry.shown ? 'on' : 'off'; + const wrapper = entry.field.wrapper; + if (wrapper.dataset.ctl !== mode) wrapper.dataset.ctl = mode; + for (const slot of [entry.field.lead, entry.field.trail, entry.field.below]) { + const inert = mode !== 'on'; + if (slot.inert !== inert) slot.inert = inert; + } + const pressed = String(isRaw); + if (entry.toggle.getAttribute('aria-pressed') !== pressed) entry.toggle.setAttribute('aria-pressed', pressed); + } + + function syncOne(entry: Upgraded): void { + if (!raw(entry.field.key)) { + let shown = false; + try { shown = entry.control.sync(entry.field.input.value, entry.field.inherited()); } catch { shown = false; } + entry.shown = shown; + } + paint(entry); + } + + function applyRaw(entry: Upgraded, before: boolean): void { + const now = raw(entry.field.key); + if (now !== before) { + try { entry.control.setRaw?.(now); } catch { } + } + syncOne(entry); + } + + function stopLabel(event: MouseEvent): void { + const target = event.target as Element | null; + const slot = event.currentTarget as HTMLElement; + const pass = target?.closest(PASS); + if (pass && slot.contains(pass)) return; + event.preventDefault(); + } + + for (const [key, node] of options.fields) { + const factory = factories.get(key); + if (!factory || !(node instanceof HTMLInputElement)) continue; + const input = node; + const wrapper = input.closest('.field'); + if (!wrapper) continue; + const head = wrapper.querySelector(':scope > .field-label'); + const label = englishLabel(head, key); + const row = element('span', 'fw-ctl-row'); + const lead = element('span', 'fw-ctl-slot fw-ctl-lead'); + const trail = element('span', 'fw-ctl-slot fw-ctl-trail'); + const below = element('span', 'fw-ctl-slot fw-ctl-below'); + input.before(row); + row.append(lead, input, trail); + row.after(below); + for (const slot of [lead, trail, below]) { + slot.dataset.ownKeys = ''; + slot.addEventListener('click', stopLabel); + } + if (wrapper instanceof HTMLLabelElement) { + if (!input.id) input.id = `fw-style-${key}`; + wrapper.htmlFor = input.id; + } + labelAttr(input, 'aria-label', label); + wrapper.classList.add('fw-ctl'); + wrapper.dataset.ctl = 'off'; + + const toggle = element('button', 'fw-ctl-raw'); + toggle.type = 'button'; + toggle.dataset.ctlRaw = key; + toggle.dataset.ownKeys = ''; + toggle.append(icon('code')); + labelAttr(toggle, 'title', 'Type {0} by hand: hide its control and edit the CSS text only. Press again to bring the control back.', [{ t: label }]); + labelAttr(toggle, 'aria-label', 'Type {0} by hand', [{ t: label }]); + toggle.setAttribute('aria-pressed', 'false'); + const reset = head?.querySelector(':scope > .fw-reset'); + if (reset) reset.after(toggle); + else head?.append(toggle); + + const values = (): { value: string; inherited: string } => options.state() ? options.values(key) : { value: '', inherited: '' }; + let entry: Upgraded; + const field: StyleField = { + key, label, input, wrapper, lead, trail, below, + value: () => committed(key, values().value), + inherited: () => values().inherited, + show(next: string) { + const value = next.trim(); + const scope = options.scope(key); + const gesture = entry.gesture; + if (gesture && (gesture.dead || gesture.scope !== scope)) { gesture.dead = true; gesture.values.add(value); return; } + if (gesture) { gesture.held = value; gesture.values.add(value); gesture.released = false; } + else { entry.gesture = { scope, held: value, values: new Set([value]), dead: false, released: false }; entry.stale.delete(value); } + if (input.value !== next) input.value = next; + }, + restore() { + entry.gesture = null; + const stored = committed(key, values().value); + if (input.value !== stored) input.value = stored; + settle(key, options.scope(key)); + }, + async commit(next: string) { + const entered = next.trim(); + const gesture = entry.gesture; + if (gesture && (gesture.dead || gesture.scope !== options.scope(key))) { entry.stale = gesture.values; entry.gesture = null; return; } + if (!gesture && entry.stale.delete(entered)) return; + const shownNow = held(key); + if (entered === committed(key, values().value) && (shownNow === null || shownNow === entered)) { field.restore(); syncOne(entry); return; } + if ((shownNow === null || shownNow === entered) && input.value !== next) input.value = next; + try { + await options.setStyle(key, next); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + const after = held(key); + if (after === null || after === entered) field.restore(); + options.status(message, true); + syncOne(entry); + throw error instanceof Error ? error : new Error(message); + } + } + }; + let control: Control; + try { control = factory(field, host); } catch (error) { console.error(error); continue; } + entry = { field, control, toggle, shown: false, gesture: null, stale: new Set() }; + upgraded.set(key, entry); + toggle.addEventListener('click', event => { + event.preventDefault(); + event.stopPropagation(); + kit.setRaw(key, !raw(key)); + }); + const typed = (): void => syncOne(entry); + input.addEventListener('input', typed); + input.addEventListener('change', typed); + input.addEventListener('blur', () => { if (!inflight.has(options.scope(key)) && held(key) === null && options.state()) { field.restore(); syncOne(entry); } }); + if (raw(key)) { try { control.setRaw?.(true); } catch { } } + paint(entry); + } + + const kit: InstalledKit = { + sync() { moved(); upgraded.forEach(syncOne); }, + track(key: string, value: string, work: Promise): Promise { + const scope = options.scope(key); + const list = inflight.get(scope) ?? []; + inflight.set(scope, list); + const mark = { value }; + list.push(mark); + const entry = upgraded.get(key); + if (entry && held(key) === value) entry.gesture = null; + return work.finally(() => { + list.splice(list.indexOf(mark), 1); + settle(key, scope); + }); + }, + shown, + raw, + setRaw(key: string, next: boolean) { + const entry = upgraded.get(key); + const before = raw(key); + stored.fields![key] = next ? 'css' : 'controls'; + save(stored); + if (entry) applyRaw(entry, before); + options.changed?.(); + }, + defaultRaw, + setDefaultRaw(next: boolean) { + const before = new Map(Array.from(upgraded.keys(), key => [key, raw(key)])); + stored.default = next ? 'css' : 'controls'; + save(stored); + upgraded.forEach((entry, key) => applyRaw(entry, before.get(key)!)); + options.changed?.(); + }, + own: () => Object.keys(stored.fields!).length, + clearRaw() { + const before = new Map(Array.from(upgraded.keys(), key => [key, raw(key)])); + stored.fields = {}; + save(stored); + upgraded.forEach((entry, key) => applyRaw(entry, before.get(key)!)); + options.changed?.(); + } + }; + return kit; +} diff --git a/frontend/src/features/inspector/controls/number.ts b/frontend/src/features/inspector/controls/number.ts new file mode 100644 index 00000000..5b75ff84 --- /dev/null +++ b/frontend/src/features/inspector/controls/number.ts @@ -0,0 +1,90 @@ +export interface Range { readonly min: number; readonly max: number; readonly step: number } +export interface Scale { + readonly units: Readonly>; + readonly unit: string; + readonly rest: number; + readonly floor: number; + readonly ceiling: number; +} +export interface Amount { readonly n: number; readonly unit: string } + +const r = (min: number, max: number, step: number): Range => ({ min, max, step }); +const scale = (unit: string, units: Record, rest = 0, floor = 0, ceiling = Infinity): Scale => ({ units, unit, rest, floor, ceiling }); +const SIGNED = -Infinity; + +export const SCALES: Readonly> = { + 'opacity': scale('', { '': r(0, 1, 0.01) }, 1, 0, 1), + 'width': scale('px', { px: r(0, 1600, 1), '%': r(0, 100, 1), rem: r(0, 100, 0.25), em: r(0, 100, 0.25), vw: r(0, 100, 1), vh: r(0, 100, 1) }), + 'height': scale('px', { px: r(0, 1200, 1), '%': r(0, 100, 1), rem: r(0, 75, 0.25), em: r(0, 75, 0.25), vh: r(0, 100, 1), vw: r(0, 100, 1) }), + 'max-width': scale('px', { px: r(0, 1920, 1), '%': r(0, 100, 1), rem: r(0, 120, 0.25), em: r(0, 120, 0.25), ch: r(0, 120, 1), vw: r(0, 100, 1) }), + 'gap': scale('px', { px: r(0, 160, 1), rem: r(0, 10, 0.25), em: r(0, 10, 0.25), '%': r(0, 20, 1) }), + 'padding': scale('px', { px: r(0, 200, 1), rem: r(0, 12, 0.25), em: r(0, 12, 0.25), '%': r(0, 50, 1), vw: r(0, 20, 0.5), vh: r(0, 20, 0.5) }), + 'margin': scale('px', { px: r(-200, 200, 1), rem: r(-12, 12, 0.25), em: r(-12, 12, 0.25), '%': r(-50, 50, 1), vw: r(-20, 20, 0.5), vh: r(-20, 20, 0.5) }, 0, SIGNED), + 'border-radius': scale('px', { px: r(0, 200, 1), rem: r(0, 12, 0.25), em: r(0, 12, 0.25), '%': r(0, 50, 1) }), + 'font-size': scale('px', { px: r(8, 96, 1), rem: r(0.5, 6, 0.05), em: r(0.5, 6, 0.05), '%': r(50, 400, 5), vw: r(0.5, 10, 0.1) }, 16), + 'line-height': scale('', { '': r(0.8, 3, 0.05), px: r(8, 120, 1), rem: r(0.5, 8, 0.05), em: r(0.5, 3, 0.05), '%': r(80, 300, 5) }, 1.2), + 'letter-spacing': scale('px', { px: r(-5, 20, 0.1), em: r(-0.1, 0.5, 0.005), rem: r(-0.1, 0.5, 0.005) }, 0, SIGNED), + 'top': scale('px', { px: r(-200, 1200, 1), '%': r(-100, 100, 1), rem: r(-12, 75, 0.25), em: r(-12, 75, 0.25), vh: r(-50, 100, 1), vw: r(-50, 100, 1) }, 0, SIGNED), + 'left': scale('px', { px: r(-200, 1600, 1), '%': r(-100, 100, 1), rem: r(-12, 100, 0.25), em: r(-12, 100, 0.25), vw: r(-50, 100, 1), vh: r(-50, 100, 1) }, 0, SIGNED), +}; + +const NUMBER = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)([a-z%]*)$/i; + +export function parse(key: string, text: string): Amount | null { + const table = SCALES[key]; + const match = NUMBER.exec(text.trim()); + if (!table || !match) return null; + const n = Number(match[1]); + const unit = match[2].toLowerCase(); + if (!Number.isFinite(n)) return null; + if (unit in table.units) return { n, unit }; + return unit === '' && n === 0 ? { n: 0, unit: table.unit } : null; +} + +export function range(key: string, unit: string): Range | null { + return SCALES[key]?.units[unit] ?? null; +} + +export function places(step: number): number { + const text = String(step); + const dot = text.indexOf('.'); + return dot < 0 ? 0 : text.length - dot - 1; +} + +export function format(n: number, unit: string, digits: number): string { + const fixed = Number(n.toFixed(Math.min(digits, 6))); + return `${Object.is(fixed, -0) ? 0 : fixed}${unit}`; +} + +export function fraction(n: number, span: Range): number { + if (span.max <= span.min) return 0; + return Math.min(1, Math.max(0, (n - span.min) / (span.max - span.min))); +} + +export function snap(at: number, span: Range): number { + const raw = span.min + Math.min(1, Math.max(0, at)) * (span.max - span.min); + const n = span.min + Math.round((raw - span.min) / span.step) * span.step; + return Number(Math.min(span.max, Math.max(span.min, n)).toFixed(places(span.step))); +} + +export function step(key: string, amount: Amount, times: number): string { + const table = SCALES[key]; + const span = table.units[amount.unit]; + const digits = Math.max(places(span.step), places(Math.abs(amount.n))); + const next = Math.min(table.ceiling, Math.max(table.floor, amount.n + times * span.step)); + return format(next, amount.unit, digits); +} + +export function slide(key: string, amount: Amount, times: number): string { + const span = SCALES[key].units[amount.unit]; + let next = amount.n + times * span.step; + if (times > 0 && next > span.max) next = Math.max(amount.n, span.max); + if (times < 0 && next < span.min) next = Math.min(amount.n, span.min); + return format(next, amount.unit, Math.max(places(span.step), places(Math.abs(amount.n)))); +} + +export function rest(key: string, unit: string): number { + const table = SCALES[key]; + const span = table.units[unit]; + return Math.min(span.max, Math.max(span.min, unit === table.unit ? table.rest : 0)); +} diff --git a/frontend/src/features/inspector/controls/slider.ts b/frontend/src/features/inspector/controls/slider.ts new file mode 100644 index 00000000..bb5f8660 --- /dev/null +++ b/frontend/src/features/inspector/controls/slider.ts @@ -0,0 +1,216 @@ +import { labelAttr, t } from '../../../i18n'; +import { element } from '../../../ui/dom'; +import { registerControl } from './index'; +import { SCALES, format, fraction, parse, places, range, rest, slide, snap, step, type Amount } from './number'; +import type { Control, StyleField } from './types'; +import '../../../styles/control-slider.css'; + +const PAUSE_MS = 700; +const UNITLESS = '×'; +const SLIDE_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End']); + +function set(node: Element, name: string, next: string): void { + if (node.getAttribute(name) !== next) node.setAttribute(name, next); +} + +function create(field: StyleField): Control { + const key = field.key; + const table = SCALES[key]; + const units = Object.keys(table.units); + const slider = element('div', 'fw-slider'); + const track = element('span', 'fw-slider-track'); + const thumb = element('span', 'fw-slider-thumb'); + track.append(element('span', 'fw-slider-fill')); + slider.append(track, thumb); + slider.tabIndex = 0; + slider.dataset.ownKeys = ''; + slider.dataset.state = 'unset'; + set(slider, 'role', 'slider'); + set(slider, 'aria-orientation', 'horizontal'); + labelAttr(slider, 'aria-label', field.label); + field.below.append(slider); + + const chooser = units.length > 1 ? element('select', 'fw-unit') : null; + if (chooser) { + for (const unit of units) { + const option = element('option', '', unit || UNITLESS); + option.value = unit; + chooser.append(option); + } + labelAttr(chooser, 'aria-label', 'Unit for {0}', [{ t: field.label }]); + labelAttr(chooser, 'title', 'Unit for {0}', [{ t: field.label }]); + field.trail.append(chooser); + } + + let raw = false; + let shown: Amount = { n: rest(key, table.unit), unit: table.unit }; + let chosen: string | null = null; + let drag: { id: number; text: string } | null = null; + let held: string | null = null; + let flying: string | null = null; + let muted = false; + let timer = 0; + + const paint = (amount: Amount, state: 'set' | 'inherited' | 'unset', label: string): void => { + shown = amount; + const span = range(key, amount.unit)!; + const at = fraction(amount.n, span); + const n = Math.min(span.max, Math.max(span.min, amount.n)); + if (slider.style.getPropertyValue('--at') !== String(at)) slider.style.setProperty('--at', String(at)); + if (slider.dataset.state !== state) slider.dataset.state = state; + set(slider, 'aria-valuemin', String(span.min)); + set(slider, 'aria-valuemax', String(span.max)); + set(slider, 'aria-valuenow', String(n)); + set(slider, 'aria-valuetext', label); + if (chooser && chooser.value !== amount.unit) chooser.value = amount.unit; + }; + const showing = (value: string, inherited: string): boolean => { + const own = value.trim(); + if (own) { + const amount = parse(key, own); + if (!amount) return false; + chosen = null; + paint(amount, 'set', own); + return true; + } + const from = parse(key, inherited); + if (from && (chosen === null || chosen === from.unit)) paint(from, 'inherited', t('Inherited: {0}', [inherited.trim()])); + else { + const unit = chosen ?? table.unit; + paint({ n: rest(key, unit), unit }, 'unset', t('Not set')); + } + return true; + }; + const again = (): void => { showing(field.input.value, field.inherited()); }; + const commit = (text: string): void => { + if (text === (flying ?? field.value().trim())) { field.restore(); if (flying === null) again(); return; } + flying = text; + void field.commit(text).catch(() => undefined).then(() => { + if (flying !== text) return; + flying = null; + if (!drag && held === null) again(); + }); + }; + const pending = (text: string): void => { + field.show(text); + const amount = parse(key, text); + if (amount) paint(amount, 'set', text); + }; + const flush = (): void => { + window.clearTimeout(timer); + if (held === null) return; + const text = held; + held = null; + commit(text); + }; + const hold = (text: string): void => { + held = text; + pending(text); + window.clearTimeout(timer); + timer = window.setTimeout(flush, PAUSE_MS); + }; + const abandon = (): void => { + muted = held !== null || muted; + window.clearTimeout(timer); + held = null; + flying = null; + if (drag && slider.hasPointerCapture(drag.id)) { const id = drag.id; drag = null; slider.releasePointerCapture(id); } + drag = null; + }; + const cancel = (): void => { + abandon(); + field.restore(); + again(); + }; + + const at = (event: PointerEvent): string => { + const box = slider.getBoundingClientRect(); + const size = thumb.offsetWidth; + const span = range(key, shown.unit)!; + const n = snap((event.clientX - box.left - size / 2) / Math.max(1, box.width - size), span); + return format(n, shown.unit, places(span.step)); + }; + slider.addEventListener('pointerdown', event => { + if (event.button !== 0 || !event.isPrimary || drag) return; + event.preventDefault(); + flush(); + slider.focus({ preventScroll: true }); + slider.setPointerCapture(event.pointerId); + drag = { id: event.pointerId, text: at(event) }; + pending(drag.text); + }); + slider.addEventListener('pointermove', event => { + if (!drag || event.pointerId !== drag.id) return; + const text = at(event); + if (text === drag.text) return; + drag.text = text; + pending(text); + }); + slider.addEventListener('pointerup', event => { + if (!drag || event.pointerId !== drag.id) return; + const text = drag.text; + drag = null; + if (slider.hasPointerCapture(event.pointerId)) slider.releasePointerCapture(event.pointerId); + commit(text); + }); + slider.addEventListener('lostpointercapture', () => { if (drag) cancel(); }); + slider.addEventListener('pointercancel', () => { if (drag) cancel(); }); + slider.addEventListener('keydown', event => { + if (event.key === 'Escape' && (drag || held !== null)) { event.preventDefault(); event.stopPropagation(); cancel(); return; } + if (drag || !SLIDE_KEYS.has(event.key) || event.altKey || event.ctrlKey || event.metaKey) return; + event.preventDefault(); + if (muted && event.repeat) return; + muted = false; + const base = held === null && flying !== null ? parse(key, flying) : null; + if (base) paint(base, 'set', flying!); + const span = range(key, shown.unit)!; + const up = event.key === 'ArrowRight' || event.key === 'ArrowUp' || event.key === 'PageUp'; + const times = (event.shiftKey || event.key.startsWith('Page') ? 10 : 1) * (up ? 1 : -1); + const digits = places(span.step); + const text = event.key === 'Home' ? format(span.min, shown.unit, digits) : event.key === 'End' ? format(span.max, shown.unit, digits) : slide(key, shown, times); + hold(text); + }); + slider.addEventListener('keyup', event => { if (SLIDE_KEYS.has(event.key)) { muted = false; flush(); } }); + slider.addEventListener('blur', flush); + + field.input.addEventListener('keydown', event => { + if (event.key === 'Escape' && held !== null) { event.preventDefault(); cancel(); return; } + if (raw || (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') || event.altKey || event.ctrlKey || event.metaKey || event.isComposing) return; + const amount = parse(key, field.input.value); + if (!amount) return; + event.preventDefault(); + if (muted && event.repeat) return; + muted = false; + const text = step(key, amount, (event.shiftKey ? 10 : 1) * (event.key === 'ArrowUp' ? 1 : -1)); + hold(text); + }); + field.input.addEventListener('keyup', event => { if (event.key === 'ArrowUp' || event.key === 'ArrowDown') { muted = false; flush(); } }); + field.input.addEventListener('blur', flush); + + chooser?.addEventListener('change', () => { + const unit = chooser.value; + flush(); + const amount = parse(key, field.input.value); + if (!field.input.value.trim() || !amount) { chosen = unit; again(); return; } + const text = format(amount.n, unit, 6); + pending(text); + commit(text); + }); + + return { + sync(value, inherited) { + if (drag || held !== null) return parse(key, value) !== null; + return showing(value, inherited); + }, + cancel: abandon, + setRaw(next) { + raw = next; + if (next && drag) cancel(); + if (next) flush(); + }, + }; +} + +export function register(): void { + registerControl(Object.keys(SCALES), create); +} diff --git a/frontend/src/features/inspector/controls/types.ts b/frontend/src/features/inspector/controls/types.ts new file mode 100644 index 00000000..114af57e --- /dev/null +++ b/frontend/src/features/inspector/controls/types.ts @@ -0,0 +1,42 @@ +import type { EditorState } from '../../../types'; + +export interface StyleField { + readonly key: string; + readonly label: string; + readonly input: HTMLInputElement; + readonly wrapper: HTMLElement; + readonly lead: HTMLElement; + readonly trail: HTMLElement; + readonly below: HTMLElement; + value(): string; + inherited(): string; + show(value: string): void; + restore(): void; + commit(value: string): Promise; +} + +export interface ColorToken { name: string; value: string; css: string; group: 'site' | 'brand' | 'team' } + +export interface ControlHost { + readonly overlay: HTMLElement; + state(): EditorState | undefined; + colors(): ColorToken[]; + restricted(): boolean; + status(message: string, error?: boolean): void; +} + +export interface Control { + sync(value: string, inherited: string): boolean; + setRaw?(raw: boolean): void; + cancel?(): void; +} + +export type ControlFactory = (field: StyleField, host: ControlHost) => Control; + +export interface ControlKit { + sync(): void; + raw(key: string): boolean; + setRaw(key: string, raw: boolean): void; + defaultRaw(): boolean; + setDefaultRaw(raw: boolean): void; +} diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 98bf6c37..56a6a306 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -40,6 +40,7 @@ import { installInspector } from './features/inspector'; import { installPageBackground, startChoices, startCommands } from './features/inspector/page-background'; import { installCanvasMenu } from './features/canvas-menu'; import { installInspectorSearch, sectionId } from './features/inspector/search'; +import { installControls } from './features/inspector/controls'; import { installLibrary } from './features/library'; import { convertSections, installConvert } from './features/convert'; import { installInsertFlyout } from './features/panel/insert-flyout'; @@ -227,7 +228,7 @@ function setStyle(name: string, content: string): Promise { return Promise.reject(new Error('Brand restriction is on: pick a brand or team library value from the list (var(--brand-...) or var(--lib-...)), or ask a project manager to turn it off in Window > Brand kit.')); } const next = { [name]: entered || null }; - return nodePatch(breakpoint === 'desktop' ? { styles: next } : { breakpoints: { [breakpoint]: next } }); + return controlKit.track(name, entered, nodePatch(breakpoint === 'desktop' ? { styles: next } : { breakpoints: { [breakpoint]: next } })); } function setAttribute(name: string, content: string): Promise { return nodePatch({ attrs: { [name]: content.trim() || null } }); @@ -1232,6 +1233,13 @@ const inspectorExt = installInspector({ panes: { design: designPane, content: contentPane, tokens: tokensPane, motion: motionPane }, anchors: { afterAttributes: attributesSection, stageBefore: viewportReadout } }); +const controlKit = installControls({ + fields: styleFields, overlay, state: () => lastState, setStyle, scope: key => `${currentNode().id}|${breakpoint}|${key}`, + setStyles: styles => { const next = Object.fromEntries(Object.entries(styles).map(([name, content]) => [name, content.trim() || null])); return nodePatch(breakpoint === 'desktop' ? { styles: next } : { breakpoints: { [breakpoint]: next } }); }, + status: (message, error) => status(message, error), + values: key => { const node = currentNode(); return { value: (breakpoint === 'desktop' ? node.styles : node.breakpoints[breakpoint] || {})[key] || '', inherited: node.styles[key] || '' }; }, + changed: () => { value(designFieldsSelect, controlKit.defaultRaw() ? 'css' : 'controls'); designFieldsAll.disabled = !controlKit.own(); } +}); const settingsPane = dialogPane('settings'); applyTheme(); const themeSelect = select(Object.entries(THEMES).map(([id, profile]) => ({ id, name: profile.label }))); @@ -1251,6 +1259,12 @@ autoShowHome.checked = homePref(); autoShowHome.addEventListener('change', () => setHomePref(autoShowHome.checked)); const autoShowHomeLabel = element('label', 'checkbox-field'); autoShowHomeLabel.append(autoShowHome, element('span', '', 'Show the Home screen at launch')); +const designFieldsSelect = select([{ id: 'controls', name: 'Controls' }, { id: 'css', name: 'CSS text' }]); +designFieldsSelect.value = controlKit.defaultRaw() ? 'css' : 'controls'; +designFieldsSelect.addEventListener('change', () => controlKit.setDefaultRaw(designFieldsSelect.value === 'css')); +const designFieldsAll = button('Use for all fields', undefined, () => { controlKit.clearRaw(); status('Every Design field now follows this setting.'); }); +designFieldsAll.disabled = !controlKit.own(); +const designFieldsNote = element('p', 'micro', 'Controls puts sliders, color swatches and choosers next to the Design fields; CSS text shows the typed value only. The switch in a field\'s label changes that field alone.'); const prefsIcons: Record = { General: 'pfGeneral', Interface: 'pfInterface', Plugins: 'pfPlugins' }; const prefsPages = element('div', 'fw-prefs-pages'); const prefsNav = element('div', 'fw-prefs-nav'); @@ -1419,7 +1433,7 @@ resetPrefs.addEventListener('click', () => { resetPrefs.hidden = true; resetRow. 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('Interface', prefsGroup('Theme', field('Editor theme', themeSelect)), prefsGroup('Language', field('Editor language', languageSelect))); +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)); prefsAdd('Plugins', prefsGroup('Server access', tokenNote, field('Server access token', authToken), endpointNote)); settingsPane.append(prefsPages); prefsMark('General'); @@ -1563,9 +1577,10 @@ function update(next: EditorState): void { text(scopeLabel, breakpoint === 'desktop' ? 'Desktop base' : breakpoint + ' override'); const override = breakpoint === 'desktop' ? node.styles : node.breakpoints[breakpoint] || {}; styleFields.forEach((control, name) => { - value(control, override[name] || ''); + value(control, controlKit.shown(name, override[name] || '')); if (control instanceof HTMLInputElement) control.placeholder = node.styles[name] || 'Auto / inherit'; }); + controlKit.sync(); segmentFields.forEach((buttons, name) => { const own = override[name] || ''; const inherited = breakpoint === 'desktop' ? '' : node.styles[name] || ''; @@ -2292,6 +2307,7 @@ registerCommands([ { id: 'view.refresh', label: 'Refresh live responsive preview', menu: 'View', group: 1, run: () => { runtimePreview.refresh(); if (!preview) { preview = true; update(state()); } }, enabled: ready }, { id: 'view.preview-full', label: 'Preview as published', menu: 'View', keys: ['Mod+Shift+P'], group: 1, run: () => fullPreview.toggle(), enabled: ready }, { 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.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/control-slider.css b/frontend/src/styles/control-slider.css new file mode 100644 index 00000000..6f8fee5f --- /dev/null +++ b/frontend/src/styles/control-slider.css @@ -0,0 +1,11 @@ +.fw-slider { --at: 0; position: relative; display: block; width: 100%; height: var(--range-box); cursor: pointer; touch-action: none; user-select: none; border-radius: var(--radius-pill); outline: none; } +.fw-slider-track { position: absolute; left: calc(var(--range-thumb) / 2); right: calc(var(--range-thumb) / 2); top: calc((var(--range-box) - var(--range-track)) / 2); height: var(--range-track); border-radius: var(--radius-pill); background: var(--range-track-bg); overflow: hidden; pointer-events: none; } +.fw-slider-fill { position: absolute; inset: 0 auto 0 0; width: calc(var(--at) * 100%); background: var(--accent-line); } +.fw-slider-thumb { position: absolute; top: calc((var(--range-box) - var(--range-thumb)) / 2); left: calc(var(--at) * (100% - var(--range-thumb))); box-sizing: border-box; width: var(--range-thumb); height: var(--range-thumb); border: 2px solid var(--bg-tertiary); border-radius: 50%; background: var(--accent-color); pointer-events: none; } +.fw-slider[data-state='inherited'] .fw-slider-thumb { background: var(--text-muted); } +.fw-slider[data-state='inherited'] .fw-slider-fill { background: var(--line-3); } +.fw-slider[data-state='unset'] .fw-slider-thumb { background: var(--bg-tertiary); border-color: var(--line-3); } +.fw-slider[data-state='unset'] .fw-slider-fill { width: 0; } +.fw-slider:hover .fw-slider-thumb { border-color: var(--line-3); } +.fw-slider:focus-visible .fw-slider-thumb { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fw-unit { --select-room: var(--space-4); --select-edge: var(--space-1); flex: none; width: auto; min-width: 0; align-self: stretch; min-height: 0; padding-left: var(--space-1); font-size: var(--fs-11); color: var(--text-secondary); } diff --git a/frontend/src/styles/controls.css b/frontend/src/styles/controls.css new file mode 100644 index 00000000..77671fde --- /dev/null +++ b/frontend/src/styles/controls.css @@ -0,0 +1,22 @@ +.fw-ctl-row { display: flex; align-items: center; min-width: 0; } +.fw-ctl-row > input { flex: 1 1 auto; min-width: 0; width: auto; text-overflow: ellipsis; } +.fw-ctl-lead, .fw-ctl-trail { display: inline-flex; flex: 0 0 auto; align-items: center; gap: var(--space-1); min-width: 0; } +.fw-ctl-lead:not(:empty) { margin-right: var(--space-1); } +.fw-ctl-trail:not(:empty) { margin-left: var(--space-1); } +.fw-ctl-lead:empty, .fw-ctl-trail:empty, .fw-ctl-below:empty { display: none; } +.fw-ctl-below { display: block; min-width: 0; } +.fw-ctl[data-ctl='off'] .fw-ctl-slot, .fw-ctl[data-ctl='raw'] .fw-ctl-below { visibility: hidden; } +.fw-ctl[data-ctl='raw'] .fw-ctl-lead, .fw-ctl[data-ctl='raw'] .fw-ctl-trail { display: none; } + +.fw-ctl-raw { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; width: 22px; min-height: 0; height: 18px; padding: 0; border: 0; border-radius: var(--radius-pill); background: transparent; color: var(--text-secondary); cursor: pointer; } +.fw-ctl-raw .icon, .fw-ctl-raw svg { width: 12px; height: 12px; } +.fw-ctl-raw:hover { background: var(--bg-hover); color: var(--text-primary); } +.fw-ctl-raw[aria-pressed='true'] { background: var(--accent-tint-strong); color: var(--accent-color); } +.fw-ctl-raw:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.field-label > .fw-reset[hidden] + .fw-ctl-raw { margin-left: auto; } + +.inspector .form-grid > .field.fw-ctl:not(.full) > .field-label { padding-right: 24px; } +.inspector .form-grid > .field.fw-ctl:not(.full) > .field-label > .fw-ctl-raw { position: absolute; top: 0; right: 0; background: var(--bg-secondary); } +.inspector .form-grid > .field.fw-ctl:not(.full) > .field-label > .fw-ctl-raw:hover { background: linear-gradient(var(--bg-hover), var(--bg-hover)), var(--bg-secondary); } +.inspector .form-grid > .field.fw-ctl:not(.full) > .field-label > .fw-ctl-raw[aria-pressed='true'] { background: linear-gradient(var(--accent-tint-strong), var(--accent-tint-strong)), var(--bg-secondary); } +.inspector .form-grid > .field.fw-ctl:not(.full) > .field-label > .fw-reset { right: 24px; max-width: calc(100% - 24px); } From a0cba840c1fa087b87391c1fe8b48df998157f03 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 00:37:24 -0500 Subject: [PATCH 21/31] feat(inspector): Color and Background show a swatch that opens a color picker with a saturation and brightness square, hue and opacity bars, a hex or rgb() entry, the site's, brand and team colors by name, an eyedropper where the browser has one, and No color; a free color is written as hex, a named color as its var(), and the brand restriction offers only brand and team colors --- .../features/inspector/controls/color-area.ts | 259 ++++++++ .../features/inspector/controls/color-math.ts | 186 ++++++ .../inspector/controls/color-picker.ts | 567 ++++++++++++++++++ .../src/features/inspector/controls/color.ts | 109 ++++ .../src/features/inspector/controls/index.ts | 2 + .../features/inspector/controls/picker-api.ts | 29 + frontend/src/styles/control-color.css | 59 ++ 7 files changed, 1211 insertions(+) create mode 100644 frontend/src/features/inspector/controls/color-area.ts create mode 100644 frontend/src/features/inspector/controls/color-math.ts create mode 100644 frontend/src/features/inspector/controls/color-picker.ts create mode 100644 frontend/src/features/inspector/controls/color.ts create mode 100644 frontend/src/features/inspector/controls/picker-api.ts create mode 100644 frontend/src/styles/control-color.css diff --git a/frontend/src/features/inspector/controls/color-area.ts b/frontend/src/features/inspector/controls/color-area.ts new file mode 100644 index 00000000..71f397c7 --- /dev/null +++ b/frontend/src/features/inspector/controls/color-area.ts @@ -0,0 +1,259 @@ +import { labelAttr } from '../../../i18n'; +import { element } from '../../../ui/dom'; +import { hsvToRgb, hueStops, parseEntry, rgbToHsv, sameColor, toHex, toRgb, type Hsva, type Rgba } from './color-math'; +import type { ColorArea, ColorAreaOptions } from './picker-api'; + +export interface AreaOptions extends ColorAreaOptions { + resolve(color: string): Rgba | null; + cancel?(): void; +} +export interface Area extends ColorArea { + dragging(): boolean; + dropping(): boolean; + relabel(name: string): void; + cancel(): boolean; +} + +interface EyeDropperResult { sRGBHex: string } +interface EyeDropperLike { open(): Promise } +type EyeDropperCtor = new () => EyeDropperLike; + +const DROPPER = ''; +const STEP_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End']); +const clamp = (value: number, low = 0, high = 1): number => Math.min(high, Math.max(low, value)); +const tinted = (hsv: Hsva): Hsva => hsv.s < 0.05 || hsv.v < 0.05 ? { ...hsv, s: 0.7, v: 0.85 } : hsv; + +export function eyeDropper(): EyeDropperCtor | null { + const ctor = (window as unknown as { EyeDropper?: EyeDropperCtor }).EyeDropper; + return typeof ctor === 'function' ? ctor : null; +} + +function slider(className: string): HTMLElement { + const node = element('div', className); + node.tabIndex = 0; + node.setAttribute('role', 'slider'); + node.append(element('span', 'fw-ca-thumb')); + return node; +} + +export function createColorArea(options: AreaOptions): Area { + const root = element('div', 'fw-ca'); + const square = slider('fw-ca-square'); + square.setAttribute('aria-valuemin', '0'); + square.setAttribute('aria-valuemax', '100'); + const hue = slider('fw-ca-bar fw-ca-hue'); + hue.setAttribute('aria-valuemin', '0'); + hue.setAttribute('aria-valuemax', '360'); + hue.style.backgroundImage = `linear-gradient(to right, ${hueStops()})`; + const alpha = slider('fw-ca-bar fw-ca-alpha'); + alpha.setAttribute('aria-valuemin', '0'); + alpha.setAttribute('aria-valuemax', '100'); + const alphaFill = element('span', 'fw-ca-fill'); + alpha.prepend(alphaFill); + const white = toRgb({ r: 255, g: 255, b: 255, a: 1 }); + const clear = toRgb({ r: 255, g: 255, b: 255, a: 0 }); + const black = toRgb({ r: 0, g: 0, b: 0, a: 1 }); + const none = toRgb({ r: 0, g: 0, b: 0, a: 0 }); + square.style.backgroundImage = `linear-gradient(to top, ${black}, ${none}), linear-gradient(to right, ${white}, ${clear})`; + const row = element('div', 'fw-ca-row'); + const preview = element('span', 'fw-ca-preview'); + preview.append(element('span', 'fw-ca-preview-fill')); + const entry = element('input', 'fw-ca-entry'); + entry.type = 'text'; + entry.spellcheck = false; + entry.autocomplete = 'off'; + const relabel = (name: string): void => { + labelAttr(square, 'aria-label', 'Saturation and brightness of {0}', [{ t: name }]); + labelAttr(hue, 'aria-label', 'Hue of {0}', [{ t: name }]); + labelAttr(alpha, 'aria-label', 'Opacity of {0}', [{ t: name }]); + labelAttr(entry, 'aria-label', 'Hex or rgb() value of {0}', [{ t: name }]); + }; + relabel(options.label); + row.append(preview, entry); + const Dropper = eyeDropper(); + let dropping = false; + if (Dropper) { + const pick = element('button', 'fw-ca-dropper'); + pick.type = 'button'; + pick.innerHTML = DROPPER; + labelAttr(pick, 'aria-label', 'Pick a color from the screen'); + labelAttr(pick, 'title', 'Pick a color from the screen'); + pick.addEventListener('click', () => { + if (dropping) return; + dropping = true; + root.dataset.dropping = 'true'; + new Dropper().open().then(result => { + const color = options.resolve(result.sRGBHex); + if (!color) return; + const keep = hsv.a; + setRgba({ ...color, a: keep }); + options.commit(api.get()); + }, () => undefined).finally(() => { dropping = false; delete root.dataset.dropping; }); + }); + row.append(pick); + } + root.append(square, hue, alpha, row); + + let hsv: Hsva = { h: 0, s: 0, v: 0, a: 1 }; + let start = ''; + let drag: HTMLElement | null = null; + let pending = false; + + function setRgba(color: Rgba): void { + const next = rgbToHsv(color); + if (next.s === 0 || next.v === 0) next.h = hsv.h; + if (next.v === 0) next.s = hsv.s; + hsv = next; + paint(); + } + + function paint(): void { + const color = hsvToRgb(hsv); + const solid = toRgb({ ...color, a: 1 }); + square.style.backgroundColor = toRgb(hsvToRgb({ h: hsv.h, s: 1, v: 1, a: 1 })); + square.style.setProperty('--x', String(hsv.s)); + square.style.setProperty('--y', String(1 - hsv.v)); + square.style.setProperty('--thumb', solid); + hue.style.setProperty('--x', String(hsv.h / 360)); + alpha.style.setProperty('--x', String(hsv.a)); + alphaFill.style.backgroundImage = `linear-gradient(to right, ${toRgb({ ...color, a: 0 })}, ${solid})`; + (preview.firstChild as HTMLElement).style.backgroundColor = toRgb(color); + const s = Math.round(hsv.s * 100); + const v = Math.round(hsv.v * 100); + square.setAttribute('aria-valuenow', String(s)); + square.setAttribute('aria-valuetext', `${s}%, ${v}%`); + hue.setAttribute('aria-valuenow', String(Math.round(hsv.h))); + hue.setAttribute('aria-valuetext', `${Math.round(hsv.h)}°`); + alpha.setAttribute('aria-valuenow', String(Math.round(hsv.a * 100))); + alpha.setAttribute('aria-valuetext', `${Math.round(hsv.a * 100)}%`); + if (document.activeElement !== entry) { + const hex = toHex(color); + if (entry.value !== hex) entry.value = hex; + } + } + + function moveTo(target: HTMLElement, event: PointerEvent): void { + const box = target.getBoundingClientRect(); + const x = clamp((event.clientX - box.left) / Math.max(1, box.width)); + const y = clamp((event.clientY - box.top) / Math.max(1, box.height)); + if (target === square) hsv = { ...hsv, s: x, v: 1 - y }; + else if (target === hue) hsv = { ...tinted(hsv), h: Math.min(359.999, x * 360) }; + else hsv = { ...hsv, a: Math.round(x * 100) / 100 }; + paint(); + options.input(api.get()); + } + + function finish(commit: boolean): void { + if (!drag) return; + const target = drag; + drag = null; + delete root.dataset.dragging; + if (target.hasPointerCapture?.(activePointer)) target.releasePointerCapture(activePointer); + if (commit && api.get() !== start) options.commit(api.get()); + } + + let activePointer = -1; + for (const target of [square, hue, alpha]) { + target.addEventListener('pointerdown', event => { + if (event.button !== 0 || drag) return; + event.preventDefault(); + target.focus({ preventScroll: true }); + drag = target; + activePointer = event.pointerId; + start = api.get(); + root.dataset.dragging = 'true'; + target.setPointerCapture(event.pointerId); + moveTo(target, event); + }); + target.addEventListener('pointermove', event => { if (drag === target && event.pointerId === activePointer) moveTo(target, event); }); + target.addEventListener('pointerup', event => { if (drag === target && event.pointerId === activePointer) finish(true); }); + target.addEventListener('pointercancel', () => { if (drag === target) cancel(); }); + target.addEventListener('lostpointercapture', () => { if (drag === target) finish(true); }); + target.addEventListener('keydown', event => { + if (!STEP_KEYS.has(event.key) || drag) return; + event.preventDefault(); + if (!pending) start = api.get(); + const big = event.shiftKey || event.key === 'PageUp' || event.key === 'PageDown'; + const sign = event.key === 'ArrowLeft' || event.key === 'ArrowDown' || event.key === 'PageDown' ? -1 : 1; + const written = api.get(); + for (let tries = 0; tries < 100; tries++) { + const was = hsv; + if (target === square) { + const step = (big ? 0.1 : 0.01) * sign; + if (event.key === 'Home') hsv = { ...hsv, s: 0 }; + else if (event.key === 'End') hsv = { ...hsv, s: 1 }; + else if (event.key === 'ArrowUp' || event.key === 'ArrowDown') hsv = { ...hsv, v: clamp(hsv.v + step) }; + else hsv = { ...hsv, s: clamp(hsv.s + step) }; + } else if (target === hue) { + const next = event.key === 'Home' ? 0 : event.key === 'End' ? 359 : hsv.h + (big ? 10 : 1) * sign; + hsv = { ...tinted(hsv), h: clamp(next, 0, 359) }; + } else { + const next = event.key === 'Home' ? 0 : event.key === 'End' ? 1 : hsv.a + (big ? 0.1 : 0.01) * sign; + hsv = { ...hsv, a: Math.round(clamp(next) * 100) / 100 }; + } + if (api.get() !== written || hsv.h === was.h && hsv.s === was.s && hsv.v === was.v && hsv.a === was.a) break; + } + pending = true; + paint(); + options.input(api.get()); + }); + target.addEventListener('keyup', event => { if (STEP_KEYS.has(event.key)) settle(); }); + target.addEventListener('blur', settle); + } + + function settle(): void { + if (!pending) return; + pending = false; + if (api.get() !== start) options.commit(api.get()); + } + + function cancel(): boolean { + if (!drag) return false; + const target = drag; + drag = null; + delete root.dataset.dragging; + if (target.hasPointerCapture?.(activePointer)) target.releasePointerCapture(activePointer); + const before = options.resolve(start); + if (before) setRgba(before); + if (options.cancel) options.cancel(); else options.input(start); + return true; + } + + let entered = ''; + function typed(): void { + const text = entry.value.trim(); + if (text === entered) return; + const color = parseEntry(text); + entry.removeAttribute('aria-invalid'); + if (!color) { entry.value = api.get(); entered = entry.value; return; } + setRgba(color); + entry.value = api.get(); + entered = entry.value; + options.commit(api.get()); + } + entry.addEventListener('focus', () => { entered = entry.value.trim(); }); + entry.addEventListener('keydown', event => { + if (event.key === 'Enter') { event.preventDefault(); typed(); } + }); + entry.addEventListener('input', () => { + if (parseEntry(entry.value) || !entry.value.trim()) entry.removeAttribute('aria-invalid'); else entry.setAttribute('aria-invalid', 'true'); + }); + entry.addEventListener('change', typed); + entry.addEventListener('blur', () => { entry.removeAttribute('aria-invalid'); paint(); }); + + const api: Area = { + element: root, + set(color: string) { + const parsed = options.resolve(color); + if (!parsed || drag || sameColor(parsed, hsvToRgb(hsv))) return; + setRgba(parsed); + }, + get: () => toHex(hsvToRgb(hsv)), + dragging: () => !!drag, + dropping: () => dropping, + relabel, + cancel + }; + paint(); + return api; +} diff --git a/frontend/src/features/inspector/controls/color-math.ts b/frontend/src/features/inspector/controls/color-math.ts new file mode 100644 index 00000000..222efa32 --- /dev/null +++ b/frontend/src/features/inspector/controls/color-math.ts @@ -0,0 +1,186 @@ +export interface Rgba { r: number; g: number; b: number; a: number } +export interface Hsva { h: number; s: number; v: number; a: number } + +const clamp = (value: number, low: number, high: number): number => Math.min(high, Math.max(low, value)); +const NUMBER = '[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?'; + +export function parseHex(text: string): Rgba | null { + const match = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(text.trim()); + if (!match) return null; + let digits = match[1]; + if (digits.length <= 4) digits = digits.split('').map(digit => digit + digit).join(''); + const at = (index: number): number => parseInt(digits.slice(index, index + 2), 16); + return { r: at(0), g: at(2), b: at(4), a: digits.length === 8 ? at(6) / 255 : 1 }; +} + +function args(text: string, names: string): string[] | null { + const match = new RegExp(`^(?:${names})\\(\\s*([^()]*)\\)$`, 'i').exec(text.trim()); + if (!match) return null; + const body = match[1].trim(); + const parts = body.includes(',') ? body.split(',').map(part => part.trim()) : body.split('/').length === 2 + ? [...body.split('/')[0].trim().split(/\s+/), body.split('/')[1].trim()] : body.split(/\s+/); + if (body.includes(',') && body.includes('/')) return null; + return parts.length === 3 || parts.length === 4 ? parts : null; +} + +function number(part: string, percentScale: number | null): number | null { + const match = new RegExp(`^(${NUMBER})(%?)$`, 'i').exec(part); + if (!match) return null; + const value = Number(match[1]); + if (!Number.isFinite(value)) return null; + if (match[2]) return percentScale === null ? null : value / 100 * percentScale; + return value; +} + +function alpha(part: string | undefined): number | null { + if (part === undefined) return 1; + const value = number(part, 1); + return value === null ? null : clamp(value, 0, 1); +} + +export function parseRgb(text: string): Rgba | null { + const parts = args(text, 'rgba?'); + if (!parts) return null; + const channels = parts.slice(0, 3).map(part => number(part, 255)); + const a = alpha(parts[3]); + if (channels.some(value => value === null) || a === null) return null; + const [r, g, b] = channels.map(value => clamp(value as number, 0, 255)); + return { r, g, b, a }; +} + +function hue(part: string): number | null { + const match = new RegExp(`^(${NUMBER})(deg|turn|rad|grad)?$`, 'i').exec(part); + if (!match) return null; + const value = Number(match[1]); + const unit = (match[2] || 'deg').toLowerCase(); + const degrees = unit === 'turn' ? value * 360 : unit === 'rad' ? value * 180 / Math.PI : unit === 'grad' ? value * 0.9 : value; + return ((degrees % 360) + 360) % 360; +} + +export function hslToRgb(h: number, s: number, l: number, a = 1): Rgba { + const chroma = (1 - Math.abs(2 * l - 1)) * s; + const f = (n: number): number => { + const k = (n + h / 30) % 12; + return l - chroma / 2 * Math.max(-1, Math.min(k - 3, 9 - k, 1)); + }; + return { r: f(0) * 255, g: f(8) * 255, b: f(4) * 255, a }; +} + +export function parseHsl(text: string): Rgba | null { + const parts = args(text, 'hsla?'); + if (!parts) return null; + const h = hue(parts[0]); + const s = number(parts[1].replace(/%$/, ''), null); + const l = number(parts[2].replace(/%$/, ''), null); + const a = alpha(parts[3]); + if (h === null || s === null || l === null || a === null) return null; + return hslToRgb(h, clamp(s / 100, 0, 1), clamp(l / 100, 0, 1), a); +} + +export function parseColor(text: string): Rgba | null { + const value = text.trim(); + if (value.startsWith('#')) return parseHex(value); + if (/^rgba?\(/i.test(value)) return parseRgb(value); + if (/^hsla?\(/i.test(value)) return parseHsl(value); + return null; +} + +export function parseEntry(text: string): Rgba | null { + const value = text.trim(); + return /^rgba?\(/i.test(value) ? parseRgb(value) : parseHex(value); +} + +export function rgbToHsv({ r, g, b, a }: Rgba): Hsva { + const red = r / 255; + const green = g / 255; + const blue = b / 255; + const max = Math.max(red, green, blue); + const delta = max - Math.min(red, green, blue); + let h = 0; + if (delta) { + if (max === red) h = ((green - blue) / delta) % 6; + else if (max === green) h = (blue - red) / delta + 2; + else h = (red - green) / delta + 4; + h = (h * 60 + 360) % 360; + } + return { h, s: max ? delta / max : 0, v: max, a }; +} + +export function hsvToRgb({ h, s, v, a }: Hsva): Rgba { + const f = (n: number): number => { + const k = (n + h / 60) % 6; + return (v - v * s * Math.max(0, Math.min(k, 4 - k, 1))) * 255; + }; + return { r: f(5), g: f(3), b: f(1), a }; +} + +const byte = (value: number): string => Math.round(clamp(value, 0, 255)).toString(16).padStart(2, '0'); + +export function toHex(color: Rgba): string { + const opaque = Math.round(clamp(color.a, 0, 1) * 255) >= 255; + return `#${byte(color.r)}${byte(color.g)}${byte(color.b)}${opaque ? '' : byte(color.a * 255)}`; +} + +export function toRgb(color: Rgba): string { + const channels = [color.r, color.g, color.b].map(value => Math.round(clamp(value, 0, 255))).join(', '); + const a = Math.round(clamp(color.a, 0, 1) * 1000) / 1000; + return a >= 1 ? `rgb(${channels})` : `rgba(${channels}, ${a})`; +} + +export function sameColor(one: Rgba | null, two: Rgba | null): boolean { + if (!one || !two) return one === two; + return toHex(one) === toHex(two); +} + +export function hueStops(steps = 6): string { + return Array.from({ length: steps + 1 }, (_, index) => toHex(hsvToRgb({ h: index * 360 / steps % 360, s: 1, v: 1, a: 1 }))).join(', '); +} + +export function topLevelCommas(text: string): number { + let depth = 0; + let commas = 0; + let quote = ''; + for (const char of text) { + if (quote) { if (char === quote) quote = ''; continue; } + if (char === '"' || char === '\'') quote = char; + else if (char === '(') depth++; + else if (char === ')') depth--; + else if (char === ',' && depth === 0) commas++; + } + return commas; +} + +export function isGradient(text: string): boolean { + const value = text.trim(); + return /^(?:repeating-)?(?:linear|radial|conic)-gradient\(.*\)$/is.test(value) && closesAtEnd(value); +} + +function closesAtEnd(text: string): boolean { + let depth = 0; + for (let index = 0; index < text.length; index++) { + if (text[index] === '(') depth++; + else if (text[index] === ')') { depth--; if (depth === 0) return index === text.length - 1; } + } + return false; +} + +export function gradientColors(text: string): string[] { + const value = text.trim(); + if (!isGradient(value)) return []; + const inner = value.slice(value.indexOf('(') + 1, -1); + const parts: string[] = []; + let depth = 0; + let from = 0; + for (let index = 0; index <= inner.length; index++) { + const char = inner[index]; + if (char === '(') depth++; + else if (char === ')') depth--; + else if (index === inner.length || char === ',' && depth === 0) { parts.push(inner.slice(from, index).trim()); from = index + 1; } + } + return parts.map(part => part.replace(/(?:\s+[-+]?(?:\d+\.?\d*|\.\d+)(?:%|[a-z]+)?)+$/i, '').trim()).filter(Boolean); +} + +export function varName(text: string): string | null { + const match = /^var\(\s*(--[a-z0-9_-]+)\s*\)$/i.exec(text.trim()); + return match ? match[1] : null; +} diff --git a/frontend/src/features/inspector/controls/color-picker.ts b/frontend/src/features/inspector/controls/color-picker.ts new file mode 100644 index 00000000..3b5bf697 --- /dev/null +++ b/frontend/src/features/inspector/controls/color-picker.ts @@ -0,0 +1,567 @@ +import { label, labelAttr } from '../../../i18n'; +import { element, keyed } from '../../../ui/dom'; +import { createColorArea, type Area } from './color-area'; +import { gradientColors, parseColor, varName, type Rgba } from './color-math'; +import type { ColorArea, ColorAreaOptions, PickerApi, PickerTab } from './picker-api'; +import type { ColorToken, ControlHost, StyleField } from './types'; + +export interface PickerTarget { + readonly key: string; + readonly label: string; + readonly anchor: HTMLElement; + readonly field?: StyleField; + value(): string; + inherited(): string; + show(value: string): void; + restore(): void; + commit(value: string): Promise; + closed?(): void; +} + +interface Mounted { tab: PickerTab; panel: HTMLElement; areas: Area[]; handle: { open(value: string): boolean; close(): void } } + +const MARGIN = 8; +const GAP = 6; +const SOLID = 'solid'; +const GROUPS: { id: ColorToken['group']; title: string }[] = [ + { id: 'site', title: 'Site colors' }, + { id: 'brand', title: 'Brand' }, + { id: 'team', title: 'Team library' } +]; +const tabs: PickerTab[] = []; +let picker: Picker | null = null; +let probe: CanvasRenderingContext2D | null = null; + +export function registerPickerTab(tab: PickerTab): void { + if (tab.id === SOLID || tabs.some(item => item.id === tab.id)) throw new Error(`picker tab already registered: ${tab.id}`); + tabs.push(tab); + picker?.mountTab(tab); +} + +export function browserColor(value: string): Rgba | null { + const text = value.trim(); + if (!text || /var\(|currentcolor|inherit|initial|unset|revert/i.test(text) || !CSS.supports('color', text)) return null; + const exact = parseColor(text); + if (exact) return exact; + probe ??= document.createElement('canvas').getContext('2d', { willReadFrequently: true }); + if (!probe) return null; + probe.fillStyle = '#000000'; + probe.fillStyle = text; + const read = parseColor(String(probe.fillStyle)); + if (read) return read; + probe.clearRect(0, 0, 1, 1); + probe.fillRect(0, 0, 1, 1); + const [r, g, b, a] = probe.getImageData(0, 0, 1, 1).data; + return { r, g, b, a: a / 255 }; +} + +export function tokenFor(tokens: ColorToken[], value: string): ColorToken | undefined { + const name = varName(value); + return name ? tokens.find(token => varName(token.css) === name) : undefined; +} + +let memo: { state: unknown; tokens: ColorToken[] } | null = null; +export function colorTokens(host: ControlHost): ColorToken[] { + const state = host.state(); + if (memo && memo.state === state && state) return memo.tokens; + const tokens = host.colors(); + memo = { state, tokens }; + const known = new Set(tokens.map(token => varName(token.css))); + for (const [name, value] of Object.entries(state?.site.tokens || {})) { + const bare = name.replace(/^--/, ''); + const css = `var(--${bare})`; + if (!known.has(`--${bare}`) && /var\(|calc\(/i.test(String(value)) && siteColor(host, css)) tokens.push({ name: bare, value: String(value), css, group: 'site' }); + } + return tokens; +} + +export function resolveColor(tokens: ColorToken[], value: string, depth = 0): Rgba | null { + const token = tokenFor(tokens, value); + if (token) return depth < 4 ? resolveColor(tokens, token.value, depth + 1) : null; + return parseColor(value) || browserColor(value); +} + +const SENTINELS = ['rgba(1, 2, 3, 0.5)', 'rgba(4, 5, 6, 0.5)']; +let sheet: { state: unknown; root: HTMLElement; probe: HTMLElement; names: Set; cache: Map } | null = null; + +function siteSheet(host: ControlHost): NonNullable | null { + const state = host.state(); + if (!state) return null; + if (!sheet) { + const root = element('div', 'fw-cp-site'); + root.hidden = true; + root.setAttribute('aria-hidden', 'true'); + const probe = element('span'); + root.append(probe); + host.overlay.append(root); + sheet = { state: null, root, probe, names: new Set(), cache: new Map() }; + } + if (sheet.state !== state) { + const tokens = Object.entries(state.site.tokens || {}).map(([name, value]) => [`--${name.replace(/^--/, '')}`, String(value)] as const); + const next = new Set(tokens.map(([name]) => name)); + for (const name of sheet.names) if (!next.has(name)) sheet.root.style.removeProperty(name); + for (const [name, value] of tokens) if (sheet.root.style.getPropertyValue(name) !== value) sheet.root.style.setProperty(name, value); + sheet.names = next; + sheet.state = state; + sheet.cache.clear(); + } + return sheet; +} + +export function siteColor(host: ControlHost, value: string): Rgba | null { + const text = value.trim(); + const names = Array.from(text.matchAll(/var\(\s*(--[a-z0-9_-]+)/gi), match => match[1]); + const site = names.length ? siteSheet(host) : null; + if (!site || names.some(name => !site.names.has(name))) return null; + if (site.cache.has(text)) return site.cache.get(text)!; + let found: Rgba | null = null; + site.probe.style.color = ''; + site.probe.style.color = text; + if (site.probe.style.color) { + const seen = SENTINELS.map(sentinel => { + site.root.style.color = sentinel; + return getComputedStyle(site.probe).color; + }); + site.root.style.color = ''; + if (seen[0] === seen[1]) found = parseColor(seen[0]) || browserColor(seen[0]); + } + site.cache.set(text, found); + return found; +} + +export function resolveFor(host: ControlHost, value: string): Rgba | null { + return resolveColor(colorTokens(host), value) || (/var\(/i.test(value) ? siteColor(host, value) : null); +} + +export function colorPicker(host: ControlHost): Picker { + picker ??= new Picker(host); + return picker; +} + +export class Picker { + private readonly root = element('div', 'fw-cp'); + private readonly strip = element('div', 'fw-cp-tabs'); + private readonly solid = element('div', 'fw-cp-panel'); + private readonly note = element('p', 'fw-cp-note'); + private readonly sets = element('div', 'fw-cp-sets'); + private readonly clear = element('button', 'fw-cp-clear'); + private readonly area: Area; + private readonly mounted: Mounted[] = []; + private target: PickerTarget | null = null; + private active = SOLID; + private seen = ''; + private frame = 0; + private quiet = false; + private closing = false; + private readonly resized = new ResizeObserver(() => this.place()); + private readonly watch = new MutationObserver(() => this.guard()); + private guardFrame = 0; + + private guard(): void { + cancelAnimationFrame(this.guardFrame); + this.guardFrame = requestAnimationFrame(() => this.keepFocus()); + } + + private keepFocus(): void { + if (this.root.hidden || !this.target || !document.hasFocus()) return; + const now = document.activeElement as HTMLElement | null; + const gone = !now || now === document.body || now === document.documentElement + || now !== this.root && this.root.contains(now) && (!now.getClientRects().length || !!now.closest('[hidden], [inert]') || (now as HTMLButtonElement).disabled === true); + if (!gone) return; + const tab = this.strip.hidden ? null : this.strip.querySelector('[aria-selected="true"]'); + (tab || this.root).focus({ preventScroll: true }); + } + + constructor(private readonly host: ControlHost) { + this.root.hidden = true; + this.root.setAttribute('role', 'dialog'); + this.root.tabIndex = -1; + this.root.dataset.ownKeys = ''; + this.strip.setAttribute('role', 'tablist'); + labelAttr(this.strip, 'aria-label', 'Color kinds'); + this.strip.hidden = true; + this.solid.dataset.tab = SOLID; + this.solid.setAttribute('role', 'tabpanel'); + this.solid.id = 'fw-cp-panel-solid'; + this.note.hidden = true; + label(this.note, 'A project manager restricted colors to the brand kit: choose a brand or team color, or No color.'); + this.area = createColorArea({ + label: 'Color', + resolve: value => this.resolve(value), + input: value => this.show(value), + commit: value => void this.commit(value), + cancel: () => this.restore() + }); + this.solid.append(this.note, this.area.element, this.sets); + this.clear.type = 'button'; + label(this.clear, 'No color'); + this.clear.addEventListener('click', () => { void this.commit(''); this.close(true); }); + const foot = element('div', 'fw-cp-foot'); + foot.append(this.clear); + this.root.append(this.strip, this.solid, foot); + host.overlay.append(this.root); + for (const tab of tabs) this.mountTab(tab); + this.root.addEventListener('keydown', event => this.keys(event)); + this.strip.addEventListener('click', event => { + const button = (event.target as Element).closest('[role="tab"]'); + if (button?.dataset.key) this.select(button.dataset.key, true); + }); + this.sets.addEventListener('click', event => { + const swatch = (event.target as Element).closest('.fw-cp-swatch'); + if (swatch?.dataset.css) this.choose(swatch.dataset.css); + }); + this.sets.addEventListener('keydown', event => this.roam(event)); + } + + mountTab(tab: PickerTab): void { + const panel = element('div', 'fw-cp-panel'); + panel.dataset.tab = tab.id; + panel.id = `fw-cp-panel-${tab.id}`; + panel.setAttribute('role', 'tabpanel'); + panel.hidden = true; + this.root.insertBefore(panel, this.root.lastElementChild); + const areas: Area[] = []; + const api: PickerApi = { + field: () => { + const field = this.target?.field; + if (!field) throw new Error('the color picker is not open on a style field'); + return this.quiet ? { ...field, show() {}, restore() {}, commit: () => Promise.resolve() } as StyleField : field; + }, + colorArea: (options: ColorAreaOptions): ColorArea => { + const area = createColorArea({ ...options, resolve: value => this.resolve(value) }); + areas.push(area); + return area; + }, + colors: () => this.host.colors(), + resolve: value => this.resolve(value), + show: value => this.show(value), + commit: value => this.commit(value) + }; + this.mounted.push({ tab, panel, areas, handle: tab.mount(panel, api) }); + } + + isOpen(target?: PickerTarget): boolean { + return !this.root.hidden && (!target || this.target === target); + } + + toggle(target: PickerTarget): void { + if (this.isOpen(target)) this.close(true); else this.open(target); + } + + open(target: PickerTarget): void { + if (this.target && this.target !== target) this.close(false); + this.target = target; + labelAttr(this.root, 'aria-label', 'Color picker for {0}', [{ t: target.label }]); + this.area.relabel(target.label); + target.anchor.setAttribute('aria-expanded', 'true'); + const value = target.value(); + this.seen = value; + this.paintSets(value); + this.paintTabs(); + const claimed = this.restricted() ? undefined : this.choices().find(item => item.handle.open(value)); + this.setActive(claimed ? claimed.tab.id : SOLID); + if (!claimed) this.area.set(this.solidStart(value)); + this.root.hidden = false; + this.place(); + this.resized.observe(this.root); + this.watch.observe(this.root, { subtree: true, childList: true, attributes: true, attributeFilter: ['hidden', 'inert', 'disabled', 'class'] }); + document.addEventListener('pointerdown', this.outside, true); + window.addEventListener('blur', this.blur); + window.addEventListener('resize', this.reflow); + document.addEventListener('scroll', this.reflow, true); + this.root.addEventListener('focusout', this.leave); + this.focusFirst(); + } + + close(restoreFocus = false): void { + if (this.root.hidden || !this.target || this.closing) return; + this.closing = true; + for (const area of [this.area, ...this.mounted.flatMap(item => item.areas)]) if (area.dragging()) area.cancel(); + const target = this.target; + const hadFocus = this.root.contains(document.activeElement); + for (const item of this.mounted) if (item.tab.id === this.active) item.handle.close(); + this.closing = false; + this.resized.disconnect(); + this.watch.disconnect(); + cancelAnimationFrame(this.guardFrame); + this.root.hidden = true; + this.target = null; + cancelAnimationFrame(this.frame); + document.removeEventListener('pointerdown', this.outside, true); + window.removeEventListener('blur', this.blur); + window.removeEventListener('resize', this.reflow); + document.removeEventListener('scroll', this.reflow, true); + this.root.removeEventListener('focusout', this.leave); + target.anchor.setAttribute('aria-expanded', 'false'); + target.closed?.(); + if ((restoreFocus || hadFocus) && target.anchor.isConnected) target.anchor.focus({ preventScroll: true }); + } + + refresh(target: PickerTarget, value: string): void { + if (!this.isOpen(target)) return; + this.guard(); + this.paintSets(value); + this.paintTabs(); + if (value === this.seen) return; + this.seen = value; + const current = this.mounted.find(item => item.tab.id === this.active); + if (current && !this.restricted() && current.handle.open(value)) return; + if (current) { current.handle.close(); this.setActive(SOLID); } + this.area.set(this.solidStart(value)); + } + + private resolve(value: string): Rgba | null { + return resolveFor(this.host, value); + } + + private solidStart(value: string): string { + const target = this.target; + if (this.resolve(value)) return value; + const stop = gradientColors(value).find(part => this.resolve(part)); + if (stop) return stop; + const inherited = target?.inherited() || ''; + return this.resolve(inherited) ? inherited : '#000000'; + } + + cancel(target: PickerTarget): void { + if (!this.isOpen(target)) return; + this.quiet = true; + try { this.close(false); } finally { this.quiet = false; } + } + + private show(value: string): void { + if (!this.target || this.quiet) return; + this.seen = value; + this.target.show(value); + } + + private restore(): void { + if (!this.target || this.quiet) return; + this.target.restore(); + this.seen = this.target.value(); + } + + private commit(value: string): Promise { + if (!this.target || this.quiet) return Promise.resolve(); + this.seen = value; + return this.target.commit(value).catch(() => undefined); + } + + private choose(css: string): void { + this.area.set(css); + void this.commit(css); + this.paintSets(css); + } + + private restricted(): boolean { + return this.host.restricted(); + } + + private choices(): Mounted[] { + const key = this.target?.key || ''; + return this.mounted.filter(item => item.tab.accepts(key)); + } + + private paintTabs(): void { + const restricted = this.restricted(); + this.root.dataset.restricted = String(restricted); + if (this.note.hidden === restricted) this.note.hidden = !restricted; + if (this.area.element.hidden !== restricted) this.area.element.hidden = restricted; + const list = restricted ? [] : this.choices(); + const items = [{ id: SOLID, label: 'Solid' }, ...list.map(item => ({ id: item.tab.id, label: item.tab.label }))]; + if (this.strip.hidden !== items.length < 2) this.strip.hidden = items.length < 2; + keyed(this.strip, items, item => item.id, () => { + const button = element('button', 'fw-cp-tab'); + button.type = 'button'; + button.setAttribute('role', 'tab'); + return button; + }, (button, item) => { + label(button, item.label); + button.id = `fw-cp-tab-${item.id}`; + button.setAttribute('aria-controls', `fw-cp-panel-${item.id}`); + }); + if (restricted && this.active !== SOLID) this.setActive(SOLID); + } + + private setActive(id: string): void { + this.active = id; + for (const button of Array.from(this.strip.children) as HTMLElement[]) { + const on = button.dataset.key === id; + button.setAttribute('aria-selected', String(on)); + button.tabIndex = on ? 0 : -1; + } + if (this.solid.hidden !== (id !== SOLID)) this.solid.hidden = id !== SOLID; + this.solid.setAttribute('aria-labelledby', 'fw-cp-tab-solid'); + for (const item of this.mounted) { + if (item.panel.hidden !== (item.tab.id !== id)) item.panel.hidden = item.tab.id !== id; + item.panel.setAttribute('aria-labelledby', `fw-cp-tab-${item.tab.id}`); + } + } + + private select(id: string, focus: boolean): void { + if (id === this.active || !this.target) return; + const value = this.target.value(); + for (const item of this.mounted) if (item.tab.id === this.active) item.handle.close(); + this.setActive(id); + const next = this.mounted.find(item => item.tab.id === id); + if (next) next.handle.open(value); else this.area.set(this.solidStart(value)); + this.place(); + if (focus) this.strip.querySelector(`[data-key="${id}"]`)?.focus({ preventScroll: true }); + } + + private paintSets(value: string): void { + const tokens = colorTokens(this.host).map(token => { + const name = varName(token.css) || ''; + const group: ColorToken['group'] = name.startsWith('--brand-') ? 'brand' : name.startsWith('--lib-') ? 'team' : token.group; + return group === token.group ? token : { ...token, group }; + }); + const restricted = this.restricted(); + const chosen = tokenFor(tokens, value); + const groups = GROUPS.filter(group => !restricted || group.id !== 'site') + .map(group => ({ ...group, tokens: tokens.filter(token => token.group === group.id) })) + .filter(group => group.tokens.length > 0 || restricted && group.id === 'brand'); + const held = this.sets.contains(document.activeElement) ? document.activeElement as HTMLElement : null; + this.fillSets(groups, chosen); + if (held && document.activeElement !== held && held.isConnected && !held.closest('[hidden]')) held.focus({ preventScroll: true }); + } + + private fillSets(groups: (typeof GROUPS[number] & { tokens: ColorToken[] })[], chosen: ColorToken | undefined): void { + keyed(this.sets, groups, group => group.id, group => { + const set = element('div', 'fw-cp-set'); + const head = element('div', 'fw-cp-set-head'); + head.id = `fw-cp-set-${group.id}`; + const row = element('div', 'fw-cp-set-row'); + row.setAttribute('role', 'group'); + row.setAttribute('aria-labelledby', head.id); + const empty = element('div', 'fw-cp-set-empty'); + label(empty, 'No brand or team colors yet. Add them in Window > Brand kit.'); + set.append(head, row, empty); + return set; + }, (set, group) => { + label(set.children[0] as HTMLElement, group.title); + const empty = set.children[2] as HTMLElement; + const none = group.tokens.length === 0; + if (empty.hidden === none) empty.hidden = !none; + keyed(set.children[1] as HTMLElement, group.tokens, token => token.css, () => { + const swatch = element('button', 'fw-cp-swatch'); + swatch.type = 'button'; + swatch.dataset.noI18n = ''; + swatch.append(element('span', 'fw-cp-swatch-fill')); + return swatch; + }, (swatch, token) => { + swatch.dataset.css = token.css; + const name = `${token.name} (${token.value})`; + if (swatch.getAttribute('aria-label') !== token.name) swatch.setAttribute('aria-label', token.name); + if (swatch.title !== name) swatch.title = name; + const color = this.resolve(token.value); + const fill = swatch.firstChild as HTMLElement; + const paint = color ? `rgba(${Math.round(color.r)}, ${Math.round(color.g)}, ${Math.round(color.b)}, ${color.a})` : ''; + if (fill.style.backgroundColor !== paint) fill.style.backgroundColor = paint; + swatch.setAttribute('aria-pressed', String(chosen?.css === token.css)); + }); + const swatches = Array.from(set.children[1].children) as HTMLElement[]; + const stop = swatches.find(swatch => swatch.getAttribute('aria-pressed') === 'true') || swatches[0]; + for (const swatch of swatches) if (swatch.tabIndex !== (swatch === stop ? 0 : -1)) swatch.tabIndex = swatch === stop ? 0 : -1; + }); + } + + private roam(event: KeyboardEvent): void { + const swatch = (event.target as Element).closest('.fw-cp-swatch'); + const keys = ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End']; + if (!swatch || !keys.includes(event.key)) return; + const row = Array.from(swatch.parentElement!.children) as HTMLElement[]; + const at = row.indexOf(swatch); + const across = Math.max(1, Math.round(swatch.parentElement!.clientWidth / Math.max(1, swatch.offsetWidth + 4))); + const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -across, ArrowDown: across, Home: -at, End: row.length - 1 - at }[event.key] ?? 0; + const next = row[Math.max(0, Math.min(row.length - 1, at + step))]; + event.preventDefault(); + if (!next || next === swatch) return; + swatch.tabIndex = -1; + next.tabIndex = 0; + next.focus({ preventScroll: true }); + next.scrollIntoView({ block: 'nearest' }); + } + + private place(): void { + const target = this.target; + if (!target) return; + const box = target.anchor.getBoundingClientRect(); + const width = this.root.offsetWidth; + const height = this.root.offsetHeight; + const beside = box.left - GAP - width >= MARGIN; + const below = window.innerHeight - box.bottom - GAP - MARGIN; + const above = box.top - GAP - MARGIN; + let top = beside ? box.top - MARGIN : below >= height || below >= above ? box.bottom + GAP : box.top - GAP - height; + top = Math.max(MARGIN, Math.min(top, window.innerHeight - height - MARGIN)); + const left = beside ? box.left - GAP - width : Math.max(MARGIN, Math.min(box.left, window.innerWidth - width - MARGIN)); + const x = `${Math.round(left)}px`; + const y = `${Math.round(top)}px`; + if (this.root.style.left !== x) this.root.style.left = x; + if (this.root.style.top !== y) this.root.style.top = y; + } + + private focusFirst(): void { + const first = this.active === SOLID + ? (this.restricted() ? this.sets.querySelector('.fw-cp-swatch') || this.clear : this.area.element.querySelector('[role="slider"]')) + : this.focusables().find(node => !this.strip.contains(node)); + (first || this.root).focus({ preventScroll: true }); + } + + private focusables(): HTMLElement[] { + return Array.from(this.root.querySelectorAll('button, input, select, textarea, [tabindex]')) + .filter(node => node !== this.root && node.tabIndex >= 0 && !(node as HTMLButtonElement).disabled && !node.closest('[hidden]')); + } + + private keys(event: KeyboardEvent): void { + if (event.isComposing) return; + if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + const areas = this.active === SOLID ? [this.area] : this.mounted.find(item => item.tab.id === this.active)?.areas || []; + if (!areas.some(area => area.cancel())) this.close(true); + return; + } + if (event.key === 'Tab') { + const list = this.focusables(); + if (!list.length) return; + const at = list.indexOf(document.activeElement as HTMLElement); + const next = event.shiftKey ? (at <= 0 ? list.length - 1 : at - 1) : (at < 0 || at === list.length - 1 ? 0 : at + 1); + event.preventDefault(); + list[next].focus({ preventScroll: true }); + return; + } + const tab = (event.target as Element).closest('[role="tab"]'); + if (tab && (event.key === 'ArrowLeft' || event.key === 'ArrowRight' || event.key === 'Home' || event.key === 'End')) { + const list = Array.from(this.strip.children) as HTMLElement[]; + const at = list.indexOf(tab); + const next = event.key === 'Home' ? 0 : event.key === 'End' ? list.length - 1 : (at + (event.key === 'ArrowRight' ? 1 : -1) + list.length) % list.length; + event.preventDefault(); + if (list[next]?.dataset.key) this.select(list[next].dataset.key!, true); + return; + } + if (event.key === 'Enter' || event.key === ' ') event.stopPropagation(); + } + + private readonly outside = (event: Event): void => { + const node = event.target as Node; + if (this.root.contains(node) || this.target?.anchor.contains(node)) return; + this.close(false); + }; + + private readonly blur = (): void => { + if (this.area.dropping()) return; + this.close(false); + }; + + private readonly leave = (event: FocusEvent): void => { + const next = event.relatedTarget as Node | null; + if (!next) { this.guard(); return; } + if (this.root.contains(next) || this.target?.anchor.contains(next)) return; + this.close(false); + }; + + private readonly reflow = (): void => { + cancelAnimationFrame(this.frame); + this.frame = requestAnimationFrame(() => this.place()); + }; +} diff --git a/frontend/src/features/inspector/controls/color.ts b/frontend/src/features/inspector/controls/color.ts new file mode 100644 index 00000000..50287c0e --- /dev/null +++ b/frontend/src/features/inspector/controls/color.ts @@ -0,0 +1,109 @@ +import { labelAttr } from '../../../i18n'; +import { element } from '../../../ui/dom'; +import { registerControl } from './index'; +import { isGradient, varName, type Rgba } from './color-math'; +import { colorPicker, resolveFor, type PickerTarget } from './color-picker'; +import type { Control, ControlHost, StyleField } from './types'; +import '../../../styles/control-color.css'; + +type Look = 'empty' | 'inherited' | 'color' | 'gradient'; +interface Shown { look: Look; paint: string } + +type Resolve = (value: string) => Rgba | null; + +function paintOf(resolve: Resolve, value: string): string { + const color = resolve(value); + return color ? `rgba(${Math.round(color.r)}, ${Math.round(color.g)}, ${Math.round(color.b)}, ${Math.round(color.a * 1000) / 1000})` : ''; +} + +function gradientPaint(resolve: Resolve, value: string): string { + return value.trim().replace(/var\(\s*(--[a-z0-9_-]+)\s*\)/gi, (_whole, name: string) => paintOf(resolve, `var(${name})`) || 'transparent'); +} + +export function readColorValue(key: string, value: string, inherited: string, resolve: Resolve): Shown | null { + const text = value.trim(); + const lower = text.toLowerCase(); + const fallback = (): Shown => { + const paint = inherited.trim() && !isGradient(inherited) ? paintOf(resolve, inherited) : ''; + return paint ? { look: 'inherited', paint } : { look: 'empty', paint: '' }; + }; + if (!text || ['inherit', 'initial', 'unset', 'revert', 'currentcolor'].includes(lower) || key === 'background' && lower === 'none') return fallback(); + if (varName(text)) { + const paint = paintOf(resolve, text); + return paint ? { look: 'color', paint } : null; + } + if (key === 'background' && isGradient(text)) return { look: 'gradient', paint: gradientPaint(resolve, text) }; + if (/var\(|url\(/i.test(text)) return null; + const paint = paintOf(resolve, text); + return paint ? { look: 'color', paint } : null; +} + +function colorControl(field: StyleField, host: ControlHost): Control { + const swatch = element('button', 'fw-color-swatch'); + swatch.type = 'button'; + swatch.dataset.look = 'empty'; + swatch.setAttribute('aria-haspopup', 'dialog'); + swatch.setAttribute('aria-expanded', 'false'); + labelAttr(swatch, 'aria-label', 'Choose {0}', [{ t: field.label }]); + labelAttr(swatch, 'title', 'Choose {0}', [{ t: field.label }]); + const resolve: Resolve = value => resolveFor(host, value); + const chip = element('span', 'fw-color-chip'); + swatch.append(chip); + field.lead.append(swatch); + + const paint = (shown: Shown): void => { + if (swatch.dataset.look !== shown.look) swatch.dataset.look = shown.look; + if (shown.look === 'gradient') { + if (chip.style.backgroundColor) chip.style.backgroundColor = ''; + if (chip.style.backgroundImage !== shown.paint) chip.style.backgroundImage = shown.paint; + } else { + if (chip.style.backgroundImage) chip.style.backgroundImage = ''; + if (chip.style.backgroundColor !== shown.paint) chip.style.backgroundColor = shown.paint; + } + }; + + const target: PickerTarget = { + key: field.key, + label: field.label, + anchor: swatch, + field, + value: () => field.value(), + inherited: () => field.inherited(), + show(value) { + field.show(value); + const shown = readColorValue(field.key, value, field.inherited(), resolve); + if (shown) paint(shown); + }, + restore() { + field.restore(); + const shown = readColorValue(field.key, field.value(), field.inherited(), resolve); + if (shown) paint(shown); + }, + commit: value => field.commit(value) + }; + const picker = colorPicker(host); + swatch.addEventListener('click', () => picker.toggle(target)); + + return { + sync(value: string, inherited: string): boolean { + const shown = readColorValue(field.key, value, inherited, resolve); + if (!shown) { + if (picker.isOpen(target)) picker.close(false); + return false; + } + paint(shown); + picker.refresh(target, value); + return true; + }, + setRaw(raw: boolean) { + if (raw && picker.isOpen(target)) picker.close(false); + }, + cancel() { + picker.cancel(target); + } + }; +} + +export function register(): void { + registerControl(['color', 'background'], colorControl); +} diff --git a/frontend/src/features/inspector/controls/index.ts b/frontend/src/features/inspector/controls/index.ts index cbe375d4..868b8571 100644 --- a/frontend/src/features/inspector/controls/index.ts +++ b/frontend/src/features/inspector/controls/index.ts @@ -5,6 +5,7 @@ import { icon } from '../../../ui/icons'; import { readBrand } from '../../brand-kit'; import type { ColorToken, Control, ControlFactory, ControlHost, ControlKit, StyleField } from './types'; import { register as registerSlider } from './slider'; +import { register as registerColor } from './color'; import '../../../styles/controls.css'; const factories = new Map(); @@ -70,6 +71,7 @@ export function installControls(options: ControlOptions): InstalledKit { if (!installed) { installed = true; registerSlider(); + registerColor(); } const stored = load(); stored.fields = stored.fields && typeof stored.fields === 'object' ? stored.fields : {}; diff --git a/frontend/src/features/inspector/controls/picker-api.ts b/frontend/src/features/inspector/controls/picker-api.ts new file mode 100644 index 00000000..755273f5 --- /dev/null +++ b/frontend/src/features/inspector/controls/picker-api.ts @@ -0,0 +1,29 @@ +import type { ColorToken, StyleField } from './types'; +import type { Rgba } from './color-math'; + +export interface ColorArea { + readonly element: HTMLElement; + set(color: string): void; + get(): string; + cancel(): boolean; +} +export interface ColorAreaOptions { + label: string; + input(color: string): void; + commit(color: string): void; +} +export interface PickerApi { + field(): StyleField; + colorArea(options: ColorAreaOptions): ColorArea; + colors(): ColorToken[]; + resolve(color: string): Rgba | null; + show(value: string): void; + commit(value: string): Promise; +} +export interface PickerTab { + readonly id: string; + readonly label: string; + accepts(key: string): boolean; + mount(panel: HTMLElement, api: PickerApi): { open(value: string): boolean; close(): void }; +} +export { registerPickerTab } from './color-picker'; diff --git a/frontend/src/styles/control-color.css b/frontend/src/styles/control-color.css new file mode 100644 index 00000000..ea40bc22 --- /dev/null +++ b/frontend/src/styles/control-color.css @@ -0,0 +1,59 @@ +.fw-color-swatch, .fw-cp-swatch, .fw-ca-preview { --checker: repeating-conic-gradient(var(--cv-checker-b) 0 25%, var(--cv-checker-a) 0 50%) 0 0 / 8px 8px; } +.fw-color-swatch { position: relative; flex: none; width: var(--ctl-sm); height: var(--ctl-sm); min-height: 0; padding: 0; border: 1px solid var(--line-3); border-radius: var(--radius-sm); background: var(--checker); overflow: hidden; } +.fw-color-swatch:hover { border-color: var(--text-muted); background: var(--checker); } +.fw-color-swatch[aria-expanded='true'] { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fw-color-chip { position: absolute; inset: 0; border-radius: inherit; } +.fw-color-swatch[data-look='empty'], .fw-color-swatch[data-look='inherited'] { border-style: dashed; background: var(--surface-field); } +.fw-color-swatch[data-look='inherited'] .fw-color-chip { inset: 5px; border-radius: var(--radius-xs); opacity: .7; } +.fw-color-swatch[data-look='empty'] .fw-color-chip { inset: 0; background: linear-gradient(to top right, transparent calc(50% - .5px), var(--text-muted) calc(50% - .5px), var(--text-muted) calc(50% + .5px), transparent calc(50% + .5px)); } + +.fw-cp { position: fixed; top: 0; left: 0; z-index: var(--z-popover); box-sizing: border-box; display: flex; flex-direction: column; gap: var(--space-2); width: 248px; max-height: calc(100vh - var(--space-4)); overflow-y: auto; scrollbar-width: none; padding: var(--space-2); pointer-events: auto; border: 1px solid var(--line-2); border-radius: var(--radius-xl); 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-cp::-webkit-scrollbar { display: none; } +.fw-cp[hidden], .fw-cp [hidden] { display: none; } +.fw-cp:focus { outline: none; } +.fw-cp-tabs { display: flex; flex: none; gap: var(--space-1); padding: 2px; border-radius: var(--radius); background: var(--surface-field); } +.fw-cp-tab { flex: 1 1 0; min-height: 0; height: var(--ctl-sm); padding: 0 var(--space-2); border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text-secondary); font-size: var(--fs-12); } +.fw-cp-tab:hover { background: var(--bg-hover); color: var(--text-primary); } +.fw-cp-tab[aria-selected='true'] { background: var(--surface-raised); color: var(--text-primary); } +.fw-cp-panel { display: flex; flex-direction: column; gap: var(--space-2); flex: none; min-width: 0; } +.fw-cp-panel[data-tab='solid'] { flex: 0 1 auto; min-height: 0; } +.fw-cp-panel[data-tab='solid'] > * { flex: none; } +.fw-cp-note { margin: 0; color: var(--text-secondary); font-size: var(--fs-12); line-height: 1.4; } + +.fw-ca { display: flex; flex-direction: column; gap: var(--space-2); } +.fw-ca [role='slider'] { position: relative; touch-action: none; cursor: crosshair; } +.fw-ca [role='slider']:focus { outline: none; } +.fw-ca [role='slider']:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 2px; } +.fw-ca-square { --x: 0; --y: 0; height: 140px; border-radius: var(--radius); } +.fw-ca-thumb { position: absolute; box-sizing: border-box; width: 14px; height: 14px; border: 2px solid var(--cv-handle-fill); border-radius: 50%; box-shadow: 0 0 0 1px var(--cv-doc-edge), var(--shadow-sm); pointer-events: none; } +.fw-ca-square > .fw-ca-thumb { left: calc(var(--x) * 100%); top: calc(var(--y) * 100%); background: var(--thumb); transform: translate(-50%, -50%); } +.fw-ca-bar { --x: 0; height: 12px; border-radius: var(--radius-pill); cursor: pointer; } +.fw-ca [role='slider'].fw-ca-bar { cursor: pointer; } +.fw-ca-bar > .fw-ca-thumb { top: 50%; left: calc(6px + var(--x) * (100% - 12px)); transform: translate(-50%, -50%); } +.fw-ca-alpha { background: repeating-conic-gradient(var(--cv-checker-b) 0 25%, var(--cv-checker-a) 0 50%) 0 0 / 8px 8px; } +.fw-ca-fill { position: absolute; inset: 0; border-radius: inherit; } +.fw-ca-row { display: flex; align-items: center; gap: var(--space-1); } +.fw-ca-preview { position: relative; flex: none; width: var(--ctl-md); height: var(--ctl-md); border: 1px solid var(--line-3); border-radius: var(--radius-sm); background: var(--checker); overflow: hidden; } +.fw-ca-preview-fill { position: absolute; inset: 0; } +.fw-ca-entry { flex: 1 1 auto; width: auto; height: var(--ctl-md); min-height: 0; padding: 0 var(--space-2); font-family: var(--font-mono); font-size: var(--fs-12); background: var(--surface-field); border-color: var(--line-2); } +.fw-ca-entry[aria-invalid='true'] { border-color: var(--danger-color); } +.fw-ca-dropper { flex: none; width: var(--ctl-md); height: var(--ctl-md); min-height: 0; padding: 0; border-color: var(--line-2); background: var(--surface-field); color: var(--text-secondary); } +.fw-ca-dropper:hover { color: var(--text-primary); } +.fw-ca-dropper svg { width: 16px; height: 16px; } +.fw-ca[data-dropping='true'] .fw-ca-dropper { color: var(--accent-color); } + +.fw-cp-panel[data-tab='solid'] > .fw-cp-sets { display: flex; flex-direction: column; gap: var(--space-2); flex: 0 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: none; } +.fw-cp-sets::-webkit-scrollbar { display: none; } +.fw-cp-panel[data-tab='solid'] > .fw-cp-sets:empty { display: none; } +.fw-cp-set { display: flex; flex-direction: column; gap: var(--space-1); } +.fw-cp-set-head { color: var(--text-muted); font-size: var(--fs-10); letter-spacing: 0.08em; text-transform: uppercase; } +.fw-cp-set-row { display: flex; flex-wrap: wrap; gap: var(--space-1); } +.fw-cp-set-row:empty { display: none; } +.fw-cp-set-empty { color: var(--text-secondary); font-size: var(--fs-12); line-height: 1.4; } +.fw-cp-swatch { position: relative; width: 20px; height: 20px; min-height: 0; padding: 0; border: 1px solid var(--line-3); border-radius: var(--radius-sm); background: var(--checker); overflow: hidden; } +.fw-cp-swatch:hover { background: var(--checker); border-color: var(--text-muted); } +.fw-cp-swatch[aria-pressed='true'] { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fw-cp-swatch-fill { position: absolute; inset: 0; } +.fw-cp-foot { display: flex; flex: none; justify-content: flex-end; padding-top: var(--space-1); border-top: 1px solid var(--line-1); } +.fw-cp-clear { min-height: 0; height: var(--ctl-sm); padding: 0 var(--space-2); border-color: var(--line-2); background: transparent; color: var(--text-secondary); font-size: var(--fs-12); } +.fw-cp-clear:hover { color: var(--text-primary); } From 4a98d337bd331c6d5757ad2510dba4bf1e9dd6a0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 00:37:35 -0500 Subject: [PATCH 22/31] feat(inspector): Grid columns and Grid rows show a button with a drawing of the current layout that opens a chooser of drawn, named layouts; choosing one writes plain CSS tracks, a typed value the chooser knows marks its entry, and on an element that is not a grid Make this element a grid sets Display and the tracks in one undo step --- .../inspector/controls/grid-tracks.ts | 140 ++++++ .../src/features/inspector/controls/grid.ts | 450 ++++++++++++++++++ .../src/features/inspector/controls/index.ts | 2 + frontend/src/styles/control-grid.css | 48 ++ 4 files changed, 640 insertions(+) create mode 100644 frontend/src/features/inspector/controls/grid-tracks.ts create mode 100644 frontend/src/features/inspector/controls/grid.ts create mode 100644 frontend/src/styles/control-grid.css diff --git a/frontend/src/features/inspector/controls/grid-tracks.ts b/frontend/src/features/inspector/controls/grid-tracks.ts new file mode 100644 index 00000000..50dc0d2c --- /dev/null +++ b/frontend/src/features/inspector/controls/grid-tracks.ts @@ -0,0 +1,140 @@ +export const NOMINAL_WIDTH = 1000; +const CONTENT = 100; +const MAX_REPEAT = 100; + +type Size = { fixed: number } | { fr: number; min?: number } | { content: true }; +type Item = { size: Size } | { auto: 'auto-fit' | 'auto-fill'; sizes: Size[] }; + +function split(text: string, separator: RegExp): string[] | null { + const parts: string[] = []; + let depth = 0; + let start = 0; + for (let i = 0; i < text.length; i++) { + const char = text[i]; + if (char === '(') depth++; + else if (char === ')') { depth--; if (depth < 0) return null; } + else if (depth === 0 && separator.test(char)) { + if (i > start) parts.push(text.slice(start, i)); + start = i + 1; + } + } + if (depth !== 0) return null; + if (text.length > start) parts.push(text.slice(start)); + return parts.map(part => part.trim()).filter(Boolean); +} + +function call(text: string, name: string): string[] | null { + const match = new RegExp(`^${name}\\((.*)\\)$`, 'i').exec(text); + return match ? split(match[1], /,/) : null; +} + +function plain(text: string): Size | null { + const lower = text.toLowerCase(); + if (lower === 'auto' || lower === 'min-content' || lower === 'max-content') return { content: true }; + if (lower === '0') return { fixed: 0 }; + const match = /^(\d+(?:\.\d+)?|\.\d+)(fr|px|%|rem|em)$/.exec(lower); + if (!match) return null; + const amount = Number(match[1]); + if (match[2] === 'fr') return { fr: amount }; + if (match[2] === 'px') return { fixed: amount }; + if (match[2] === '%') return { fixed: amount * NOMINAL_WIDTH / 100 }; + return { fixed: amount * 16 }; +} + +function size(text: string): Size | null { + const args = call(text, 'minmax'); + if (!args) return plain(text); + if (args.length !== 2) return null; + const low = plain(args[0]); + const high = plain(args[1]); + if (!low || !high || 'fr' in low) return null; + if ('fr' in high) return 'fixed' in low && low.fixed > 0 ? { fr: high.fr, min: low.fixed } : high; + if ('fixed' in high) return high; + return low; +} + +function items(text: string, nested: boolean): Item[] | null { + const words = split(text, /\s/); + if (!words) return null; + const out: Item[] = []; + for (const word of words) { + const args = call(word, 'repeat'); + if (!args) { + const one = size(word); + if (!one) return null; + out.push({ size: one }); + continue; + } + if (nested || args.length !== 2) return null; + const inner = items(args[1], true); + if (!inner || !inner.length) return null; + const sizes = inner.map(item => 'size' in item ? item.size : null); + if (sizes.some(item => !item)) return null; + const count = args[0].toLowerCase(); + if (count === 'auto-fit' || count === 'auto-fill') { + if (sizes.some(item => !item || !('fixed' in item && item.fixed > 0) && !('fr' in item && item.min))) return null; + out.push({ auto: count, sizes: sizes as Size[] }); + continue; + } + if (!/^\d+$/.test(count)) return null; + const times = Number(count); + if (times < 1 || times > MAX_REPEAT) return null; + for (let i = 0; i < times; i++) for (const item of sizes) out.push({ size: item! }); + } + return out; +} + +function autoCount(sizes: Size[], room: number): number { + const each = sizes.reduce((sum, item) => sum + ('fixed' in item ? item.fixed : 'fr' in item ? item.min || 0 : 0), 0); + return each > 0 ? Math.max(1, Math.min(MAX_REPEAT, Math.floor(room / each))) : 1; +} + +export function parseTracks(value: string): number[] | null { + const text = value.trim(); + if (!text) return []; + const list = items(text, false); + if (!list || !list.length) return null; + const autos = list.filter(item => 'auto' in item); + if (autos.length > 1) return null; + const fixedOf = (item: Size): number => 'fixed' in item ? item.fixed : 'content' in item ? CONTENT : 0; + const outside = list.reduce((sum, item) => sum + ('size' in item ? fixedOf(item.size) : 0), 0); + const sizes: Size[] = []; + for (const item of list) { + if ('size' in item) { sizes.push(item.size); continue; } + const times = autoCount(item.sizes, Math.max(NOMINAL_WIDTH - outside, 0)); + for (let i = 0; i < times; i++) sizes.push(...item.sizes); + } + const fixed = sizes.reduce((sum, item) => sum + fixedOf(item), 0); + const fr = sizes.reduce((sum, item) => sum + ('fr' in item ? item.fr : 0), 0); + const free = fr > 0 ? Math.max(NOMINAL_WIDTH - fixed, NOMINAL_WIDTH * 0.3) : 0; + const widths = sizes.map(item => 'fr' in item ? free * item.fr / fr : fixedOf(item)); + const total = Math.max(NOMINAL_WIDTH, widths.reduce((sum, width) => sum + width, 0)); + return widths.map(width => width / total); +} + +function canonical(value: string): string { + return value.trim().toLowerCase().replace(/\s+/g, ' ').replace(/\s*([(),])\s*/g, '$1'); +} + +function expand(value: string): string | null { + const text = canonical(value); + if (!text) return ''; + const words = split(text, /\s/); + if (!words) return null; + const out: string[] = []; + for (const word of words) { + const match = /^repeat\((\d+),(.*)\)$/.exec(word); + if (!match) { out.push(word); continue; } + const times = Number(match[1]); + const inner = split(match[2], /\s/); + if (!inner || times < 1 || times > MAX_REPEAT) return null; + for (let i = 0; i < times; i++) out.push(...inner); + } + return out.join(' '); +} + +export function sameTracks(a: string, b: string): boolean { + if (canonical(a) === canonical(b)) return true; + const left = expand(a); + return left !== null && left === expand(b); +} diff --git a/frontend/src/features/inspector/controls/grid.ts b/frontend/src/features/inspector/controls/grid.ts new file mode 100644 index 00000000..cd05b441 --- /dev/null +++ b/frontend/src/features/inspector/controls/grid.ts @@ -0,0 +1,450 @@ +import { label, labelAttr } from '../../../i18n'; +import { element } from '../../../ui/dom'; +import { registerControl } from './index'; +import { parseTracks, sameTracks } from './grid-tracks'; +import type { Control, ControlHost, StyleField } from './types'; +import '../../../styles/control-grid.css'; + +type Axis = 'columns' | 'rows'; +type Words = [string, string[]?]; +interface Choice { css: string; name: Words } +interface Group { title: string; choices: Choice[]; stepper?: boolean; rows?: boolean } +interface GridHost extends ControlHost { commitStyles?(styles: Record): Promise } + +const SVG = 'http://www.w3.org/2000/svg'; +const MARGIN = 8; +const GAP = 4; +const MAX_EQUAL = 12; + +function equal(axis: Axis, count: number): Choice { + const one = axis === 'columns' ? 'One column' : 'One row'; + const many = axis === 'columns' ? '{0} columns' : '{0} rows'; + return { css: `repeat(${count}, 1fr)`, name: count === 1 ? [one] : [many, [String(count)]] }; +} + +function groupsFor(axis: Axis): Group[] { + const equals = [1, 2, 3, 4, 5, 6].map(count => equal(axis, count)); + if (axis === 'rows') return [ + { title: 'Equal rows', choices: equals, stepper: true }, + { title: 'Header and footer', choices: [{ css: 'auto 1fr auto', name: ['Header, content, footer'] }, { css: 'auto 1fr', name: ['Header and content'] }] } + ]; + return [ + { title: 'Equal columns', choices: equals, stepper: true }, + { title: 'Two columns', choices: [ + { css: '1fr 2fr', name: ['Narrow left, wide right'] }, + { css: '2fr 1fr', name: ['Wide left, narrow right'] }, + { css: '1fr 3fr', name: ['Slim left, wide right'] }, + { css: '3fr 1fr', name: ['Wide left, slim right'] }, + { css: '240px 1fr', name: ['Fixed sidebar on the left'] }, + { css: '1fr 240px', name: ['Fixed sidebar on the right'] } + ] }, + { title: 'Three columns', choices: [{ css: '1fr 2fr 1fr', name: ['Wide middle'] }] }, + { title: 'As many as fit', rows: true, choices: [160, 200, 240, 320].map(min => ({ css: `repeat(auto-fit, minmax(${min}px, 1fr))`, name: ['At least {0} px each', [String(min)]] as Words })) } + ]; +} + +interface Drawing { svg: SVGSVGElement; paint(sizes: number[] | null): void } + +function drawing(axis: Axis, width: number, height: number): Drawing { + const svg = document.createElementNS(SVG, 'svg'); + svg.setAttribute('class', 'fw-grid-draw'); + svg.setAttribute('viewBox', `0 0 ${width} ${height}`); + svg.setAttribute('width', String(width)); + svg.setAttribute('height', String(height)); + svg.setAttribute('aria-hidden', 'true'); + svg.dataset.axis = axis; + const frame = document.createElementNS(SVG, 'rect'); + frame.setAttribute('class', 'fw-grid-draw-frame'); + frame.setAttribute('x', '0.5'); + frame.setAttribute('y', '0.5'); + frame.setAttribute('width', String(width - 1)); + frame.setAttribute('height', String(height - 1)); + frame.setAttribute('rx', '1.5'); + svg.append(frame); + const bars: SVGRectElement[] = []; + const set = (node: Element, name: string, next: string): void => { if (node.getAttribute(name) !== next) node.setAttribute(name, next); }; + return { + svg, + paint(sizes) { + const list = sizes && sizes.length ? sizes : []; + const state = sizes === null ? 'none' : list.length ? 'tracks' : 'empty'; + if (svg.dataset.state !== state) svg.dataset.state = state; + while (bars.length < list.length) { + const bar = document.createElementNS(SVG, 'rect'); + bar.setAttribute('class', 'fw-grid-draw-bar'); + bar.setAttribute('rx', '1'); + svg.append(bar); + bars.push(bar); + } + const long = axis === 'columns' ? width : height; + const inset = 2; + const gap = list.length > 12 ? 0.5 : 1.5; + const room = long - inset * 2 - gap * Math.max(0, list.length - 1); + let at = inset; + bars.forEach((bar, index) => { + if (index >= list.length) { set(bar, 'display', 'none'); return; } + set(bar, 'display', 'inline'); + const size = Math.max(0.75, list[index] * room); + const along = at.toFixed(2); + const extent = size.toFixed(2); + const across = String(inset); + const thick = String((axis === 'columns' ? height : width) - inset * 2); + set(bar, 'x', axis === 'columns' ? along : across); + set(bar, 'y', axis === 'columns' ? across : along); + set(bar, 'width', axis === 'columns' ? extent : thick); + set(bar, 'height', axis === 'columns' ? thick : extent); + at += size + gap; + }); + } + }; +} + +function displayIsGrid(field: StyleField): boolean | null { + const scope = field.wrapper.closest('.inspector') || document; + const group = scope.querySelector('.fw-seg[data-style="display"]'); + if (!group) return null; + const own = group.querySelector('.fw-seg-btn.is-on') || group.querySelector('.fw-seg-btn.is-inherited'); + return /grid/.test(own?.dataset.value || ''); +} + +function gridControl(field: StyleField, host: GridHost): Control { + const axis: Axis = field.key === 'grid-template-rows' ? 'rows' : 'columns'; + const opener = element('button', 'fw-grid-open'); + opener.type = 'button'; + opener.setAttribute('aria-haspopup', 'dialog'); + opener.setAttribute('aria-expanded', 'false'); + labelAttr(opener, 'aria-label', 'Choose {0}', [{ t: field.label }]); + labelAttr(opener, 'title', 'Choose {0}', [{ t: field.label }]); + const face = drawing(axis, 22, 16); + opener.append(face.svg); + field.lead.append(opener); + + const panel = element('div', 'fw-gridpick'); + panel.hidden = true; + panel.setAttribute('role', 'dialog'); + labelAttr(panel, 'aria-label', 'Choose {0}', [{ t: field.label }]); + panel.dataset.axis = axis; + panel.dataset.ownKeys = ''; + + const hint = element('div', 'fw-gridpick-hint'); + hint.hidden = true; + const hintText = element('p', 'fw-gridpick-hint-text'); + label(hintText, "{0} only takes effect when this element's Display is Grid.", [{ t: field.label }]); + const make = element('button', 'fw-gridpick-make'); + make.type = 'button'; + label(make, 'Make this element a grid'); + const makeCss = element('code', 'fw-gridpick-make-css'); + hint.append(hintText, make, makeCss); + if (!host.commitStyles) { make.hidden = true; makeCss.hidden = true; } + + const entries: HTMLButtonElement[] = []; + const body = element('div', 'fw-gridpick-body'); + let stepInput: HTMLInputElement | null = null; + let stepEntry: HTMLButtonElement | null = null; + let stepDraw: Drawing | null = null; + let stepCode: HTMLElement | null = null; + let counter = 0; + const panelId = `fw-gridpick-${field.key}`; + + function entry(css: string, name: Words, size: [number, number]): { button: HTMLButtonElement; draw: Drawing; code: HTMLElement } { + const button = element('button', 'fw-gridpick-entry'); + button.type = 'button'; + button.tabIndex = -1; + button.dataset.css = css; + button.setAttribute('aria-pressed', 'false'); + const draw = drawing(axis, size[0], size[1]); + draw.paint(parseTracks(css)); + const words = element('span', 'fw-gridpick-name'); + label(words, name[0], name[1]); + labelAttr(button, 'title', name[0], name[1]); + const code = element('code', 'fw-gridpick-css', css); + button.append(draw.svg, words, code); + entries.push(button); + return { button, draw, code }; + } + + for (const group of groupsFor(axis)) { + const section = element('div', 'fw-gridpick-group'); + section.setAttribute('role', 'group'); + const head = element('div', 'fw-gridpick-head'); + head.id = `${panelId}-head-${++counter}`; + label(head, group.title); + section.setAttribute('aria-labelledby', head.id); + const tiles = element('div', group.rows ? 'fw-gridpick-tiles is-rows' : 'fw-gridpick-tiles'); + for (const choice of group.choices) { + const made = entry(choice.css, choice.name, group.rows ? [40, 20] : [44, 22]); + if (group.rows) made.button.classList.add('fw-gridpick-entry-row'); + tiles.append(made.button); + } + section.append(head, tiles); + if (group.stepper) { + const row = element('div', 'fw-gridpick-step'); + const stepLabel = element('label', 'fw-gridpick-step-label'); + const words = element('span'); + label(words, axis === 'columns' ? 'Any number of columns' : 'Any number of rows'); + const input = element('input', 'fw-gridpick-step-input'); + input.type = 'number'; + input.min = '1'; + input.max = String(MAX_EQUAL); + input.step = '1'; + input.value = '8'; + stepLabel.append(words, input); + const made = entry('repeat(8, 1fr)', axis === 'columns' ? ['{0} columns', ['8']] : ['{0} rows', ['8']], [30, 18]); + made.button.classList.add('fw-gridpick-entry-step'); + row.append(stepLabel, made.button); + section.append(row); + stepInput = input; + stepEntry = made.button; + stepDraw = made.draw; + stepCode = made.code; + const nameNode = made.button.querySelector('.fw-gridpick-name')!; + input.addEventListener('input', () => { + const count = Math.round(Number(input.value)); + if (!Number.isFinite(count) || count < 1 || count > MAX_EQUAL) return; + const css = `repeat(${count}, 1fr)`; + made.button.dataset.css = css; + if (stepCode!.textContent !== css) stepCode!.textContent = css; + const words = axis === 'columns' ? (count === 1 ? 'One column' : '{0} columns') : (count === 1 ? 'One row' : '{0} rows'); + label(nameNode, words, [String(count)]); + labelAttr(made.button, 'title', words, [String(count)]); + stepDraw!.paint(parseTracks(css)); + mark(); + }); + input.addEventListener('keydown', event => { + if (event.key !== 'Enter') return; + event.preventDefault(); + input.dispatchEvent(new Event('input')); + choose(made.button); + }); + } + body.append(section); + } + panel.append(hint, body); + host.overlay.append(panel); + + let current = ''; + let picked: string | null = null; + let notGrid = false; + let active: HTMLButtonElement | null = null; + + function mark(): void { + const pending = notGrid && !!host.commitStyles && picked !== null; + const target = pending ? picked! : current; + const matches = new Set(entries.filter(button => !!target.trim() && sameTracks(button.dataset.css || '', target))); + if (stepEntry && matches.size > 1) matches.delete(stepEntry); + for (const button of entries) { + const on = matches.has(button); + const pressed = String(on); + if (button.getAttribute('aria-pressed') !== pressed) button.setAttribute('aria-pressed', pressed); + const look = on && pending; + if (button.classList.contains('is-picked') !== look) button.classList.toggle('is-picked', look); + } + if (!makeCss.hidden) { + const columns = (picked ?? current).trim(); + const css = `display: grid;\n${columns ? `${field.key}: ${columns};` : ''}`; + if (makeCss.textContent !== css) makeCss.textContent = css; + if (makeCss.title !== css) makeCss.title = css; + } + } + + function setActive(button: HTMLButtonElement | null, focus: boolean): void { + if (active && active !== button) active.tabIndex = -1; + active = button; + if (!button) return; + button.tabIndex = 0; + if (focus) button.focus({ preventScroll: false }); + } + + function refreshHint(): void { + const grid = displayIsGrid(field); + notGrid = grid === false; + if (hint.hidden !== !notGrid) hint.hidden = !notGrid; + mark(); + } + + function place(): void { + const rect = opener.getBoundingClientRect(); + panel.style.left = '0px'; + panel.style.top = '0px'; + panel.style.maxHeight = ''; + const width = panel.offsetWidth; + const height = panel.offsetHeight; + const beside = rect.left - GAP - width >= MARGIN; + const below = window.innerHeight - rect.bottom - GAP - MARGIN; + const above = rect.top - GAP - MARGIN; + const under = below >= height || below >= above; + const room = beside ? window.innerHeight - MARGIN * 2 : Math.max(160, under ? below : above); + if (height > room) panel.style.maxHeight = `${room}px`; + const shown = Math.min(height, room); + let top = beside ? rect.top - MARGIN : under ? rect.bottom + GAP : rect.top - GAP - shown; + top = Math.max(MARGIN, Math.min(top, window.innerHeight - shown - MARGIN)); + const left = beside ? rect.left - GAP - width : Math.max(MARGIN, Math.min(rect.left, window.innerWidth - width - MARGIN)); + panel.style.left = `${Math.round(left)}px`; + panel.style.top = `${Math.round(top)}px`; + } + + const outside = (event: Event): void => { + const target = event.target as Node; + if (panel.contains(target) || opener.contains(target)) return; + close(false); + }; + const leave = (event: FocusEvent): void => { + const next = event.relatedTarget as Node | null; + if (next && (panel.contains(next) || opener.contains(next))) return; + close(false, false); + }; + const resize = (): void => close(false); + const scrolled = (event: Event): void => { if (!panel.contains(event.target as Node)) place(); }; + + function open(): void { + if (!panel.hidden) return; + picked = null; + if (stepInput) { + const sizes = parseTracks(current); + const even = sizes && sizes.length >= 1 && sizes.length <= MAX_EQUAL && /^repeat\(\s*\d+\s*,\s*1fr\s*\)$|^(1fr\s*)+$/i.test(current.trim()); + const next = even ? String(sizes!.length) : '8'; + if (stepInput.value !== next) { stepInput.value = next; stepInput.dispatchEvent(new Event('input')); } + } + refreshHint(); + panel.hidden = false; + opener.setAttribute('aria-expanded', 'true'); + place(); + const chosen = entries.find(button => button.getAttribute('aria-pressed') === 'true' && button !== stepEntry) || entries.find(button => button.getAttribute('aria-pressed') === 'true') || entries[0]; + setActive(chosen, true); + document.addEventListener('pointerdown', outside, true); + window.addEventListener('resize', resize); + document.addEventListener('scroll', scrolled, true); + panel.addEventListener('focusout', leave); + } + + function close(restore: boolean, fallback = true): void { + if (panel.hidden) return; + const hadFocus = fallback && panel.contains(document.activeElement); + panel.hidden = true; + opener.setAttribute('aria-expanded', 'false'); + document.removeEventListener('pointerdown', outside, true); + window.removeEventListener('resize', resize); + document.removeEventListener('scroll', scrolled, true); + panel.removeEventListener('focusout', leave); + picked = null; + if ((restore || hadFocus && document.activeElement === document.body) && opener.isConnected) { + opener.focus({ preventScroll: true }); + if (document.activeElement !== opener) field.input.focus({ preventScroll: true }); + } + } + + function choose(button: HTMLButtonElement): void { + const css = button.dataset.css || ''; + if (!css) return; + if (notGrid && host.commitStyles) { + picked = css; + setActive(button, false); + mark(); + return; + } + close(true); + void field.commit(css).catch(() => undefined); + } + + function makeGrid(): void { + const commitStyles = host.commitStyles; + if (!commitStyles) return; + const columns = (picked ?? current).trim(); + const styles: Record = { display: 'grid' }; + if (columns && columns !== field.value().trim()) styles[field.key] = columns; + close(true); + commitStyles(styles).catch(error => host.status(error instanceof Error ? error.message : String(error), true)); + } + + function nearest(from: HTMLButtonElement, key: string): HTMLButtonElement | null { + const box = from.getBoundingClientRect(); + const cx = box.left + box.width / 2; + const cy = box.top + box.height / 2; + let best: HTMLButtonElement | null = null; + let score = Infinity; + for (const button of entries) { + if (button === from) continue; + const other = button.getBoundingClientRect(); + const ox = other.left + other.width / 2; + const oy = other.top + other.height / 2; + const dx = ox - cx; + const dy = oy - cy; + let main: number; + let side: number; + if (key === 'ArrowRight') { if (dx <= 1 || Math.abs(dy) > box.height / 2) continue; main = dx; side = 0; } + else if (key === 'ArrowLeft') { if (dx >= -1 || Math.abs(dy) > box.height / 2) continue; main = -dx; side = 0; } + else if (key === 'ArrowDown') { if (dy <= 1) continue; main = dy; side = Math.abs(dx); } + else { if (dy >= -1) continue; main = -dy; side = Math.abs(dx); } + const total = main * 4 + side; + if (total < score) { score = total; best = button; } + } + if (best) return best; + const at = entries.indexOf(from); + if (key === 'ArrowRight' || key === 'ArrowDown') return entries[at + 1] || null; + return entries[at - 1] || null; + } + + opener.addEventListener('click', () => { if (panel.hidden) open(); else close(true); }); + make.addEventListener('click', makeGrid); + panel.addEventListener('mousedown', event => { if (!(event.target as Element).closest('input')) event.preventDefault(); }); + panel.addEventListener('click', event => { + const button = (event.target as Element).closest('.fw-gridpick-entry'); + if (button && panel.contains(button)) choose(button); + }); + panel.addEventListener('keydown', event => { + if (event.isComposing) return; + if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(true); return; } + const from = (event.target as Element).closest('.fw-gridpick-entry'); + if (event.key === 'Tab') { + const stops = [make, active, stepInput].filter((node): node is HTMLButtonElement | HTMLInputElement => !!node && !node.hidden && !node.closest('[hidden]')); + if (!stops.length) return; + const at = stops.indexOf(document.activeElement as HTMLButtonElement); + const next = stops[(at + (event.shiftKey ? -1 : 1) + stops.length) % stops.length]; + event.preventDefault(); + next.focus({ preventScroll: false }); + return; + } + if (!from) return; + if (['ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp'].includes(event.key)) { + event.preventDefault(); + const next = nearest(from, event.key); + if (next) setActive(next, true); + } else if (event.key === 'Home' || event.key === 'End') { + event.preventDefault(); + setActive(event.key === 'Home' ? entries[0] : entries[entries.length - 1], true); + } + }); + + return { + sync(value: string, inherited: string): boolean { + const sizes = parseTracks(value); + if (sizes === null) { + close(false); + return false; + } + current = value; + const shownSizes = sizes.length ? sizes : parseTracks(inherited) || []; + face.paint(shownSizes); + const look = sizes.length ? 'own' : shownSizes.length ? 'inherited' : 'empty'; + if (opener.dataset.look !== look) opener.dataset.look = look; + if (!panel.hidden) queueMicrotask(refreshHint); + else mark(); + return true; + }, + cancel() { + picked = null; + if (!panel.hidden) close(panel.contains(document.activeElement)); + else mark(); + }, + setRaw(raw: boolean) { + if (!raw || panel.hidden) return; + const had = panel.contains(document.activeElement); + close(false, false); + if (had) field.input.focus({ preventScroll: true }); + } + }; +} + +export function register(): void { + registerControl(['grid-template-columns', 'grid-template-rows'], gridControl); +} diff --git a/frontend/src/features/inspector/controls/index.ts b/frontend/src/features/inspector/controls/index.ts index 868b8571..6d6a55c5 100644 --- a/frontend/src/features/inspector/controls/index.ts +++ b/frontend/src/features/inspector/controls/index.ts @@ -6,6 +6,7 @@ import { readBrand } from '../../brand-kit'; import type { ColorToken, Control, ControlFactory, ControlHost, ControlKit, StyleField } from './types'; import { register as registerSlider } from './slider'; import { register as registerColor } from './color'; +import { register as registerGrid } from './grid'; import '../../../styles/controls.css'; const factories = new Map(); @@ -72,6 +73,7 @@ export function installControls(options: ControlOptions): InstalledKit { installed = true; registerSlider(); registerColor(); + registerGrid(); } const stored = load(); stored.fields = stored.fields && typeof stored.fields === 'object' ? stored.fields : {}; diff --git a/frontend/src/styles/control-grid.css b/frontend/src/styles/control-grid.css new file mode 100644 index 00000000..b4001cc8 --- /dev/null +++ b/frontend/src/styles/control-grid.css @@ -0,0 +1,48 @@ +.fw-grid-open { display: inline-flex; flex: none; align-items: center; justify-content: center; width: calc(var(--ctl-sm) + var(--space-2)); height: var(--ctl-sm); min-height: 0; padding: 0; border: 1px solid var(--line-3); border-radius: var(--radius-sm); background: var(--surface-field); color: var(--accent-color); cursor: pointer; } +.fw-grid-open:hover { border-color: var(--text-muted); background: var(--bg-hover); } +.fw-grid-open:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fw-grid-open[aria-expanded='true'] { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fw-grid-open[data-look='inherited'] { color: var(--text-muted); border-style: dashed; } +.fw-grid-open[data-look='empty'] { color: var(--text-muted); border-style: dashed; } + +.fw-grid-draw { display: block; flex: none; overflow: visible; } +.fw-grid-draw-frame { fill: none; stroke: var(--line-3); stroke-width: 1; } +.fw-grid-draw-bar { fill: currentColor; fill-opacity: .4; } +.fw-grid-draw[data-state='empty'] .fw-grid-draw-frame { stroke-dasharray: 2 2; } + +.fw-gridpick { position: fixed; top: 0; left: 0; z-index: var(--z-popover); box-sizing: border-box; display: flex; flex-direction: column; gap: var(--space-2); width: min(304px, calc(100vw - var(--space-4))); max-height: calc(100vh - var(--space-4)); overflow-y: auto; overscroll-behavior: contain; scrollbar-width: none; padding: var(--space-2); pointer-events: auto; border: 1px solid var(--line-2); border-radius: var(--radius-xl); 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-gridpick::-webkit-scrollbar { display: none; } +.fw-gridpick[hidden], .fw-gridpick [hidden] { display: none; } + +.fw-gridpick-hint { display: grid; gap: var(--space-2); padding: var(--space-2); border: 1px solid var(--accent-line); border-radius: var(--radius); background: var(--accent-wash); } +.fw-gridpick-hint-text { margin: 0; color: var(--text-primary); font-size: var(--fs-12); line-height: 1.4; } +.fw-gridpick-make { justify-self: start; min-height: 0; height: var(--ctl-md); padding: 0 var(--space-3); border: 1px solid var(--accent-line); border-radius: var(--radius); background: var(--accent-soft); color: var(--text-primary); font-size: var(--fs-12); font-weight: 600; cursor: pointer; } +.fw-gridpick-make:hover { background: var(--accent-glow); } +.fw-gridpick-make:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fw-gridpick-make-css { display: block; min-height: 2.6em; overflow: hidden; color: var(--text-muted); font-size: var(--fs-10); line-height: 1.3; text-overflow: ellipsis; white-space: pre; } + +.fw-gridpick-body { display: flex; flex-direction: column; gap: var(--space-2); } +.fw-gridpick-group { display: flex; flex-direction: column; gap: var(--space-1); } +.fw-gridpick-head { padding: var(--space-1) var(--space-1) 0; color: var(--text-muted); font-size: var(--fs-10); letter-spacing: .06em; text-transform: uppercase; } +.fw-gridpick-tiles { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--space-1); } +.fw-gridpick-tiles.is-rows { grid-template-columns: minmax(0, 1fr); gap: 0; } + +.fw-gridpick-entry { display: flex; flex-direction: column; align-items: center; gap: 2px; min-width: 0; min-height: 0; height: auto; padding: 6px var(--space-1) var(--space-1); white-space: normal; border: 1px solid transparent; border-radius: var(--radius); background: transparent; color: var(--text-secondary); text-align: center; cursor: pointer; } +.fw-gridpick-entry .fw-grid-draw { color: var(--text-secondary); } +.fw-gridpick-entry:hover { background: var(--bg-hover); color: var(--text-primary); } +.fw-gridpick-entry:focus { outline: none; } +.fw-gridpick-entry:focus-visible { outline: 2px solid var(--accent-color); outline-offset: -1px; } +.fw-gridpick-entry[aria-pressed='true'] { border-color: var(--accent-line); background: var(--accent-wash); color: var(--text-primary); } +.fw-gridpick-entry[aria-pressed='true'] .fw-grid-draw { color: var(--accent-color); } +.fw-gridpick-entry.is-picked { border-style: dashed; border-color: var(--accent-color); background: var(--accent-soft); } +.fw-gridpick-name { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden; width: 100%; font-size: var(--fs-11); line-height: 1.25; white-space: normal; overflow-wrap: anywhere; } +.fw-gridpick-css { display: block; width: 100%; margin-top: auto; color: var(--text-muted); font-size: var(--fs-9); line-height: 1.3; white-space: normal; overflow-wrap: anywhere; } + +.fw-gridpick-step { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); align-items: center; gap: var(--space-1); } +.fw-gridpick-step-label { display: flex; align-items: center; gap: var(--space-2); min-width: 0; padding-left: var(--space-1); color: var(--text-secondary); font-size: var(--fs-11); } +.fw-gridpick-step-label > span { min-width: 0; line-height: 1.3; } +.fw-gridpick-step-input { flex: none; width: 52px; min-height: 0; height: var(--ctl-sm); padding: 0 var(--space-1); font-size: var(--fs-12); font-variant-numeric: tabular-nums; } +.fw-gridpick-entry-step, .fw-gridpick-entry-row { display: grid; grid-template-columns: auto minmax(0, 1fr); column-gap: var(--space-2); row-gap: 1px; align-items: center; padding: var(--space-1) var(--space-2); text-align: left; } +.fw-gridpick-entry-step > .fw-grid-draw, .fw-gridpick-entry-row > .fw-grid-draw { grid-row: span 2; } +.fw-gridpick-entry-step .fw-gridpick-name, .fw-gridpick-entry-row .fw-gridpick-name { -webkit-line-clamp: 1; line-clamp: 1; } +.fw-gridpick-entry-row .fw-gridpick-css, .fw-gridpick-entry-step .fw-gridpick-css { margin-top: 0; white-space: nowrap; } From b5ea5a428ca5bc9c3ceb7d984dde9de25e8c0ef7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 00:38:06 -0500 Subject: [PATCH 23/31] i18n: the 73 new strings of 0.33.0 (Design field controls, the color picker, the Gradient tab, the grid chooser and the Preferences setting) in all 23 languages, and the color-stop word in Polish, Finnish and Hungarian where it read as a bus stop --- frontend/src/i18n/keys.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/cs.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/da.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/de.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/es-MX.ts | 3 ++ frontend/src/i18n/locales/es.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/fi.ts | 79 ++++++++++++++++++++++++++++-- frontend/src/i18n/locales/fr.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/hu.ts | 79 ++++++++++++++++++++++++++++-- frontend/src/i18n/locales/id.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/it.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/ja.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/ko.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/nb.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/nl.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/pl.ts | 77 ++++++++++++++++++++++++++++- frontend/src/i18n/locales/pt-BR.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/ru.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/sv.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/th.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/tr.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/uk.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/vi.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/zh-CN.ts | 73 +++++++++++++++++++++++++++ frontend/src/i18n/locales/zh-TW.ts | 73 +++++++++++++++++++++++++++ 25 files changed, 1763 insertions(+), 8 deletions(-) diff --git a/frontend/src/i18n/keys.ts b/frontend/src/i18n/keys.ts index 0fa0d9c1..870687f9 100644 --- a/frontend/src/i18n/keys.ts +++ b/frontend/src/i18n/keys.ts @@ -2940,4 +2940,77 @@ export const KEYS: readonly string[] = [ "This file is not a zip archive FormWeb can read. Nothing was imported.", "The archive is password protected. Make the zip again without a password. Nothing was imported.", "The archive is larger than 64.0 MiB, the most a site import takes. Zip only the folder that holds the finished site, leaving out large videos and files it does not use. Nothing was imported.", + "Type {0} by hand: hide its control and edit the CSS text only. Press again to bring the control back.", + "Type {0} by hand", + "CSS text", + "Use for all fields", + "Every Design field now follows this setting.", + "Controls puts sliders, color swatches and choosers next to the Design fields; CSS text shows the typed value only. The switch in a field's label changes that field alone.", + "Design fields", + "Show in Design fields", + "Show controls in Design fields", + "Design fields show the CSS text only.", + "Design fields show their controls.", + "Unit for {0}", + "Inherited: {0}", + "Not set", + "Choose {0}", + "Color picker for {0}", + "Color kinds", + "Solid", + "Saturation and brightness of {0}", + "Hue of {0}", + "Opacity of {0}", + "Hex or rgb() value of {0}", + "Pick a color from the screen", + "Site colors", + "Brand", + "Team library", + "No color", + "A project manager restricted colors to the brand kit: choose a brand or team color, or No color.", + "No brand or team colors yet. Add them in Window > Brand kit.", + "One column", + "{0} columns", + "One row", + "{0} rows", + "Equal columns", + "Equal rows", + "Any number of columns", + "Any number of rows", + "Two columns", + "Narrow left, wide right", + "Wide left, narrow right", + "Slim left, wide right", + "Wide left, slim right", + "Fixed sidebar on the left", + "Fixed sidebar on the right", + "Three columns", + "Wide middle", + "As many as fit", + "At least {0} px each", + "Header and footer", + "Header, content, footer", + "Header and content", + "{0} only takes effect when this element's Display is Grid.", + "Make this element a grid", + "Gradient", + "Gradient type", + "Radial", + "Gradient stops", + "Click to add a stop", + "Position", + "Stop position in percent", + "Remove stop", + "Stop color", + "Angle", + "Angle in degrees", + "Up right", + "Down right", + "Down left", + "Up left", + "Ellipse", + "Reverse", + "Use gradient", + "Gradient stop {0}", + "Stop {0} of {1}, {2} percent", ]; diff --git a/frontend/src/i18n/locales/cs.ts b/frontend/src/i18n/locales/cs.ts index 35b31f4d..75c3a3d0 100644 --- a/frontend/src/i18n/locales/cs.ts +++ b/frontend/src/i18n/locales/cs.ts @@ -2940,4 +2940,77 @@ export default [ "Tento soubor není archiv zip, který FormWeb dokáže přečíst. Nic nebylo importováno.", "Archiv je chráněný heslem. Vytvořte zip znovu bez hesla. Nic nebylo importováno.", "Archiv je větší než 64.0 MiB, což je limit pro import webu. Zabalte do zipu jen složku s hotovým webem a vynechte velká videa a soubory, které nepoužívá. Nic nebylo importováno.", + "{0}: zadat ručně. Skryje ovládací prvek a ponechá jen text CSS k úpravě. Dalším stisknutím ovládací prvek vrátíte.", + "{0}: zadat ručně", + "Text CSS", + "Použít pro všechna pole", + "Všechna pole Návrhu se teď řídí tímto nastavením.", + "Ovládací prvky přidají k polím Návrhu posuvníky, vzorky barev a výběry; Text CSS ukazuje jen zadanou hodnotu. Přepínač v popisku pole mění jen to pole.", + "Pole Návrhu", + "Zobrazit v polích Návrhu", + "Zobrazit ovládací prvky v polích Návrhu", + "Pole Návrhu ukazují jen text CSS.", + "Pole Návrhu ukazují své ovládací prvky.", + "{0}: jednotka", + "Zděděno: {0}", + "Nenastaveno", + "Vybrat: {0}", + "Výběr barvy: {0}", + "Druhy barvy", + "Jednolitá", + "{0}: sytost a jas", + "{0}: odstín", + "{0}: krytí", + "{0}: hodnota hex nebo rgb()", + "Nabrat barvu z obrazovky", + "Barvy webu", + "Značka", + "Týmová knihovna", + "Bez barvy", + "Projektový manažer omezil barvy na sadu značky: vyberte barvu značky nebo týmu, nebo Bez barvy.", + "Zatím žádné barvy značky ani týmu. Přidejte je v nabídce Okno > Sada značky.", + "Jeden sloupec", + "Sloupce: {0}", + "Jeden řádek", + "Řádky: {0}", + "Stejné sloupce", + "Stejné řádky", + "Libovolný počet sloupců", + "Libovolný počet řádků", + "Dva sloupce", + "Úzký vlevo, široký vpravo", + "Široký vlevo, úzký vpravo", + "Velmi úzký vlevo, široký vpravo", + "Široký vlevo, velmi úzký vpravo", + "Pevný boční panel vlevo", + "Pevný boční panel vpravo", + "Tři sloupce", + "Široký střed", + "Kolik se vejde", + "Každý aspoň {0} px", + "Záhlaví a zápatí", + "Záhlaví, obsah, zápatí", + "Záhlaví a obsah", + "„{0}“ platí jen tehdy, když je Zobrazení tohoto prvku Mřížka.", + "Udělat z tohoto prvku mřížku", + "Přechod", + "Typ přechodu", + "Kruhový", + "Zarážky přechodu", + "Kliknutím přidáte zarážku", + "Poloha", + "Poloha zarážky v procentech", + "Odebrat zarážku", + "Barva zarážky", + "Úhel", + "Úhel ve stupních", + "Nahoru vpravo", + "Dolů vpravo", + "Dolů vlevo", + "Nahoru vlevo", + "Elipsa", + "Obrátit", + "Použít přechod", + "Zarážka přechodu {0}", + "Zarážka {0} z {1}, {2} %", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/da.ts b/frontend/src/i18n/locales/da.ts index 0327c252..b2761965 100644 --- a/frontend/src/i18n/locales/da.ts +++ b/frontend/src/i18n/locales/da.ts @@ -2940,4 +2940,77 @@ export default [ "Denne fil er ikke et zip-arkiv, som FormWeb kan læse. Intet blev importeret.", "Arkivet er beskyttet med adgangskode. Lav zip-filen igen uden adgangskode. Intet blev importeret.", "Arkivet er større end 64.0 MiB, som er det maksimale for en siteimport. Zip kun mappen med det færdige site, og udelad store videoer og filer, det ikke bruger. Intet blev importeret.", + "Skriv {0} i hånden: skjuler kontrollen, så du kun redigerer CSS-teksten. Tryk igen for at få kontrollen tilbage.", + "Skriv {0} i hånden", + "CSS-tekst", + "Brug for alle felter", + "Alle Design-felter følger nu denne indstilling.", + "Kontroller viser skydere, farveprøver og vælgere ved siden af Design-felterne; CSS-tekst viser kun den skrevne værdi. Kontakten i et felts etiket ændrer kun det felt.", + "Design-felter", + "Vis i Design-felter", + "Vis kontroller i Design-felter", + "Design-felter viser kun CSS-teksten.", + "Design-felter viser deres kontroller.", + "Enhed for {0}", + "Nedarvet: {0}", + "Ikke angivet", + "Vælg {0}", + "Farvevælger for {0}", + "Farvetyper", + "Ensfarvet", + "Mætning og lysstyrke for {0}", + "Farvetone for {0}", + "Opacitet for {0}", + "Hex- eller rgb()-værdi for {0}", + "Hent en farve fra skærmen", + "Sitets farver", + "Brand", + "Teambibliotek", + "Ingen farve", + "En projektleder har begrænset farverne til brandkittet: vælg en brand- eller teamfarve eller Ingen farve.", + "Ingen brand- eller teamfarver endnu. Tilføj dem under Vindue > Brandkit.", + "Én kolonne", + "{0} kolonner", + "Én række", + "{0} rækker", + "Lige brede kolonner", + "Lige høje rækker", + "Vilkårligt antal kolonner", + "Vilkårligt antal rækker", + "To kolonner", + "Smal til venstre, bred til højre", + "Bred til venstre, smal til højre", + "Meget smal til venstre, bred til højre", + "Bred til venstre, meget smal til højre", + "Fast sidebjælke til venstre", + "Fast sidebjælke til højre", + "Tre kolonner", + "Bred midte", + "Så mange, der er plads til", + "Mindst {0} px hver", + "Sidehoved og sidefod", + "Sidehoved, indhold, sidefod", + "Sidehoved og indhold", + "{0} virker kun, når dette elements Visning er Gitter.", + "Gør dette element til et gitter", + "Forløb", + "Forløbstype", + "Radial", + "Forløbsstop", + "Klik for at tilføje et stop", + "Position", + "Stoppets position i procent", + "Fjern stop", + "Stopfarve", + "Vinkel", + "Vinkel i grader", + "Op til højre", + "Ned til højre", + "Ned til venstre", + "Op til venstre", + "Ellipse", + "Omvendt", + "Brug forløb", + "Forløbsstop {0}", + "Stop {0} af {1}, {2} procent", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/de.ts b/frontend/src/i18n/locales/de.ts index 1af54ec5..c604ed58 100644 --- a/frontend/src/i18n/locales/de.ts +++ b/frontend/src/i18n/locales/de.ts @@ -2940,4 +2940,77 @@ export default [ "Diese Datei ist kein Zip-Archiv, das FormWeb lesen kann. Es wurde nichts importiert.", "Das Archiv ist passwortgeschützt. Erstelle das Zip ohne Passwort neu. Es wurde nichts importiert.", "Das Archiv ist größer als 64.0 MiB, das Maximum für einen Website-Import. Packe nur den Ordner mit der fertigen Website als Zip und lass große Videos und Dateien weg, die sie nicht nutzt. Es wurde nichts importiert.", + "{0} von Hand eingeben: blendet das Steuerelement aus, sodass du nur den CSS-Text bearbeitest. Erneut drücken, um das Steuerelement zurückzuholen.", + "{0} von Hand eingeben", + "CSS-Text", + "Für alle Felder verwenden", + "Alle Design-Felder folgen jetzt dieser Einstellung.", + "Steuerelemente zeigt Schieberegler, Farbfelder und Auswahlen neben den Design-Feldern; CSS-Text zeigt nur den eingegebenen Wert. Der Schalter in der Beschriftung eines Felds ändert nur dieses Feld.", + "Design-Felder", + "In Design-Feldern anzeigen", + "Steuerelemente in Design-Feldern anzeigen", + "Design-Felder zeigen nur den CSS-Text.", + "Design-Felder zeigen ihre Steuerelemente.", + "Einheit für {0}", + "Geerbt: {0}", + "Nicht festgelegt", + "{0} wählen", + "Farbwähler für {0}", + "Farbarten", + "Einfarbig", + "Sättigung und Helligkeit von {0}", + "Farbton von {0}", + "Deckkraft von {0}", + "Hex- oder rgb()-Wert von {0}", + "Farbe vom Bildschirm aufnehmen", + "Website-Farben", + "Marke", + "Team-Bibliothek", + "Keine Farbe", + "Ein Projektmanager hat die Farben auf das Marken-Kit beschränkt: Wähle eine Marken- oder Teamfarbe oder Keine Farbe.", + "Noch keine Marken- oder Teamfarben. Füge sie unter Fenster > Marken-Kit hinzu.", + "Eine Spalte", + "{0} Spalten", + "Eine Zeile", + "{0} Zeilen", + "Gleiche Spalten", + "Gleiche Zeilen", + "Beliebig viele Spalten", + "Beliebig viele Zeilen", + "Zwei Spalten", + "Links schmal, rechts breit", + "Links breit, rechts schmal", + "Links sehr schmal, rechts breit", + "Links breit, rechts sehr schmal", + "Feste Seitenleiste links", + "Feste Seitenleiste rechts", + "Drei Spalten", + "Breite Mitte", + "So viele wie passen", + "Je mindestens {0} px", + "Kopf- und Fußbereich", + "Kopfbereich, Inhalt, Fußbereich", + "Kopfbereich und Inhalt", + "{0} wirkt nur, wenn die Anzeige dieses Elements Raster ist.", + "Dieses Element zum Raster machen", + "Verlauf", + "Verlaufsart", + "Radial", + "Verlaufsstopps", + "Klicken, um einen Stopp hinzuzufügen", + "Position", + "Position des Stopps in Prozent", + "Stopp entfernen", + "Stoppfarbe", + "Winkel", + "Winkel in Grad", + "Nach rechts oben", + "Nach rechts unten", + "Nach links unten", + "Nach links oben", + "Ellipse", + "Umkehren", + "Verlauf verwenden", + "Verlaufsstopp {0}", + "Stopp {0} von {1}, {2} Prozent", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/es-MX.ts b/frontend/src/i18n/locales/es-MX.ts index 86bc01d1..30a50524 100644 --- a/frontend/src/i18n/locales/es-MX.ts +++ b/frontend/src/i18n/locales/es-MX.ts @@ -87,4 +87,7 @@ export default { "Tip: drag a selected element to move it; on a touch screen, hold it first. It snaps to the places the layout allows.": "Consejo: arrastra un elemento seleccionado para moverlo; en una pantalla táctil, mantenlo presionado primero. Se ajusta a los lugares que permite el diseño.", "Turns this code section's HTML and CSS into elements you can click, retype, restyle and drag. The look is measured at desktop width; responsive rules are not carried over. One undo step.": "Convierte el HTML y el CSS de esta sección de código en elementos en los que puedes hacer clic, reescribir, cambiar de estilo y arrastrar. El aspecto se mide al ancho de escritorio; las reglas adaptables no se trasladan. Un solo paso de deshacer.", "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.": "Cada título, párrafo, imagen y caja se convierte en un elemento en el que puedes hacer clic, reescribir, cambiar de estilo y arrastrar. El aspecto se mide al ancho de escritorio; las reglas adaptables no se trasladan, y los scripts y marcos quedan como pequeñas secciones de código.", + "Type {0} by hand: hide its control and edit the CSS text only. Press again to bring the control back.": "Escribir {0} a mano: oculta su control y edita solo el texto CSS. Presiona de nuevo para recuperar el control.", + "No brand or team colors yet. Add them in Window > Brand kit.": "Aún no hay colores de marca ni de equipo. Agrégalos en Ventana > Kit de marca.", + "Click to add a stop": "Haz clic para agregar una parada", } as Record; diff --git a/frontend/src/i18n/locales/es.ts b/frontend/src/i18n/locales/es.ts index 8c2aa480..1d45decc 100644 --- a/frontend/src/i18n/locales/es.ts +++ b/frontend/src/i18n/locales/es.ts @@ -2940,4 +2940,77 @@ export default [ "Este archivo no es un archivo zip que FormWeb pueda leer. No se importó nada.", "El archivo comprimido está protegido con contraseña. Vuelve a crear el zip sin contraseña. No se importó nada.", "El archivo comprimido pesa más de 64.0 MiB, lo máximo que admite una importación de sitio. Comprime en zip solo la carpeta que contiene el sitio terminado, sin archivos multimedia grandes ni archivos que no use. No se importó nada.", + "Escribir {0} a mano: oculta su control y edita solo el texto CSS. Pulsa de nuevo para recuperar el control.", + "Escribir {0} a mano", + "Texto CSS", + "Usar en todos los campos", + "Todos los campos de Diseño siguen ahora este ajuste.", + "Controles pone deslizadores, muestras de color y selectores junto a los campos de Diseño; Texto CSS muestra solo el valor escrito. El interruptor de la etiqueta de un campo cambia solo ese campo.", + "Campos de Diseño", + "Mostrar en los campos de Diseño", + "Mostrar controles en los campos de Diseño", + "Los campos de Diseño muestran solo el texto CSS.", + "Los campos de Diseño muestran sus controles.", + "Unidad de {0}", + "Heredado: {0}", + "Sin definir", + "Elegir {0}", + "Selector de color de {0}", + "Tipos de color", + "Sólido", + "Saturación y brillo de {0}", + "Tono de {0}", + "Opacidad de {0}", + "Valor hexadecimal o rgb() de {0}", + "Tomar un color de la pantalla", + "Colores del sitio", + "Marca", + "Biblioteca del equipo", + "Sin color", + "Un gestor de proyecto limitó los colores al kit de marca: elige un color de la marca o del equipo, o Sin color.", + "Aún no hay colores de marca ni de equipo. Añádelos en Ventana > Kit de marca.", + "Una columna", + "{0} columnas", + "Una fila", + "{0} filas", + "Columnas iguales", + "Filas iguales", + "Cualquier número de columnas", + "Cualquier número de filas", + "Dos columnas", + "Estrecha a la izquierda, ancha a la derecha", + "Ancha a la izquierda, estrecha a la derecha", + "Fina a la izquierda, ancha a la derecha", + "Ancha a la izquierda, fina a la derecha", + "Barra lateral fija a la izquierda", + "Barra lateral fija a la derecha", + "Tres columnas", + "Centro ancho", + "Tantas como quepan", + "Al menos {0} px cada una", + "Cabecera y pie", + "Cabecera, contenido, pie", + "Cabecera y contenido", + "{0} solo tiene efecto cuando la Visualización de este elemento es Cuadrícula.", + "Convertir este elemento en cuadrícula", + "Degradado", + "Tipo de degradado", + "Radial", + "Paradas del degradado", + "Haz clic para añadir una parada", + "Posición", + "Posición de la parada en porcentaje", + "Quitar parada", + "Color de la parada", + "Ángulo", + "Ángulo en grados", + "Arriba a la derecha", + "Abajo a la derecha", + "Abajo a la izquierda", + "Arriba a la izquierda", + "Elipse", + "Invertir", + "Usar degradado", + "Parada {0} del degradado", + "Parada {0} de {1}, {2} por ciento", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/fi.ts b/frontend/src/i18n/locales/fi.ts index 37ba3478..6a435ff2 100644 --- a/frontend/src/i18n/locales/fi.ts +++ b/frontend/src/i18n/locales/fi.ts @@ -22,7 +22,7 @@ export default [ "Toiminnot ja näkyvyysehdot", "Lisää ankkuripiste", "Lisää otsikkorivi ja vähintään yksi tietorivi.", - "Lisää pysäkki leveimpään väliin", + "Lisää väripiste leveimpään väliin", "Lisää väri", "Lisää sarake vasemmalle", "Lisää sarake oikealle", @@ -36,7 +36,7 @@ export default [ "Lisää rivi yläpuolelle", "Lisää rivi alapuolelle", "Lisää lajitteluvaihtoehto", - "Lisää pysäkki", + "Lisää väripiste", "Edistynyt sisällöntuotanto, palvelut ja yhdistetyt työnkulut", "Edistyneet sidonnat ja kyselyt", "Edistynyt studio", @@ -1515,7 +1515,7 @@ export default [ "Tasainen leveys", "Valinnan kaikki 4 kulmaa", "viiva väli viiva väli", - "Liukuvärityökalu (G): vedä asettaaksesi viivan, vedä päitä tai pysäytyksiä, lisää pysäytys napsauttamalla viivaa, poista pysäytys Alt-napsauttamalla sitä.", + "Liukuvärityökalu (G): vedä asettaaksesi viivan, vedä päitä tai väripisteitä, lisää väripiste napsauttamalla viivaa, poista väripiste Alt-napsauttamalla sitä.", "Kun kaksi tai useampi ankkuripiste on valittu, nämä toimivat ankkuripisteisiin. Avainobjekti on viimeksi valittu polku.", "Valinnan kaikki {0} kulmaa", "{0} ankkuripiste valittu", @@ -2940,4 +2940,77 @@ export default [ "Tämä tiedosto ei ole zip-arkisto, jota FormWeb osaa lukea. Mitään ei tuotu.", "Arkisto on suojattu salasanalla. Tee zip-tiedosto uudelleen ilman salasanaa. Mitään ei tuotu.", "Arkisto on suurempi kuin 64.0 MiB, joka on sivustotuonnin enimmäiskoko. Pakkaa zip-tiedostoksi vain valmiin sivuston kansio ja jätä pois suuret videot ja tiedostot, joita se ei käytä. Mitään ei tuotu.", + "{0}: kirjoita käsin. Piilottaa ohjaimen, jolloin muokkaat vain CSS-tekstiä. Palauta ohjain painamalla uudelleen.", + "{0}: kirjoita käsin", + "CSS-teksti", + "Käytä kaikissa kentissä", + "Kaikki Suunnittelu-kentät noudattavat nyt tätä asetusta.", + "Ohjaimet tuo liukusäätimet, värinäytteet ja valitsimet Suunnittelu-kenttien viereen; CSS-teksti näyttää vain kirjoitetun arvon. Kentän nimiössä oleva kytkin muuttaa vain sitä kenttää.", + "Suunnittelu-kentät", + "Näytä Suunnittelu-kentissä", + "Näytä ohjaimet Suunnittelu-kentissä", + "Suunnittelu-kentät näyttävät vain CSS-tekstin.", + "Suunnittelu-kentät näyttävät ohjaimensa.", + "{0}: yksikkö", + "Peritty: {0}", + "Ei asetettu", + "Valitse: {0}", + "Värinvalitsin: {0}", + "Värityypit", + "Tasaväri", + "{0}: kylläisyys ja kirkkaus", + "{0}: sävy", + "{0}: peittävyys", + "{0}: heksa- tai rgb()-arvo", + "Poimi väri näytöltä", + "Sivuston värit", + "Brändi", + "Tiimin kirjasto", + "Ei väriä", + "Projektipäällikkö on rajannut värit brändipakettiin: valitse brändin tai tiimin väri tai Ei väriä.", + "Brändin tai tiimin värejä ei vielä ole. Lisää niitä kohdassa Ikkuna > Brändipaketti.", + "Yksi sarake", + "Sarakkeita: {0}", + "Yksi rivi", + "Rivejä: {0}", + "Yhtä leveät sarakkeet", + "Yhtä korkeat rivit", + "Mikä tahansa määrä sarakkeita", + "Mikä tahansa määrä rivejä", + "Kaksi saraketta", + "Kapea vasen, leveä oikea", + "Leveä vasen, kapea oikea", + "Hyvin kapea vasen, leveä oikea", + "Leveä vasen, hyvin kapea oikea", + "Kiinteä sivupalkki vasemmalla", + "Kiinteä sivupalkki oikealla", + "Kolme saraketta", + "Leveä keskiosa", + "Niin monta kuin mahtuu", + "Kukin vähintään {0} px", + "Ylä- ja alatunniste", + "Ylätunniste, sisältö, alatunniste", + "Ylätunniste ja sisältö", + "{0} vaikuttaa vain, kun tämän elementin Näyttö on Ruudukko.", + "Tee tästä elementistä ruudukko", + "Liukuväri", + "Liukuvärin tyyppi", + "Säteittäinen", + "Liukuvärin väripisteet", + "Lisää väripiste napsauttamalla", + "Sijainti", + "Väripisteen sijainti prosentteina", + "Poista väripiste", + "Väripisteen väri", + "Kulma", + "Kulma asteina", + "Ylös oikealle", + "Alas oikealle", + "Alas vasemmalle", + "Ylös vasemmalle", + "Ellipsi", + "Käänteinen", + "Käytä liukuväriä", + "Liukuvärin väripiste {0}", + "Väripiste {0}/{1}, {2} prosenttia", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/fr.ts b/frontend/src/i18n/locales/fr.ts index da47a695..342907e7 100644 --- a/frontend/src/i18n/locales/fr.ts +++ b/frontend/src/i18n/locales/fr.ts @@ -2940,4 +2940,77 @@ export default [ "Ce fichier n’est pas une archive zip que FormWeb peut lire. Rien n’a été importé.", "L’archive est protégée par un mot de passe. Refaites le zip sans mot de passe. Rien n’a été importé.", "L’archive dépasse 64.0 MiB, le maximum accepté pour une importation de site. Zippez seulement le dossier qui contient le site terminé, sans les grosses vidéos ni les fichiers qu’il n’utilise pas. Rien n’a été importé.", + "Saisir {0} à la main : masque son contrôle et ne laisse que le texte CSS à modifier. Appuyez de nouveau pour rétablir le contrôle.", + "Saisir {0} à la main", + "Texte CSS", + "Appliquer à tous les champs", + "Tous les champs Design suivent maintenant ce réglage.", + "Contrôles place des curseurs, des échantillons de couleur et des sélecteurs à côté des champs Design ; Texte CSS n’affiche que la valeur saisie. Le bouton dans l’étiquette d’un champ ne change que ce champ.", + "Champs Design", + "Afficher dans les champs Design", + "Afficher les contrôles dans les champs Design", + "Les champs Design n’affichent que le texte CSS.", + "Les champs Design affichent leurs contrôles.", + "Unité de {0}", + "Hérité : {0}", + "Non défini", + "Choisir {0}", + "Sélecteur de couleur pour {0}", + "Types de couleur", + "Uni", + "Saturation et luminosité de {0}", + "Teinte de {0}", + "Opacité de {0}", + "Valeur hexadécimale ou rgb() de {0}", + "Prélever une couleur à l’écran", + "Couleurs du site", + "Marque", + "Bibliothèque d’équipe", + "Aucune couleur", + "Un chef de projet a limité les couleurs au kit de marque : choisissez une couleur de la marque ou de l’équipe, ou Aucune couleur.", + "Pas encore de couleurs de marque ou d’équipe. Ajoutez-les dans Fenêtre > Kit de marque.", + "Une colonne", + "{0} colonnes", + "Une ligne", + "{0} lignes", + "Colonnes égales", + "Lignes égales", + "Nombre de colonnes au choix", + "Nombre de lignes au choix", + "Deux colonnes", + "Étroite à gauche, large à droite", + "Large à gauche, étroite à droite", + "Fine à gauche, large à droite", + "Large à gauche, fine à droite", + "Barre latérale fixe à gauche", + "Barre latérale fixe à droite", + "Trois colonnes", + "Milieu large", + "Autant que la place le permet", + "Au moins {0} px chacune", + "En-tête et pied de page", + "En-tête, contenu, pied de page", + "En-tête et contenu", + "{0} ne s’applique que si l’Affichage de cet élément est Grille.", + "Faire de cet élément une grille", + "Dégradé", + "Type de dégradé", + "Radial", + "Points du dégradé", + "Cliquez pour ajouter un point", + "Position", + "Position du point en pourcentage", + "Supprimer le point", + "Couleur du point", + "Angle", + "Angle en degrés", + "En haut à droite", + "En bas à droite", + "En bas à gauche", + "En haut à gauche", + "Ellipse", + "Inverser", + "Utiliser le dégradé", + "Point {0} du dégradé", + "Point {0} sur {1}, {2} pour cent", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/hu.ts b/frontend/src/i18n/locales/hu.ts index c3b470a1..b076a64a 100644 --- a/frontend/src/i18n/locales/hu.ts +++ b/frontend/src/i18n/locales/hu.ts @@ -22,7 +22,7 @@ export default [ "Műveletek és láthatósági feltételek", "Horgonypont hozzáadása", "Adjon hozzá fejlécsort és legalább egy adatsort.", - "Színátmenet-megállópont hozzáadása a legszélesebb résbe", + "Színpont hozzáadása a legszélesebb résbe", "Szín hozzáadása", "Oszlop hozzáadása balra", "Oszlop hozzáadása jobbra", @@ -36,7 +36,7 @@ export default [ "Sor beszúrása fölé", "Sor beszúrása alá", "Rendezési lehetőség hozzáadása", - "Megállópont hozzáadása", + "Színpont hozzáadása", "Haladó szerkesztés, szolgáltatások és összekapcsolt munkafolyamatok", "Haladó kötések és lekérdezések", "Haladó stúdió", @@ -1515,7 +1515,7 @@ export default [ "Egységes szélesség", "A kijelölés mind a 4 sarka", "vonal szünet vonal szünet", - "Színátmenet eszköz (G): húzással adhatja meg a vonalat, húzza a végpontokat vagy a megállókat, kattintson a vonalra megálló hozzáadásához, Alt+kattintás a megállón eltávolítja azt.", + "Színátmenet eszköz (G): húzással adhatja meg a vonalat, húzza a végpontokat vagy a színpontokat, kattintson a vonalra színpont hozzáadásához, Alt+kattintás a színponton eltávolítja azt.", "Ha két vagy több horgonypont van kijelölve, ezek a parancsok a horgonypontokra hatnak. A kulcsobjektum az utoljára kijelölt útvonal.", "A kijelölés összes sarka ({0})", "{0} horgonypont kijelölve", @@ -2940,4 +2940,77 @@ export default [ "Ez a fájl nem olyan zip archívum, amelyet a FormWeb el tud olvasni. Semmi sem lett importálva.", "Az archívum jelszóval védett. Készítsd el újra a zip fájlt jelszó nélkül. Semmi sem lett importálva.", "Az archívum nagyobb 64.0 MiB-nál, ennyit fogad el legfeljebb egy webhelyimportálás. Csak a kész webhelyet tartalmazó mappát tömörítsd zip fájlba, a nagy videók és a nem használt fájlok nélkül. Semmi sem lett importálva.", + "{0}: kézi beírás. Elrejti a vezérlőt, így csak a CSS-szöveget szerkeszted. Nyomd meg újra a vezérlő visszahozásához.", + "{0}: kézi beírás", + "CSS-szöveg", + "Használat minden mezőnél", + "Most már minden Tervezés-mező ezt a beállítást követi.", + "A Vezérlők csúszkákat, színmintákat és választókat tesz a Tervezés-mezők mellé; a CSS-szöveg csak a beírt értéket mutatja. Egy mező címkéjében lévő kapcsoló csak azt a mezőt változtatja meg.", + "Tervezés-mezők", + "Megjelenítés a Tervezés-mezőkben", + "Vezérlők megjelenítése a Tervezés-mezőkben", + "A Tervezés-mezők csak a CSS-szöveget mutatják.", + "A Tervezés-mezők mutatják a vezérlőiket.", + "{0}: mértékegység", + "Örökölt: {0}", + "Nincs beállítva", + "Választás: {0}", + "Színválasztó: {0}", + "Színfajták", + "Egyszínű", + "{0}: telítettség és fényerő", + "{0}: színezet", + "{0}: átlátszatlanság", + "{0}: hexa vagy rgb() érték", + "Szín felvétele a képernyőről", + "A webhely színei", + "Márka", + "Csapatkönyvtár", + "Nincs szín", + "Egy projektmenedzser a márkakészletre korlátozta a színeket: válassz márka- vagy csapatszínt, vagy a Nincs szín lehetőséget.", + "Még nincsenek márka- vagy csapatszínek. Az Ablak > Márkakészlet menüben adhatod hozzá őket.", + "Egy oszlop", + "Oszlopok: {0}", + "Egy sor", + "Sorok: {0}", + "Egyenlő oszlopok", + "Egyenlő sorok", + "Tetszőleges számú oszlop", + "Tetszőleges számú sor", + "Két oszlop", + "Balra keskeny, jobbra széles", + "Balra széles, jobbra keskeny", + "Balra nagyon keskeny, jobbra széles", + "Balra széles, jobbra nagyon keskeny", + "Rögzített oldalsáv balra", + "Rögzített oldalsáv jobbra", + "Három oszlop", + "Széles közép", + "Ahány elfér", + "Mindegyik legalább {0} px", + "Fejléc és lábléc", + "Fejléc, tartalom, lábléc", + "Fejléc és tartalom", + "A(z) „{0}” csak akkor hat, ha ennek az elemnek a Megjelenítése Rács.", + "Az elem átalakítása ráccsá", + "Színátmenet", + "Színátmenet típusa", + "Sugaras", + "Színátmenet színpontjai", + "Kattints színpont hozzáadásához", + "Pozíció", + "A színpont helye százalékban", + "Színpont eltávolítása", + "Színpont színe", + "Szög", + "Szög fokban", + "Fel és jobbra", + "Le és jobbra", + "Le és balra", + "Fel és balra", + "Ellipszis", + "Megfordítás", + "Színátmenet használata", + "{0}. színpont", + "{0}. színpont / {1}, {2}%", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/id.ts b/frontend/src/i18n/locales/id.ts index 549747a1..c5103cfc 100644 --- a/frontend/src/i18n/locales/id.ts +++ b/frontend/src/i18n/locales/id.ts @@ -2940,4 +2940,77 @@ export default [ "File ini bukan arsip zip yang dapat dibaca FormWeb. Tidak ada yang diimpor.", "Arsip dilindungi kata sandi. Buat ulang zip tanpa kata sandi. Tidak ada yang diimpor.", "Arsip lebih besar dari 64.0 MiB, batas maksimal impor situs. Zip hanya folder yang berisi situs yang sudah jadi, tanpa video besar dan file yang tidak dipakainya. Tidak ada yang diimpor.", + "Ketik {0} secara manual: menyembunyikan kontrolnya sehingga Anda hanya mengedit teks CSS. Tekan lagi untuk memunculkan kontrol kembali.", + "Ketik {0} secara manual", + "Teks CSS", + "Gunakan untuk semua kolom", + "Semua kolom Desain kini mengikuti pengaturan ini.", + "Kontrol menampilkan penggeser, contoh warna, dan pemilih di samping kolom Desain; Teks CSS hanya menampilkan nilai yang diketik. Sakelar di label sebuah kolom hanya mengubah kolom itu.", + "Kolom Desain", + "Tampilkan di kolom Desain", + "Tampilkan kontrol di kolom Desain", + "Kolom Desain hanya menampilkan teks CSS.", + "Kolom Desain menampilkan kontrolnya.", + "Satuan untuk {0}", + "Diwarisi: {0}", + "Belum diatur", + "Pilih {0}", + "Pemilih warna untuk {0}", + "Jenis warna", + "Solid", + "Saturasi dan kecerahan {0}", + "Rona {0}", + "Opasitas {0}", + "Nilai heksadesimal atau rgb() untuk {0}", + "Ambil warna dari layar", + "Warna situs", + "Merek", + "Pustaka tim", + "Tanpa warna", + "Manajer proyek membatasi warna ke kit merek: pilih warna merek atau tim, atau Tanpa warna.", + "Belum ada warna merek atau tim. Tambahkan di Jendela > Kit merek.", + "Satu kolom", + "{0} kolom", + "Satu baris", + "{0} baris", + "Kolom sama lebar", + "Baris sama tinggi", + "Jumlah kolom bebas", + "Jumlah baris bebas", + "Dua kolom", + "Sempit di kiri, lebar di kanan", + "Lebar di kiri, sempit di kanan", + "Ramping di kiri, lebar di kanan", + "Lebar di kiri, ramping di kanan", + "Bilah samping tetap di kiri", + "Bilah samping tetap di kanan", + "Tiga kolom", + "Tengah lebar", + "Sebanyak yang muat", + "Masing-masing minimal {0} px", + "Header dan footer", + "Header, konten, footer", + "Header dan konten", + "{0} hanya berlaku jika Tampilan elemen ini adalah Kisi.", + "Jadikan elemen ini kisi", + "Gradien", + "Jenis gradien", + "Radial", + "Stop gradien", + "Klik untuk menambah stop", + "Posisi", + "Posisi stop dalam persen", + "Hapus stop", + "Warna stop", + "Sudut", + "Sudut dalam derajat", + "Ke kanan atas", + "Ke kanan bawah", + "Ke kiri bawah", + "Ke kiri atas", + "Elips", + "Balik", + "Gunakan gradien", + "Stop gradien {0}", + "Stop {0} dari {1}, {2} persen", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/it.ts b/frontend/src/i18n/locales/it.ts index 7cf5bd1b..03e498d7 100644 --- a/frontend/src/i18n/locales/it.ts +++ b/frontend/src/i18n/locales/it.ts @@ -2940,4 +2940,77 @@ export default [ "Questo file non è un archivio zip che FormWeb può leggere. Non è stato importato nulla.", "L'archivio è protetto da password. Crea di nuovo lo zip senza password. Non è stato importato nulla.", "L'archivio supera i 64.0 MiB, il massimo per un'importazione di sito. Comprimi in zip solo la cartella che contiene il sito finito, lasciando fuori video grandi e file che non usa. Non è stato importato nulla.", + "Digita {0} a mano: nasconde il controllo e modifica solo il testo CSS. Premi di nuovo per riavere il controllo.", + "Digita {0} a mano", + "Testo CSS", + "Usa per tutti i campi", + "Ora tutti i campi di Design seguono questa impostazione.", + "Controlli mette cursori, campioni di colore e selettori accanto ai campi di Design; Testo CSS mostra solo il valore digitato. L'interruttore nell'etichetta di un campo cambia solo quel campo.", + "Campi di Design", + "Mostra nei campi di Design", + "Mostra i controlli nei campi di Design", + "I campi di Design mostrano solo il testo CSS.", + "I campi di Design mostrano i loro controlli.", + "Unità di {0}", + "Ereditato: {0}", + "Non impostato", + "Scegli {0}", + "Selettore colore di {0}", + "Tipi di colore", + "Tinta unita", + "Saturazione e luminosità di {0}", + "Tonalità di {0}", + "Opacità di {0}", + "Valore esadecimale o rgb() di {0}", + "Preleva un colore dallo schermo", + "Colori del sito", + "Brand", + "Libreria del team", + "Nessun colore", + "Un project manager ha limitato i colori al brand kit: scegli un colore del brand o del team, oppure Nessun colore.", + "Ancora nessun colore del brand o del team. Aggiungili in Finestra > Brand kit.", + "Una colonna", + "{0} colonne", + "Una riga", + "{0} righe", + "Colonne uguali", + "Righe uguali", + "Numero di colonne a scelta", + "Numero di righe a scelta", + "Due colonne", + "Stretta a sinistra, larga a destra", + "Larga a sinistra, stretta a destra", + "Sottile a sinistra, larga a destra", + "Larga a sinistra, sottile a destra", + "Barra laterale fissa a sinistra", + "Barra laterale fissa a destra", + "Tre colonne", + "Centro largo", + "Quante ne entrano", + "Almeno {0} px ciascuna", + "Intestazione e piè di pagina", + "Intestazione, contenuto, piè di pagina", + "Intestazione e contenuto", + "{0} ha effetto solo quando la Visualizzazione di questo elemento è Griglia.", + "Rendi questo elemento una griglia", + "Sfumatura", + "Tipo di sfumatura", + "Radiale", + "Punti della sfumatura", + "Fai clic per aggiungere un punto", + "Posizione", + "Posizione del punto in percentuale", + "Rimuovi punto", + "Colore del punto", + "Angolo", + "Angolo in gradi", + "In alto a destra", + "In basso a destra", + "In basso a sinistra", + "In alto a sinistra", + "Ellisse", + "Inverti", + "Usa la sfumatura", + "Punto {0} della sfumatura", + "Punto {0} di {1}, {2} percento", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ja.ts b/frontend/src/i18n/locales/ja.ts index 4c1a4dbd..e1af2a5e 100644 --- a/frontend/src/i18n/locales/ja.ts +++ b/frontend/src/i18n/locales/ja.ts @@ -2940,4 +2940,77 @@ export default [ "このファイルは FormWeb が読める zip アーカイブではありません。何もインポートされませんでした。", "アーカイブはパスワードで保護されています。パスワードなしで zip を作り直してください。何もインポートされませんでした。", "アーカイブが 64.0 MiB を超えています。サイトのインポートで扱えるのはここまでです。完成したサイトのフォルダーだけを zip にし、大きな動画や使っていないファイルは除いてください。何もインポートされませんでした。", + "{0} を手入力: コントロールを隠し、CSS テキストだけを編集します。もう一度押すとコントロールが戻ります。", + "{0} を手入力", + "CSS テキスト", + "すべてのフィールドに適用", + "すべての「デザイン」フィールドがこの設定に従うようになりました。", + "「コントロール」は「デザイン」フィールドの横にスライダー、カラースウォッチ、選択肢を表示します。「CSS テキスト」は入力した値だけを表示します。フィールドのラベルにあるスイッチは、そのフィールドだけを切り替えます。", + "「デザイン」フィールド", + "「デザイン」フィールドの表示", + "「デザイン」フィールドにコントロールを表示", + "「デザイン」フィールドに CSS テキストだけを表示しています。", + "「デザイン」フィールドにコントロールを表示しています。", + "{0} の単位", + "継承: {0}", + "未設定", + "{0} を選択", + "{0} のカラーピッカー", + "カラーの種類", + "単色", + "{0} の彩度と明るさ", + "{0} の色相", + "{0} の不透明度", + "{0} の 16 進数または rgb() の値", + "画面からカラーを取得", + "サイトのカラー", + "ブランド", + "チームライブラリ", + "カラーなし", + "プロジェクトマネージャーがカラーをブランドキットに制限しています。ブランドかチームのカラー、または「カラーなし」を選んでください。", + "ブランドやチームのカラーはまだありません。「ウィンドウ > ブランドキット」で追加してください。", + "1 列", + "{0} 列", + "1 行", + "{0} 行", + "均等な列", + "均等な行", + "任意の列数", + "任意の行数", + "2 列", + "左が狭く右が広い", + "左が広く右が狭い", + "左が細く右が広い", + "左が広く右が細い", + "左に固定サイドバー", + "右に固定サイドバー", + "3 列", + "中央を広く", + "入るだけ並べる", + "それぞれ {0} px 以上", + "ヘッダーとフッター", + "ヘッダー、コンテンツ、フッター", + "ヘッダーとコンテンツ", + "{0} は、この要素の「表示方法」が「グリッド」のときだけ効果があります。", + "この要素をグリッドにする", + "グラデーション", + "グラデーションの種類", + "円形", + "グラデーションのストップ", + "クリックしてストップを追加", + "位置", + "ストップの位置 (パーセント)", + "ストップを削除", + "ストップのカラー", + "角度", + "角度 (度)", + "右上へ", + "右下へ", + "左下へ", + "左上へ", + "楕円形", + "反転", + "グラデーションを使用", + "グラデーションのストップ {0}", + "ストップ {0}/{1}、{2} パーセント", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ko.ts b/frontend/src/i18n/locales/ko.ts index cd77c4e8..11ca11e5 100644 --- a/frontend/src/i18n/locales/ko.ts +++ b/frontend/src/i18n/locales/ko.ts @@ -2940,4 +2940,77 @@ export default [ "이 파일은 FormWeb이 읽을 수 있는 zip 아카이브가 아닙니다. 아무것도 가져오지 않았습니다.", "아카이브가 암호로 보호되어 있습니다. 암호 없이 zip을 다시 만드세요. 아무것도 가져오지 않았습니다.", "아카이브가 64.0 MiB를 넘습니다. 사이트 가져오기는 이 크기까지만 받습니다. 완성된 사이트가 있는 폴더만 zip으로 묶고, 큰 동영상과 사용하지 않는 파일은 빼세요. 아무것도 가져오지 않았습니다.", + "{0} 직접 입력: 컨트롤을 숨기고 CSS 텍스트만 편집합니다. 다시 누르면 컨트롤이 돌아옵니다.", + "{0} 직접 입력", + "CSS 텍스트", + "모든 필드에 사용", + "이제 모든 디자인 필드가 이 설정을 따릅니다.", + "컨트롤은 디자인 필드 옆에 슬라이더, 색상 견본, 선택기를 표시하고, CSS 텍스트는 입력한 값만 표시합니다. 필드 레이블의 스위치는 그 필드만 바꿉니다.", + "디자인 필드", + "디자인 필드에 표시", + "디자인 필드에 컨트롤 표시", + "디자인 필드에 CSS 텍스트만 표시합니다.", + "디자인 필드에 컨트롤을 표시합니다.", + "{0} 단위", + "상속됨: {0}", + "설정 안 됨", + "{0} 선택", + "{0} 색상 선택기", + "색상 종류", + "단색", + "{0} 채도와 밝기", + "{0} 색조", + "{0} 불투명도", + "{0} 16진수 또는 rgb() 값", + "화면에서 색상 가져오기", + "사이트 색상", + "브랜드", + "팀 라이브러리", + "색상 없음", + "프로젝트 관리자가 색상을 브랜드 키트로 제한했습니다. 브랜드 또는 팀 색상이나 색상 없음을 선택하세요.", + "아직 브랜드 또는 팀 색상이 없습니다. 창 > 브랜드 키트에서 추가하세요.", + "1열", + "{0}열", + "1행", + "{0}행", + "같은 너비의 열", + "같은 높이의 행", + "원하는 열 수", + "원하는 행 수", + "2열", + "왼쪽 좁게, 오른쪽 넓게", + "왼쪽 넓게, 오른쪽 좁게", + "왼쪽 가늘게, 오른쪽 넓게", + "왼쪽 넓게, 오른쪽 가늘게", + "왼쪽 고정 사이드바", + "오른쪽 고정 사이드바", + "3열", + "가운데 넓게", + "들어가는 만큼", + "각각 최소 {0}px", + "헤더와 푸터", + "헤더, 콘텐츠, 푸터", + "헤더와 콘텐츠", + "{0}은(는) 이 요소의 표시 방식이 격자일 때만 적용됩니다.", + "이 요소를 격자로 만들기", + "그레이디언트", + "그레이디언트 유형", + "방사형", + "그레이디언트 정지점", + "클릭하여 정지점 추가", + "위치", + "정지점 위치(퍼센트)", + "정지점 제거", + "정지점 색상", + "각도", + "각도(도)", + "오른쪽 위", + "오른쪽 아래", + "왼쪽 아래", + "왼쪽 위", + "타원", + "반전", + "그레이디언트 사용", + "그레이디언트 정지점 {0}", + "정지점 {0}/{1}, {2}퍼센트", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/nb.ts b/frontend/src/i18n/locales/nb.ts index 5099d5e3..f716b6c6 100644 --- a/frontend/src/i18n/locales/nb.ts +++ b/frontend/src/i18n/locales/nb.ts @@ -2940,4 +2940,77 @@ export default [ "Denne filen er ikke et zip-arkiv FormWeb kan lese. Ingenting ble importert.", "Arkivet er passordbeskyttet. Lag zip-filen på nytt uten passord. Ingenting ble importert.", "Arkivet er større enn 64.0 MiB, som er det meste en nettstedsimport tar. Zip bare mappen med det ferdige nettstedet, og utelat store videoer og filer det ikke bruker. Ingenting ble importert.", + "Skriv {0} for hånd: skjuler kontrollen, så du bare redigerer CSS-teksten. Trykk igjen for å få kontrollen tilbake.", + "Skriv {0} for hånd", + "CSS-tekst", + "Bruk for alle felt", + "Alle Design-felt følger nå denne innstillingen.", + "Kontroller viser glidebrytere, fargeprøver og velgere ved siden av Design-feltene; CSS-tekst viser bare den skrevne verdien. Bryteren i etiketten til et felt endrer bare det feltet.", + "Design-felt", + "Vis i Design-felt", + "Vis kontroller i Design-felt", + "Design-felt viser bare CSS-teksten.", + "Design-felt viser kontrollene sine.", + "Enhet for {0}", + "Arvet: {0}", + "Ikke angitt", + "Velg {0}", + "Fargevelger for {0}", + "Fargetyper", + "Ensfarget", + "Metning og lysstyrke for {0}", + "Fargetone for {0}", + "Opasitet for {0}", + "Heks- eller rgb()-verdi for {0}", + "Hent en farge fra skjermen", + "Nettstedets farger", + "Merkevare", + "Teambibliotek", + "Ingen farge", + "En prosjektleder har begrenset fargene til merkesettet: velg en merkevare- eller teamfarge, eller Ingen farge.", + "Ingen merkevare- eller teamfarger ennå. Legg dem til under Vindu > Merkesett.", + "Én kolonne", + "{0} kolonner", + "Én rad", + "{0} rader", + "Like brede kolonner", + "Like høye rader", + "Valgfritt antall kolonner", + "Valgfritt antall rader", + "To kolonner", + "Smal til venstre, bred til høyre", + "Bred til venstre, smal til høyre", + "Svært smal til venstre, bred til høyre", + "Bred til venstre, svært smal til høyre", + "Fast sidestolpe til venstre", + "Fast sidestolpe til høyre", + "Tre kolonner", + "Bred midtdel", + "Så mange som får plass", + "Minst {0} px hver", + "Topptekst og bunntekst", + "Topptekst, innhold, bunntekst", + "Topptekst og innhold", + "{0} virker bare når Visning for dette elementet er Rutenett.", + "Gjør dette elementet til et rutenett", + "Fargeovergang", + "Type fargeovergang", + "Radial", + "Stopp i fargeovergangen", + "Klikk for å legge til et stopp", + "Posisjon", + "Stoppets posisjon i prosent", + "Fjern stopp", + "Stoppfarge", + "Vinkel", + "Vinkel i grader", + "Opp til høyre", + "Ned til høyre", + "Ned til venstre", + "Opp til venstre", + "Ellipse", + "Reverser", + "Bruk fargeovergang", + "Fargeovergangsstopp {0}", + "Stopp {0} av {1}, {2} prosent", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/nl.ts b/frontend/src/i18n/locales/nl.ts index 23bd03e0..43662d30 100644 --- a/frontend/src/i18n/locales/nl.ts +++ b/frontend/src/i18n/locales/nl.ts @@ -2940,4 +2940,77 @@ export default [ "Dit bestand is geen zip-archief dat FormWeb kan lezen. Er is niets geïmporteerd.", "Het archief is met een wachtwoord beveiligd. Maak de zip opnieuw zonder wachtwoord. Er is niets geïmporteerd.", "Het archief is groter dan 64.0 MiB, het maximum voor een site-import. Zip alleen de map met de afgewerkte site en laat grote video's en bestanden die ze niet gebruikt weg. Er is niets geïmporteerd.", + "{0} met de hand typen: verbergt de bediening en laat alleen de CSS-tekst over om te bewerken. Druk nogmaals om de bediening terug te halen.", + "{0} met de hand typen", + "CSS-tekst", + "Voor alle velden gebruiken", + "Alle Ontwerp-velden volgen nu deze instelling.", + "Bediening zet schuifregelaars, kleurstalen en kiezers naast de Ontwerp-velden; CSS-tekst toont alleen de getypte waarde. De schakelaar in het label van een veld verandert alleen dat veld.", + "Ontwerp-velden", + "Tonen in Ontwerp-velden", + "Bediening tonen in Ontwerp-velden", + "Ontwerp-velden tonen alleen de CSS-tekst.", + "Ontwerp-velden tonen hun bediening.", + "Eenheid voor {0}", + "Geërfd: {0}", + "Niet ingesteld", + "{0} kiezen", + "Kleurkiezer voor {0}", + "Kleursoorten", + "Effen", + "Verzadiging en helderheid van {0}", + "Tint van {0}", + "Dekking van {0}", + "Hex- of rgb()-waarde van {0}", + "Een kleur van het scherm oppikken", + "Sitekleuren", + "Merk", + "Teambibliotheek", + "Geen kleur", + "Een projectmanager heeft de kleuren beperkt tot de merkkit: kies een merk- of teamkleur, of Geen kleur.", + "Nog geen merk- of teamkleuren. Voeg ze toe via Venster > Merkkit.", + "Eén kolom", + "{0} kolommen", + "Eén rij", + "{0} rijen", + "Gelijke kolommen", + "Gelijke rijen", + "Willekeurig aantal kolommen", + "Willekeurig aantal rijen", + "Twee kolommen", + "Smal links, breed rechts", + "Breed links, smal rechts", + "Heel smal links, breed rechts", + "Breed links, heel smal rechts", + "Vaste zijbalk links", + "Vaste zijbalk rechts", + "Drie kolommen", + "Breed midden", + "Zoveel als er passen", + "Elk minstens {0} px", + "Kop en voet", + "Kop, inhoud, voet", + "Kop en inhoud", + "{0} werkt alleen als de Weergave van dit element Raster is.", + "Dit element een raster maken", + "Verloop", + "Soort verloop", + "Radiaal", + "Verloopstops", + "Klik om een stop toe te voegen", + "Positie", + "Positie van de stop in procenten", + "Stop verwijderen", + "Kleur van de stop", + "Hoek", + "Hoek in graden", + "Rechtsboven", + "Rechtsonder", + "Linksonder", + "Linksboven", + "Ellips", + "Omkeren", + "Verloop gebruiken", + "Verloopstop {0}", + "Stop {0} van {1}, {2} procent", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/pl.ts b/frontend/src/i18n/locales/pl.ts index 4f5e66fe..d52c784d 100644 --- a/frontend/src/i18n/locales/pl.ts +++ b/frontend/src/i18n/locales/pl.ts @@ -22,7 +22,7 @@ export default [ "Akcje i warunki widoczności", "Dodaj punkt kontrolny", "Dodaj wiersz nagłówka i co najmniej jeden wiersz danych.", - "Dodaj przystanek w najszerszej przerwie", + "Dodaj punkt w najszerszej przerwie", "Dodaj kolor", "Dodaj kolumnę po lewej", "Dodaj kolumnę po prawej", @@ -36,7 +36,7 @@ export default [ "Dodaj wiersz powyżej", "Dodaj wiersz poniżej", "Dodaj opcję sortowania", - "Dodaj przystanek", + "Dodaj punkt", "Zaawansowane tworzenie, usługi i połączone przepływy pracy", "Zaawansowane powiązania i zapytania", "Studio zaawansowane", @@ -2940,4 +2940,77 @@ export default [ "Ten plik nie jest archiwum zip, które FormWeb potrafi odczytać. Nic nie zostało zaimportowane.", "Archiwum jest chronione hasłem. Utwórz zip ponownie bez hasła. Nic nie zostało zaimportowane.", "Archiwum jest większe niż 64.0 MiB, czyli limit importu witryny. Spakuj do zip tylko folder z gotową witryną, bez dużych filmów i plików, których ona nie używa. Nic nie zostało zaimportowane.", + "{0}: wpisz ręcznie. Ukrywa kontrolkę, zostaje tylko tekst CSS do edycji. Naciśnij ponownie, aby przywrócić kontrolkę.", + "{0}: wpisz ręcznie", + "Tekst CSS", + "Użyj dla wszystkich pól", + "Wszystkie pola Projektu stosują teraz to ustawienie.", + "Kontrolki dodają suwaki, próbki kolorów i listy wyboru obok pól Projektu; Tekst CSS pokazuje tylko wpisaną wartość. Przełącznik w etykiecie pola zmienia tylko to pole.", + "Pola Projektu", + "Pokazuj w polach Projektu", + "Pokazuj kontrolki w polach Projektu", + "Pola Projektu pokazują tylko tekst CSS.", + "Pola Projektu pokazują swoje kontrolki.", + "{0}: jednostka", + "Odziedziczone: {0}", + "Nie ustawiono", + "Wybierz: {0}", + "Próbnik koloru: {0}", + "Rodzaje koloru", + "Jednolity", + "{0}: nasycenie i jasność", + "{0}: odcień", + "{0}: krycie", + "{0}: wartość szesnastkowa lub rgb()", + "Pobierz kolor z ekranu", + "Kolory witryny", + "Marka", + "Biblioteka zespołu", + "Bez koloru", + "Kierownik projektu ograniczył kolory do zestawu marki: wybierz kolor marki lub zespołu albo Bez koloru.", + "Nie ma jeszcze kolorów marki ani zespołu. Dodaj je w Okno > Zestaw marki.", + "Jedna kolumna", + "Kolumny: {0}", + "Jeden wiersz", + "Wiersze: {0}", + "Równe kolumny", + "Równe wiersze", + "Dowolna liczba kolumn", + "Dowolna liczba wierszy", + "Dwie kolumny", + "Wąska z lewej, szeroka z prawej", + "Szeroka z lewej, wąska z prawej", + "Bardzo wąska z lewej, szeroka z prawej", + "Szeroka z lewej, bardzo wąska z prawej", + "Stały pasek boczny z lewej", + "Stały pasek boczny z prawej", + "Trzy kolumny", + "Szeroki środek", + "Tyle, ile się zmieści", + "Każda co najmniej {0} px", + "Nagłówek i stopka", + "Nagłówek, treść, stopka", + "Nagłówek i treść", + "„{0}” działa tylko wtedy, gdy Wyświetlanie tego elementu to Siatka.", + "Zamień ten element w siatkę", + "Gradient", + "Typ gradientu", + "Radialny", + "Punkty gradientu", + "Kliknij, aby dodać punkt", + "Położenie", + "Położenie punktu w procentach", + "Usuń punkt", + "Kolor punktu", + "Kąt", + "Kąt w stopniach", + "W górę w prawo", + "W dół w prawo", + "W dół w lewo", + "W górę w lewo", + "Elipsa", + "Odwróć", + "Użyj gradientu", + "Punkt gradientu {0}", + "Punkt {0} z {1}, {2}%", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/pt-BR.ts b/frontend/src/i18n/locales/pt-BR.ts index 34bdc8ce..36d928d4 100644 --- a/frontend/src/i18n/locales/pt-BR.ts +++ b/frontend/src/i18n/locales/pt-BR.ts @@ -2940,4 +2940,77 @@ export default [ "Este arquivo não é um arquivo zip que o FormWeb consiga ler. Nada foi importado.", "O arquivo compactado está protegido por senha. Crie o zip de novo sem senha. Nada foi importado.", "O arquivo compactado tem mais de 64.0 MiB, o máximo que uma importação de site aceita. Compacte em zip só a pasta que contém o site pronto, deixando de fora vídeos grandes e arquivos que ele não usa. Nada foi importado.", + "Digitar {0} à mão: oculta o controle e edita só o texto CSS. Clique de novo para trazer o controle de volta.", + "Digitar {0} à mão", + "Texto CSS", + "Usar em todos os campos", + "Todos os campos de Design agora seguem esta configuração.", + "Controles coloca controles deslizantes, amostras de cor e seletores ao lado dos campos de Design; Texto CSS mostra só o valor digitado. A chave no rótulo de um campo muda apenas aquele campo.", + "Campos de Design", + "Mostrar nos campos de Design", + "Mostrar controles nos campos de Design", + "Os campos de Design mostram só o texto CSS.", + "Os campos de Design mostram seus controles.", + "Unidade de {0}", + "Herdado: {0}", + "Não definido", + "Escolher {0}", + "Seletor de cor de {0}", + "Tipos de cor", + "Sólida", + "Saturação e brilho de {0}", + "Matiz de {0}", + "Opacidade de {0}", + "Valor hexadecimal ou rgb() de {0}", + "Capturar uma cor da tela", + "Cores do site", + "Marca", + "Biblioteca da equipe", + "Sem cor", + "Um gerente de projeto restringiu as cores ao kit de marca: escolha uma cor da marca ou da equipe, ou Sem cor.", + "Ainda não há cores da marca nem da equipe. Adicione-as em Janela > Kit de marca.", + "Uma coluna", + "{0} colunas", + "Uma linha", + "{0} linhas", + "Colunas iguais", + "Linhas iguais", + "Qualquer número de colunas", + "Qualquer número de linhas", + "Duas colunas", + "Estreita à esquerda, larga à direita", + "Larga à esquerda, estreita à direita", + "Fina à esquerda, larga à direita", + "Larga à esquerda, fina à direita", + "Barra lateral fixa à esquerda", + "Barra lateral fixa à direita", + "Três colunas", + "Meio largo", + "Quantas couberem", + "Pelo menos {0} px cada", + "Cabeçalho e rodapé", + "Cabeçalho, conteúdo, rodapé", + "Cabeçalho e conteúdo", + "{0} só tem efeito quando a Exibição deste elemento é Grade.", + "Transformar este elemento em grade", + "Gradiente", + "Tipo de gradiente", + "Radial", + "Paradas do gradiente", + "Clique para adicionar uma parada", + "Posição", + "Posição da parada em porcentagem", + "Remover parada", + "Cor da parada", + "Ângulo", + "Ângulo em graus", + "Para cima e à direita", + "Para baixo e à direita", + "Para baixo e à esquerda", + "Para cima e à esquerda", + "Elipse", + "Inverter", + "Usar gradiente", + "Parada {0} do gradiente", + "Parada {0} de {1}, {2} por cento", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ru.ts b/frontend/src/i18n/locales/ru.ts index 94d110aa..e2e7b1fc 100644 --- a/frontend/src/i18n/locales/ru.ts +++ b/frontend/src/i18n/locales/ru.ts @@ -2940,4 +2940,77 @@ export default [ "Этот файл не является zip-архивом, который FormWeb может прочитать. Ничего не импортировано.", "Архив защищён паролем. Создайте zip заново без пароля. Ничего не импортировано.", "Архив больше 64.0 MiB, это предел для импорта сайта. Упакуйте в zip только папку с готовым сайтом, без больших видео и файлов, которые он не использует. Ничего не импортировано.", + "{0}: ввод вручную. Скрывает элемент управления, остаётся только текст CSS. Нажмите ещё раз, чтобы вернуть элемент управления.", + "{0}: ввод вручную", + "Текст CSS", + "Применить ко всем полям", + "Теперь все поля «Дизайна» следуют этой настройке.", + "«Элементы управления» добавляют ползунки, образцы цвета и списки выбора рядом с полями «Дизайна»; «Текст CSS» показывает только введённое значение. Переключатель в подписи поля меняет только это поле.", + "Поля «Дизайна»", + "Показывать в полях «Дизайна»", + "Элементы управления в полях «Дизайна»", + "Поля «Дизайна» показывают только текст CSS.", + "Поля «Дизайна» показывают свои элементы управления.", + "{0}: единица", + "Унаследовано: {0}", + "Не задано", + "Выбрать: {0}", + "Выбор цвета: {0}", + "Виды цвета", + "Сплошной", + "{0}: насыщенность и яркость", + "{0}: цветовой тон", + "{0}: непрозрачность", + "{0}: значение hex или rgb()", + "Взять цвет с экрана", + "Цвета сайта", + "Бренд", + "Командная библиотека", + "Без цвета", + "Менеджер проекта ограничил цвета набором бренда: выберите цвет бренда или команды либо «Без цвета».", + "Цветов бренда и команды пока нет. Добавьте их в меню Окно > Набор бренда.", + "Один столбец", + "Столбцов: {0}", + "Одна строка", + "Строк: {0}", + "Равные столбцы", + "Равные строки", + "Любое число столбцов", + "Любое число строк", + "Два столбца", + "Узкий слева, широкий справа", + "Широкий слева, узкий справа", + "Тонкий слева, широкий справа", + "Широкий слева, тонкий справа", + "Фиксированная боковая панель слева", + "Фиксированная боковая панель справа", + "Три столбца", + "Широкая середина", + "Сколько поместится", + "Каждый не меньше {0} px", + "Шапка и подвал", + "Шапка, контент, подвал", + "Шапка и контент", + "«{0}» действует, только если в поле «Отображение» этого элемента выбрано «Сетка».", + "Сделать этот элемент сеткой", + "Градиент", + "Тип градиента", + "Радиальный", + "Опорные точки градиента", + "Щёлкните, чтобы добавить опорную точку", + "Положение", + "Положение точки в процентах", + "Удалить опорную точку", + "Цвет точки", + "Угол", + "Угол в градусах", + "Вверх и вправо", + "Вниз и вправо", + "Вниз и влево", + "Вверх и влево", + "Эллипс", + "Обратить", + "Применить градиент", + "Опорная точка градиента {0}", + "Точка {0} из {1}, {2} %", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/sv.ts b/frontend/src/i18n/locales/sv.ts index b7ec3508..ebdf9464 100644 --- a/frontend/src/i18n/locales/sv.ts +++ b/frontend/src/i18n/locales/sv.ts @@ -2940,4 +2940,77 @@ export default [ "Den här filen är inte ett zip-arkiv som FormWeb kan läsa. Inget importerades.", "Arkivet är lösenordsskyddat. Skapa zip-filen igen utan lösenord. Inget importerades.", "Arkivet är större än 64.0 MiB, det mesta en webbplatsimport tar emot. Zippa bara mappen med den färdiga webbplatsen och utelämna stora videor och filer den inte använder. Inget importerades.", + "Skriv {0} för hand: döljer kontrollen så att du bara redigerar CSS-texten. Tryck igen för att få tillbaka kontrollen.", + "Skriv {0} för hand", + "CSS-text", + "Använd för alla fält", + "Alla Design-fält följer nu den här inställningen.", + "Kontroller visar reglage, färgprover och väljare bredvid Design-fälten; CSS-text visar bara det skrivna värdet. Brytaren i ett fälts etikett ändrar bara det fältet.", + "Design-fält", + "Visa i Design-fält", + "Visa kontroller i Design-fält", + "Design-fält visar bara CSS-texten.", + "Design-fält visar sina kontroller.", + "Enhet för {0}", + "Ärvt: {0}", + "Inte angivet", + "Välj {0}", + "Färgväljare för {0}", + "Färgtyper", + "Enfärgad", + "Mättnad och ljusstyrka för {0}", + "Nyans för {0}", + "Opacitet för {0}", + "Hex- eller rgb()-värde för {0}", + "Hämta en färg från skärmen", + "Webbplatsens färger", + "Varumärke", + "Teambibliotek", + "Ingen färg", + "En projektledare har begränsat färgerna till varumärkeskitet: välj en varumärkes- eller teamfärg, eller Ingen färg.", + "Inga varumärkes- eller teamfärger än. Lägg till dem under Fönster > Varumärkeskit.", + "En kolumn", + "{0} kolumner", + "En rad", + "{0} rader", + "Lika breda kolumner", + "Lika höga rader", + "Valfritt antal kolumner", + "Valfritt antal rader", + "Två kolumner", + "Smal till vänster, bred till höger", + "Bred till vänster, smal till höger", + "Mycket smal till vänster, bred till höger", + "Bred till vänster, mycket smal till höger", + "Fast sidofält till vänster", + "Fast sidofält till höger", + "Tre kolumner", + "Bred mitt", + "Så många som får plats", + "Minst {0} px vardera", + "Sidhuvud och sidfot", + "Sidhuvud, innehåll, sidfot", + "Sidhuvud och innehåll", + "{0} gäller bara när Visning för det här elementet är Rutnät.", + "Gör det här elementet till ett rutnät", + "Toning", + "Typ av toning", + "Radiell", + "Toningsstopp", + "Klicka för att lägga till ett stopp", + "Position", + "Stoppets position i procent", + "Ta bort stopp", + "Stoppfärg", + "Vinkel", + "Vinkel i grader", + "Uppåt höger", + "Nedåt höger", + "Nedåt vänster", + "Uppåt vänster", + "Ellips", + "Omvänd", + "Använd toning", + "Toningsstopp {0}", + "Stopp {0} av {1}, {2} procent", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/th.ts b/frontend/src/i18n/locales/th.ts index a8b0d369..b48228f0 100644 --- a/frontend/src/i18n/locales/th.ts +++ b/frontend/src/i18n/locales/th.ts @@ -2940,4 +2940,77 @@ export default [ "ไฟล์นี้ไม่ใช่ไฟล์เก็บถาวร zip ที่ FormWeb อ่านได้ ไม่มีสิ่งใดถูกนำเข้า", "ไฟล์เก็บถาวรมีการป้องกันด้วยรหัสผ่าน สร้าง zip ใหม่โดยไม่ใส่รหัสผ่าน ไม่มีสิ่งใดถูกนำเข้า", "ไฟล์เก็บถาวรใหญ่กว่า 64.0 MiB ซึ่งเป็นขนาดสูงสุดที่การนำเข้าไซต์รับได้ บีบอัดเป็น zip เฉพาะโฟลเดอร์ที่มีไซต์ที่เสร็จแล้ว โดยไม่รวมวิดีโอขนาดใหญ่และไฟล์ที่ไซต์ไม่ได้ใช้ ไม่มีสิ่งใดถูกนำเข้า", + "พิมพ์ {0} เอง: ซ่อนตัวควบคุมและแก้ไขเฉพาะข้อความ CSS กดอีกครั้งเพื่อนำตัวควบคุมกลับมา", + "พิมพ์ {0} เอง", + "ข้อความ CSS", + "ใช้กับทุกช่อง", + "ตอนนี้ทุกช่องในดีไซน์ใช้การตั้งค่านี้แล้ว", + "ตัวควบคุมจะแสดงแถบเลื่อน ตัวอย่างสี และตัวเลือกไว้ข้างช่องในดีไซน์ ส่วนข้อความ CSS จะแสดงเฉพาะค่าที่พิมพ์ สวิตช์ในป้ายของช่องจะเปลี่ยนเฉพาะช่องนั้น", + "ช่องในดีไซน์", + "แสดงในช่องดีไซน์", + "แสดงตัวควบคุมในช่องดีไซน์", + "ช่องในดีไซน์แสดงเฉพาะข้อความ CSS", + "ช่องในดีไซน์แสดงตัวควบคุมแล้ว", + "หน่วยของ {0}", + "สืบทอด: {0}", + "ยังไม่ได้ตั้งค่า", + "เลือก {0}", + "ตัวเลือกสีของ {0}", + "ชนิดของสี", + "สีทึบ", + "ความอิ่มตัวและความสว่างของ {0}", + "เฉดสีของ {0}", + "ความทึบของ {0}", + "ค่าฐานสิบหกหรือ rgb() ของ {0}", + "ดูดสีจากหน้าจอ", + "สีของไซต์", + "แบรนด์", + "ไลบรารีทีม", + "ไม่มีสี", + "ผู้จัดการโปรเจกต์จำกัดสีให้ใช้ชุดแบรนด์ เลือกสีของแบรนด์หรือทีม หรือไม่มีสี", + "ยังไม่มีสีของแบรนด์หรือทีม เพิ่มได้ที่ หน้าต่าง > ชุดแบรนด์", + "หนึ่งคอลัมน์", + "{0} คอลัมน์", + "หนึ่งแถว", + "{0} แถว", + "คอลัมน์เท่ากัน", + "แถวเท่ากัน", + "กี่คอลัมน์ก็ได้", + "กี่แถวก็ได้", + "สองคอลัมน์", + "ซ้ายแคบ ขวากว้าง", + "ซ้ายกว้าง ขวาแคบ", + "ซ้ายเรียว ขวากว้าง", + "ซ้ายกว้าง ขวาเรียว", + "แถบด้านข้างคงที่ทางซ้าย", + "แถบด้านข้างคงที่ทางขวา", + "สามคอลัมน์", + "ตรงกลางกว้าง", + "ใส่ได้เท่าที่พอดี", + "อย่างน้อย {0} px ต่อช่อง", + "ส่วนหัวและส่วนท้าย", + "ส่วนหัว เนื้อหา ส่วนท้าย", + "ส่วนหัวและเนื้อหา", + "{0} มีผลเฉพาะเมื่อการแสดงผลขององค์ประกอบนี้เป็นกริด", + "ทำให้องค์ประกอบนี้เป็นกริด", + "ไล่ระดับสี", + "ชนิดการไล่ระดับสี", + "แนวรัศมี", + "จุดหยุดของการไล่ระดับสี", + "คลิกเพื่อเพิ่มจุดหยุด", + "ตำแหน่ง", + "ตำแหน่งของจุดหยุดเป็นเปอร์เซ็นต์", + "ลบจุดหยุด", + "สีของจุดหยุด", + "มุม", + "มุมเป็นองศา", + "ขึ้นขวา", + "ลงขวา", + "ลงซ้าย", + "ขึ้นซ้าย", + "วงรี", + "ย้อนกลับ", + "ใช้การไล่ระดับสี", + "จุดหยุดการไล่ระดับสี {0}", + "จุดหยุด {0} จาก {1}, {2} เปอร์เซ็นต์", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/tr.ts b/frontend/src/i18n/locales/tr.ts index ead956fe..94547158 100644 --- a/frontend/src/i18n/locales/tr.ts +++ b/frontend/src/i18n/locales/tr.ts @@ -2940,4 +2940,77 @@ export default [ "Bu dosya, FormWeb'in okuyabildiği bir zip arşivi değil. Hiçbir şey içe aktarılmadı.", "Arşiv parola korumalı. Zip'i parolasız olarak yeniden oluşturun. Hiçbir şey içe aktarılmadı.", "Arşiv 64.0 MiB'tan büyük; bir site içe aktarması en fazla bu kadarını alır. Yalnızca bitmiş siteyi içeren klasörü, büyük videoları ve kullanmadığı dosyaları dışarıda bırakarak zip'leyin. Hiçbir şey içe aktarılmadı.", + "{0}: elle yaz. Denetimini gizler, yalnızca CSS metnini düzenlersiniz. Denetimi geri getirmek için yeniden basın.", + "{0}: elle yaz", + "CSS metni", + "Tüm alanlarda kullan", + "Artık tüm Tasarım alanları bu ayarı izliyor.", + "Denetimler, Tasarım alanlarının yanına kaydırıcılar, renk örnekleri ve seçiciler koyar; CSS metni yalnızca yazılan değeri gösterir. Bir alanın etiketindeki anahtar yalnızca o alanı değiştirir.", + "Tasarım alanları", + "Tasarım alanlarında göster", + "Tasarım alanlarında denetimleri göster", + "Tasarım alanları yalnızca CSS metnini gösteriyor.", + "Tasarım alanları denetimlerini gösteriyor.", + "{0} birimi", + "Devralınan: {0}", + "Ayarlanmadı", + "Seç: {0}", + "{0} için renk seçici", + "Renk türleri", + "Düz renk", + "{0} doygunluğu ve parlaklığı", + "{0} tonu", + "{0} opaklığı", + "{0} için hex veya rgb() değeri", + "Ekrandan renk al", + "Site renkleri", + "Marka", + "Ekip kitaplığı", + "Renk yok", + "Bir proje yöneticisi renkleri marka setiyle sınırladı: bir marka veya ekip rengi ya da Renk yok seçin.", + "Henüz marka veya ekip rengi yok. Bunları Pencere > Marka seti bölümünden ekleyin.", + "Tek sütun", + "{0} sütun", + "Tek satır", + "{0} satır", + "Eşit sütunlar", + "Eşit satırlar", + "İstediğiniz sayıda sütun", + "İstediğiniz sayıda satır", + "İki sütun", + "Solda dar, sağda geniş", + "Solda geniş, sağda dar", + "Solda ince, sağda geniş", + "Solda geniş, sağda ince", + "Solda sabit kenar çubuğu", + "Sağda sabit kenar çubuğu", + "Üç sütun", + "Geniş orta", + "Sığdığı kadar", + "Her biri en az {0} px", + "Üst bilgi ve alt bilgi", + "Üst bilgi, içerik, alt bilgi", + "Üst bilgi ve içerik", + "{0} yalnızca bu öğenin Görüntüleme değeri Izgara olduğunda etkili olur.", + "Bu öğeyi ızgara yap", + "Degrade", + "Degrade türü", + "Dairesel", + "Degrade durakları", + "Durak eklemek için tıklayın", + "Konum", + "Durağın yüzde olarak konumu", + "Durağı kaldır", + "Durak rengi", + "Açı", + "Derece cinsinden açı", + "Yukarı sağa", + "Aşağı sağa", + "Aşağı sola", + "Yukarı sola", + "Elips", + "Ters Çevir", + "Degradeyi kullan", + "Degrade durağı {0}", + "Durak {0}/{1}, yüzde {2}", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/uk.ts b/frontend/src/i18n/locales/uk.ts index 04c1af98..29d0fd6e 100644 --- a/frontend/src/i18n/locales/uk.ts +++ b/frontend/src/i18n/locales/uk.ts @@ -2940,4 +2940,77 @@ export default [ "Цей файл не є zip-архівом, який FormWeb може прочитати. Нічого не імпортовано.", "Архів захищено паролем. Створіть zip заново без пароля. Нічого не імпортовано.", "Архів більший за 64.0 MiB, це межа для імпорту сайту. Запакуйте в zip лише папку з готовим сайтом, без великих відео та файлів, які він не використовує. Нічого не імпортовано.", + "{0}: ввести вручну. Приховує елемент керування, лишається тільки текст CSS. Натисніть ще раз, щоб повернути елемент керування.", + "{0}: ввести вручну", + "Текст CSS", + "Застосувати до всіх полів", + "Тепер усі поля «Дизайну» дотримуються цього налаштування.", + "«Елементи керування» додають повзунки, зразки кольору й списки вибору поруч із полями «Дизайну»; «Текст CSS» показує лише введене значення. Перемикач у підписі поля змінює лише це поле.", + "Поля «Дизайну»", + "Показувати в полях «Дизайну»", + "Елементи керування в полях «Дизайну»", + "Поля «Дизайну» показують лише текст CSS.", + "Поля «Дизайну» показують свої елементи керування.", + "{0}: одиниця", + "Успадковано: {0}", + "Не задано", + "Вибрати: {0}", + "Вибір кольору: {0}", + "Види кольору", + "Суцільний", + "{0}: насиченість і яскравість", + "{0}: колірний тон", + "{0}: непрозорість", + "{0}: значення hex або rgb()", + "Узяти колір з екрана", + "Кольори сайту", + "Бренд", + "Командна бібліотека", + "Без кольору", + "Керівник проєкту обмежив кольори набором бренду: виберіть колір бренду чи команди або «Без кольору».", + "Кольорів бренду й команди ще немає. Додайте їх у меню Вікно > Набір бренду.", + "Один стовпець", + "Стовпців: {0}", + "Один рядок", + "Рядків: {0}", + "Рівні стовпці", + "Рівні рядки", + "Будь-яка кількість стовпців", + "Будь-яка кількість рядків", + "Два стовпці", + "Вузький ліворуч, широкий праворуч", + "Широкий ліворуч, вузький праворуч", + "Тонкий ліворуч, широкий праворуч", + "Широкий ліворуч, тонкий праворуч", + "Закріплена бічна панель ліворуч", + "Закріплена бічна панель праворуч", + "Три стовпці", + "Широка середина", + "Скільки вміститься", + "Кожен щонайменше {0} px", + "Шапка й нижній колонтитул", + "Шапка, контент, нижній колонтитул", + "Шапка й контент", + "«{0}» діє, лише якщо в полі «Відображення» цього елемента вибрано «Сітка».", + "Зробити цей елемент сіткою", + "Градієнт", + "Тип градієнта", + "Радіальний", + "Опорні точки градієнта", + "Клацніть, щоб додати опорну точку", + "Положення", + "Положення точки у відсотках", + "Видалити опорну точку", + "Колір точки", + "Кут", + "Кут у градусах", + "Вгору й праворуч", + "Вниз і праворуч", + "Вниз і ліворуч", + "Вгору й ліворуч", + "Еліпс", + "Обернути", + "Застосувати градієнт", + "Опорна точка градієнта {0}", + "Точка {0} з {1}, {2} %", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/vi.ts b/frontend/src/i18n/locales/vi.ts index 146442a5..b5b2ffa0 100644 --- a/frontend/src/i18n/locales/vi.ts +++ b/frontend/src/i18n/locales/vi.ts @@ -2940,4 +2940,77 @@ export default [ "Tệp này không phải tệp lưu trữ zip mà FormWeb đọc được. Không có gì được nhập.", "Tệp lưu trữ được bảo vệ bằng mật khẩu. Hãy tạo lại tệp zip không có mật khẩu. Không có gì được nhập.", "Tệp lưu trữ lớn hơn 64.0 MiB, mức tối đa một lần nhập trang web nhận. Chỉ nén zip thư mục chứa trang web đã hoàn chỉnh, bỏ ra các video lớn và tệp nó không dùng. Không có gì được nhập.", + "Gõ {0} bằng tay: ẩn điều khiển của nó và chỉ sửa văn bản CSS. Nhấn lần nữa để đưa điều khiển trở lại.", + "Gõ {0} bằng tay", + "Văn bản CSS", + "Dùng cho mọi trường", + "Giờ mọi trường Thiết kế đều theo cài đặt này.", + "Điều khiển đặt thanh trượt, mẫu màu và bộ chọn cạnh các trường Thiết kế; Văn bản CSS chỉ hiện giá trị đã gõ. Công tắc trong nhãn của một trường chỉ đổi riêng trường đó.", + "Trường Thiết kế", + "Hiện trong trường Thiết kế", + "Hiện điều khiển trong trường Thiết kế", + "Các trường Thiết kế chỉ hiện văn bản CSS.", + "Các trường Thiết kế hiện điều khiển của chúng.", + "Đơn vị cho {0}", + "Kế thừa: {0}", + "Chưa đặt", + "Chọn {0}", + "Bộ chọn màu cho {0}", + "Loại màu", + "Màu đơn", + "Độ bão hòa và độ sáng của {0}", + "Sắc độ của {0}", + "Độ mờ đục của {0}", + "Giá trị hex hoặc rgb() của {0}", + "Lấy màu từ màn hình", + "Màu của trang web", + "Thương hiệu", + "Thư viện nhóm", + "Không màu", + "Một quản lý dự án đã giới hạn màu trong bộ nhận diện thương hiệu: hãy chọn một màu thương hiệu hoặc màu nhóm, hoặc Không màu.", + "Chưa có màu thương hiệu hay màu nhóm. Hãy thêm trong Cửa sổ > Bộ nhận diện thương hiệu.", + "Một cột", + "{0} cột", + "Một hàng", + "{0} hàng", + "Các cột bằng nhau", + "Các hàng bằng nhau", + "Số cột tùy ý", + "Số hàng tùy ý", + "Hai cột", + "Trái hẹp, phải rộng", + "Trái rộng, phải hẹp", + "Trái mảnh, phải rộng", + "Trái rộng, phải mảnh", + "Thanh bên cố định ở trái", + "Thanh bên cố định ở phải", + "Ba cột", + "Giữa rộng", + "Vừa bao nhiêu xếp bấy nhiêu", + "Mỗi cột ít nhất {0} px", + "Đầu trang và chân trang", + "Đầu trang, nội dung, chân trang", + "Đầu trang và nội dung", + "{0} chỉ có tác dụng khi Hiển thị của phần tử này là Lưới.", + "Biến phần tử này thành lưới", + "Chuyển màu", + "Kiểu chuyển màu", + "Xuyên tâm", + "Các điểm dừng chuyển màu", + "Nhấp để thêm điểm dừng", + "Vị trí", + "Vị trí điểm dừng theo phần trăm", + "Xóa điểm dừng", + "Màu điểm dừng", + "Góc", + "Góc theo độ", + "Lên phải", + "Xuống phải", + "Xuống trái", + "Lên trái", + "Elip", + "Đảo ngược", + "Dùng chuyển màu", + "Điểm dừng chuyển màu {0}", + "Điểm dừng {0}/{1}, {2} phần trăm", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index e88961cc..c06909ca 100644 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -2940,4 +2940,77 @@ export default [ "此文件不是 FormWeb 能读取的 zip 压缩包。未导入任何内容。", "压缩包受密码保护。请不设密码重新打包 zip。未导入任何内容。", "压缩包大于 64.0 MiB,超过了站点导入的上限。请只将包含完成站点的文件夹打包为 zip,并去掉大型视频和站点不使用的文件。未导入任何内容。", + "手动输入{0}:隐藏其控件,只编辑 CSS 文本。再按一次可恢复控件。", + "手动输入{0}", + "CSS 文本", + "应用到所有字段", + "现在所有“设计”字段都遵循此设置。", + "“控件”会在“设计”字段旁显示滑块、色板和选择器;“CSS 文本”只显示输入的值。字段标签中的开关只改变该字段。", + "“设计”字段", + "在“设计”字段中显示", + "在“设计”字段中显示控件", + "“设计”字段只显示 CSS 文本。", + "“设计”字段显示其控件。", + "{0}的单位", + "继承:{0}", + "未设置", + "选择{0}", + "{0}的拾色器", + "颜色类型", + "纯色", + "{0}的饱和度和亮度", + "{0}的色相", + "{0}的不透明度", + "{0}的十六进制或 rgb() 值", + "从屏幕上吸取颜色", + "站点颜色", + "品牌", + "团队资源库", + "无颜色", + "项目经理已将颜色限制为品牌套件:请选择品牌或团队颜色,或选择“无颜色”。", + "还没有品牌或团队颜色。请在“窗口 > 品牌套件”中添加。", + "一列", + "{0} 列", + "一行", + "{0} 行", + "等宽列", + "等高行", + "任意列数", + "任意行数", + "两列", + "左窄右宽", + "左宽右窄", + "左细右宽", + "左宽右细", + "左侧固定侧栏", + "右侧固定侧栏", + "三列", + "中间宽", + "尽量多放", + "每个至少 {0} px", + "页眉和页脚", + "页眉、内容、页脚", + "页眉和内容", + "只有当此元素的“显示方式”为“网格”时,{0}才会生效。", + "将此元素设为网格", + "渐变", + "渐变类型", + "径向", + "渐变色标", + "点击添加色标", + "位置", + "色标位置(百分比)", + "删除色标", + "色标颜色", + "角度", + "角度(度)", + "向右上", + "向右下", + "向左下", + "向左上", + "椭圆", + "反向", + "使用渐变", + "渐变色标 {0}", + "第 {0} 个色标,共 {1} 个,{2}%", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index 89b8fa15..8fe58323 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -2940,4 +2940,77 @@ export default [ "此檔案不是 FormWeb 能讀取的 zip 封存檔。未匯入任何內容。", "封存檔受密碼保護。請不設密碼重新打包 zip。未匯入任何內容。", "封存檔大於 64.0 MiB,超過網站匯入的上限。請只將包含完成網站的資料夾打包成 zip,並去掉大型影片和網站不使用的檔案。未匯入任何內容。", + "手動輸入{0}:隱藏其控制項,只編輯 CSS 文字。再按一次可恢復控制項。", + "手動輸入{0}", + "CSS 文字", + "套用到所有欄位", + "現在所有「設計」欄位都遵循此設定。", + "「控制項」會在「設計」欄位旁顯示滑桿、色票和選擇器;「CSS 文字」只顯示輸入的值。欄位標籤中的開關只會變更該欄位。", + "「設計」欄位", + "在「設計」欄位中顯示", + "在「設計」欄位中顯示控制項", + "「設計」欄位只顯示 CSS 文字。", + "「設計」欄位顯示其控制項。", + "{0}的單位", + "繼承:{0}", + "未設定", + "選擇{0}", + "{0}的檢色器", + "顏色類型", + "純色", + "{0}的飽和度和亮度", + "{0}的色相", + "{0}的不透明度", + "{0}的十六進位或 rgb() 值", + "從螢幕上擷取顏色", + "網站顏色", + "品牌", + "團隊資源庫", + "無顏色", + "專案經理已將顏色限制為品牌套件:請選擇品牌或團隊顏色,或選擇「無顏色」。", + "還沒有品牌或團隊顏色。請在「視窗 > 品牌套件」中新增。", + "一欄", + "{0} 欄", + "一列", + "{0} 列", + "等寬欄", + "等高列", + "任意欄數", + "任意列數", + "兩欄", + "左窄右寬", + "左寬右窄", + "左細右寬", + "左寬右細", + "左側固定側邊欄", + "右側固定側邊欄", + "三欄", + "中間寬", + "盡量多放", + "每個至少 {0} px", + "頁首和頁尾", + "頁首、內容、頁尾", + "頁首和內容", + "只有當此元素的「顯示方式」為「格線」時,{0}才會生效。", + "將此元素設為格線", + "漸層", + "漸層類型", + "放射狀", + "漸層色標", + "按一下以新增色標", + "位置", + "色標位置(百分比)", + "移除色標", + "色標顏色", + "角度", + "角度(度)", + "向右上", + "向右下", + "向左下", + "向左上", + "橢圓形", + "反向", + "使用漸層", + "漸層色標 {0}", + "第 {0} 個色標,共 {1} 個,{2}%", ] as readonly string[]; From 7aa4f54812c35381bead0a9b71b7b44585feafc4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 00:53:12 -0500 Subject: [PATCH 24/31] feat(inspector): the Background picker has a Gradient tab: linear or radial, stops that can be added, dragged, recolored and removed, an angle or direction, and reverse; it writes one plain CSS gradient, opens a typed gradient it can represent, and leaves any other value exactly as typed --- .../inspector/controls/gradient-model.ts | 339 ++++++++++++ .../features/inspector/controls/gradient.ts | 510 ++++++++++++++++++ .../src/features/inspector/controls/index.ts | 2 + frontend/src/styles/control-gradient.css | 28 + 4 files changed, 879 insertions(+) create mode 100644 frontend/src/features/inspector/controls/gradient-model.ts create mode 100644 frontend/src/features/inspector/controls/gradient.ts create mode 100644 frontend/src/styles/control-gradient.css diff --git a/frontend/src/features/inspector/controls/gradient-model.ts b/frontend/src/features/inspector/controls/gradient-model.ts new file mode 100644 index 00000000..918f1aa3 --- /dev/null +++ b/frontend/src/features/inspector/controls/gradient-model.ts @@ -0,0 +1,339 @@ +export type GradientKind = 'linear' | 'radial'; +export type RadialShape = 'circle' | 'ellipse'; + +export interface GradientStop { + color: string; + position: number; +} + +export interface Gradient { + kind: GradientKind; + angle: number; + to: string; + shape: RadialShape; + size: string; + at: string; + stops: GradientStop[]; +} + +export interface Rgba { r: number; g: number; b: number; a: number } + +const SIDES = ['top', 'right', 'bottom', 'left']; +const SIDE_ANGLE: Record = { top: 0, right: 90, bottom: 180, left: 270, 'top right': 45, 'bottom right': 135, 'bottom left': 225, 'top left': 315 }; +const EXTENTS = ['closest-side', 'closest-corner', 'farthest-side', 'farthest-corner']; +const POSITION_WORDS = ['center', 'top', 'right', 'bottom', 'left']; +const COLOR_FUNCTIONS = ['rgb', 'rgba', 'hsl', 'hsla', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'color', 'color-mix', 'var']; + +const NAMED: Record = { + aliceblue: 'f0f8ff', antiquewhite: 'faebd7', aqua: '00ffff', aquamarine: '7fffd4', azure: 'f0ffff', beige: 'f5f5dc', bisque: 'ffe4c4', black: '000000', + blanchedalmond: 'ffebcd', blue: '0000ff', blueviolet: '8a2be2', brown: 'a52a2a', burlywood: 'deb887', cadetblue: '5f9ea0', chartreuse: '7fff00', + chocolate: 'd2691e', coral: 'ff7f50', cornflowerblue: '6495ed', cornsilk: 'fff8dc', crimson: 'dc143c', cyan: '00ffff', darkblue: '00008b', + darkcyan: '008b8b', darkgoldenrod: 'b8860b', darkgray: 'a9a9a9', darkgreen: '006400', darkgrey: 'a9a9a9', darkkhaki: 'bdb76b', darkmagenta: '8b008b', + darkolivegreen: '556b2f', darkorange: 'ff8c00', darkorchid: '9932cc', darkred: '8b0000', darksalmon: 'e9967a', darkseagreen: '8fbc8f', + darkslateblue: '483d8b', darkslategray: '2f4f4f', darkslategrey: '2f4f4f', darkturquoise: '00ced1', darkviolet: '9400d3', deeppink: 'ff1493', + deepskyblue: '00bfff', dimgray: '696969', dimgrey: '696969', dodgerblue: '1e90ff', firebrick: 'b22222', floralwhite: 'fffaf0', forestgreen: '228b22', + fuchsia: 'ff00ff', gainsboro: 'dcdcdc', ghostwhite: 'f8f8ff', gold: 'ffd700', goldenrod: 'daa520', gray: '808080', green: '008000', + greenyellow: 'adff2f', grey: '808080', honeydew: 'f0fff0', hotpink: 'ff69b4', indianred: 'cd5c5c', indigo: '4b0082', ivory: 'fffff0', khaki: 'f0e68c', + lavender: 'e6e6fa', lavenderblush: 'fff0f5', lawngreen: '7cfc00', lemonchiffon: 'fffacd', lightblue: 'add8e6', lightcoral: 'f08080', + lightcyan: 'e0ffff', lightgoldenrodyellow: 'fafad2', lightgray: 'd3d3d3', lightgreen: '90ee90', lightgrey: 'd3d3d3', lightpink: 'ffb6c1', + lightsalmon: 'ffa07a', lightseagreen: '20b2aa', lightskyblue: '87cefa', lightslategray: '778899', lightslategrey: '778899', lightsteelblue: 'b0c4de', + lightyellow: 'ffffe0', lime: '00ff00', limegreen: '32cd32', linen: 'faf0e6', magenta: 'ff00ff', maroon: '800000', mediumaquamarine: '66cdaa', + mediumblue: '0000cd', mediumorchid: 'ba55d3', mediumpurple: '9370db', mediumseagreen: '3cb371', mediumslateblue: '7b68ee', + mediumspringgreen: '00fa9a', mediumturquoise: '48d1cc', mediumvioletred: 'c71585', midnightblue: '191970', mintcream: 'f5fffa', mistyrose: 'ffe4e1', + moccasin: 'ffe4b5', navajowhite: 'ffdead', navy: '000080', oldlace: 'fdf5e6', olive: '808000', olivedrab: '6b8e23', orange: 'ffa500', + orangered: 'ff4500', orchid: 'da70d6', palegoldenrod: 'eee8aa', palegreen: '98fb98', paleturquoise: 'afeeee', palevioletred: 'db7093', + papayawhip: 'ffefd5', peachpuff: 'ffdab9', peru: 'cd853f', pink: 'ffc0cb', plum: 'dda0dd', powderblue: 'b0e0e6', purple: '800080', + rebeccapurple: '663399', red: 'ff0000', rosybrown: 'bc8f8f', royalblue: '4169e1', saddlebrown: '8b4513', salmon: 'fa8072', sandybrown: 'f4a460', + seagreen: '2e8b57', seashell: 'fff5ee', sienna: 'a0522d', silver: 'c0c0c0', skyblue: '87ceeb', slateblue: '6a5acd', slategray: '708090', + slategrey: '708090', snow: 'fffafa', springgreen: '00ff7f', steelblue: '4682b4', tan: 'd2b48c', teal: '008080', thistle: 'd8bfd8', tomato: 'ff6347', + turquoise: '40e0d0', violet: 'ee82ee', wheat: 'f5deb3', white: 'ffffff', whitesmoke: 'f5f5f5', yellow: 'ffff00', yellowgreen: '9acd32', +}; + +function splitTop(text: string, separator: ',' | ' '): string[] | null { + const parts: string[] = []; + let depth = 0; + let start = 0; + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (c === '(') depth++; + else if (c === ')') { depth--; if (depth < 0) return null; } + else if (depth === 0 && (separator === ',' ? c === ',' : /\s/.test(c))) { + parts.push(text.slice(start, i)); + start = i + 1; + } + } + if (depth !== 0) return null; + parts.push(text.slice(start)); + return separator === ' ' ? parts.filter(Boolean) : parts.map(part => part.trim()); +} + +function functionCall(text: string): { name: string; body: string } | null { + const match = /^([a-z-]+)\(([\s\S]*)\)$/i.exec(text.trim()); + if (!match) return null; + const body = match[2]; + let depth = 0; + for (const c of body) { + if (c === '(') depth++; + else if (c === ')' && --depth < 0) return null; + } + return depth === 0 ? { name: match[1].toLowerCase(), body } : null; +} + +export function isColor(text: string): boolean { + const value = text.trim().toLowerCase(); + if (/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(value)) return true; + if (value === 'transparent' || value === 'currentcolor' || value in NAMED) return true; + const call = functionCall(value); + if (!call || !COLOR_FUNCTIONS.includes(call.name) || !call.body.trim()) return false; + if (call.name === 'var') return /^--[\w-]+(\s*,[\s\S]+)?$/.test(call.body.trim()); + return !/\bcalc\(/.test(call.body); +} + +function parsePercent(text: string): number | null { + const match = /^(-?\d*\.?\d+)%$/.exec(text); + if (match) return Number(match[1]); + return /^0*\.?0+$/.test(text) ? 0 : null; +} + +function parseStop(text: string): { color: string; position: number | null } | null { + const parts = splitTop(text, ' '); + if (!parts || !parts.length || parts.length > 2) return null; + const color = parts[0]; + if (!isColor(color)) return null; + if (parts.length === 1) return { color, position: null }; + const position = parsePercent(parts[1]); + if (position === null || position < 0 || position > 100) return null; + return { color, position }; +} + +function parsePosition(words: string[]): string | null { + if (!words.length || words.length > 4) return null; + for (const word of words) { + if (POSITION_WORDS.includes(word)) continue; + if (/^-?\d*\.?\d+(%|px|em|rem)$/.test(word) || /^0+$/.test(word)) continue; + return null; + } + return words.join(' '); +} + +function parseRadialHead(text: string, gradient: Gradient): boolean { + const words = splitTop(text, ' '); + if (!words || !words.length) return false; + const atIndex = words.indexOf('at'); + const head = atIndex === -1 ? words : words.slice(0, atIndex); + if (atIndex !== -1) { + const at = parsePosition(words.slice(atIndex + 1)); + if (at === null) return false; + gradient.at = at; + } + if (head.length > 2) return false; + let shape = ''; + for (const word of head) { + if ((word === 'circle' || word === 'ellipse') && !shape) shape = word; + else if (EXTENTS.includes(word) && !gradient.size) gradient.size = word; + else return false; + } + if (shape) gradient.shape = shape as RadialShape; + return true; +} + +function parseLinearHead(text: string, gradient: Gradient): boolean | null { + const angle = /^(-?\d*\.?\d+)deg$/.exec(text); + if (angle) { + gradient.angle = Number(angle[1]); + return true; + } + const words = text.split(/\s+/); + if (words[0] !== 'to') return isColor(splitTop(text, ' ')?.[0] ?? '') ? null : false; + const sides = words.slice(1); + if (!sides.length || sides.length > 2 || !sides.every(side => SIDES.includes(side))) return false; + if (sides.length === 2 && (sides[0] === sides[1] || (SIDES.indexOf(sides[0]) % 2) === (SIDES.indexOf(sides[1]) % 2))) return false; + const key = sides.length === 2 ? [sides.find(s => s === 'top' || s === 'bottom'), sides.find(s => s === 'left' || s === 'right')].join(' ') : sides[0]; + gradient.to = key; + gradient.angle = SIDE_ANGLE[key]; + return true; +} + +export function blankGradient(): Gradient { + return { kind: 'linear', angle: 180, to: '', shape: 'ellipse', size: '', at: '', stops: [] }; +} + +export function parseGradient(text: string): Gradient | null { + const call = functionCall(text.trim()); + if (!call || (call.name !== 'linear-gradient' && call.name !== 'radial-gradient')) return null; + const parts = splitTop(call.body, ','); + if (!parts || parts.some(part => !part)) return null; + const gradient = blankGradient(); + gradient.kind = call.name === 'linear-gradient' ? 'linear' : 'radial'; + let first = parts[0].toLowerCase(); + if (gradient.kind === 'linear') { + const head = parseLinearHead(first.trim(), gradient); + if (head === false) return null; + if (head) parts.shift(); + } else { + first = first.trim(); + const words = splitTop(first, ' ') ?? []; + if (!isColor(words[0] ?? '')) { + if (!parseRadialHead(first, gradient)) return null; + parts.shift(); + } + } + if (parts.length < 2) return null; + const raw: { color: string; position: number | null }[] = []; + for (const part of parts) { + const stop = parseStop(part); + if (!stop) return null; + raw.push(stop); + } + if (raw[0].position === null) raw[0].position = 0; + if (raw[raw.length - 1].position === null) raw[raw.length - 1].position = Math.max(100, ...raw.map(stop => stop.position ?? 0)); + let highest = 0; + for (const stop of raw) if (stop.position !== null) { stop.position = Math.max(stop.position, highest); highest = stop.position; } + for (let i = 1; i < raw.length; i++) { + if (raw[i].position !== null) continue; + let j = i; + while (raw[j].position === null) j++; + const from = raw[i - 1].position as number; + const to = raw[j].position as number; + for (let k = i; k < j; k++) raw[k].position = from + (to - from) * (k - i + 1) / (j - i + 1); + } + if (raw.some(stop => (stop.position as number) > 100)) return null; + gradient.stops = raw.map(stop => ({ color: stop.color, position: round(stop.position as number) })); + return gradient; +} + +export function round(value: number): number { + return Math.round(value * 100) / 100; +} + +function number(value: number): string { + return String(round(value)); +} + +export function normaliseAngle(angle: number): number { + return round(((angle % 360) + 360) % 360); +} + +export function sortedStops(stops: readonly T[]): T[] { + return stops.map((stop, index) => ({ stop, index })).sort((a, b) => a.stop.position - b.stop.position || a.index - b.index).map(item => item.stop); +} + +export function stopList(stops: readonly GradientStop[]): string { + return sortedStops(stops).map(stop => `${stop.color.trim()} ${number(stop.position)}%`).join(', '); +} + +export function serializeGradient(gradient: Gradient): string { + const stops = stopList(gradient.stops); + if (gradient.kind === 'linear') { + const direction = gradient.to ? `to ${gradient.to}` : `${number(gradient.angle)}deg`; + return `linear-gradient(${direction}, ${stops})`; + } + const head = [gradient.shape, gradient.size, gradient.at ? `at ${gradient.at}` : ''].filter(Boolean).join(' '); + return `radial-gradient(${head}, ${stops})`; +} + +function clamp(value: number, low = 0, high = 1): number { + return Math.min(high, Math.max(low, value)); +} + +function hslToRgb(h: number, s: number, l: number): [number, number, number] { + const k = (n: number): number => (n + h / 30) % 12; + const a = s * Math.min(l, 1 - l); + const f = (n: number): number => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1)); + return [f(0) * 255, f(8) * 255, f(4) * 255]; +} + +function channel(text: string, scale: number): number | null { + const match = /^(-?\d*\.?\d+)(%?)$/.exec(text); + if (!match) return null; + return match[2] ? Number(match[1]) / 100 * scale : Number(match[1]); +} + +export function toRgba(text: string): Rgba | null { + const value = text.trim().toLowerCase(); + if (value === 'transparent') return { r: 0, g: 0, b: 0, a: 0 }; + const hex = value.startsWith('#') ? value.slice(1) : NAMED[value]; + if (hex !== undefined) { + if (!/^([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(hex)) return null; + const full = hex.length <= 4 ? hex.split('').map(c => c + c).join('') : hex; + const n = (i: number): number => parseInt(full.slice(i, i + 2), 16); + return { r: n(0), g: n(2), b: n(4), a: full.length === 8 ? n(6) / 255 : 1 }; + } + const call = functionCall(value); + if (!call || !['rgb', 'rgba', 'hsl', 'hsla'].includes(call.name)) return null; + const pieces = call.body.replace(/\//g, ' / ').split(/[\s,]+/).filter(piece => piece && piece !== '/'); + if (pieces.length < 3 || pieces.length > 4) return null; + const alpha = pieces.length === 4 ? channel(pieces[3], 1) : 1; + if (alpha === null) return null; + if (call.name.startsWith('rgb')) { + const rgb = pieces.slice(0, 3).map(piece => channel(piece, 255)); + if (rgb.some(c => c === null)) return null; + const [r, g, b] = rgb as number[]; + return { r: clamp(r, 0, 255), g: clamp(g, 0, 255), b: clamp(b, 0, 255), a: clamp(alpha) }; + } + const h = /^(-?\d*\.?\d+)(deg)?$/.exec(pieces[0]); + const s = channel(pieces[1], 1); + const l = channel(pieces[2], 1); + if (!h || s === null || l === null) return null; + const [r, g, b] = hslToRgb(((Number(h[1]) % 360) + 360) % 360, clamp(s), clamp(l)); + return { r, g, b, a: clamp(alpha) }; +} + +export function toHex(color: Rgba): string { + const part = (n: number): string => Math.round(clamp(n, 0, 255)).toString(16).padStart(2, '0'); + const alpha = color.a >= 1 ? '' : part(color.a * 255); + return `#${part(color.r)}${part(color.g)}${part(color.b)}${alpha}`; +} + +export function mix(a: Rgba, b: Rgba, t: number): Rgba { + const alpha = a.a + (b.a - a.a) * t; + if (alpha <= 0) return { r: 0, g: 0, b: 0, a: 0 }; + const c = (x: number, y: number): number => (x * a.a + (y * b.a - x * a.a) * t) / alpha; + return { r: c(a.r, b.r), g: c(a.g, b.g), b: c(a.b, b.b), a: alpha }; +} + +export function colorAt(stops: readonly GradientStop[], position: number, resolve: (color: string) => Rgba | null = toRgba): string { + const sorted = sortedStops(stops); + if (!sorted.length) return '#000000'; + if (position <= sorted[0].position) return sorted[0].color; + const last = sorted[sorted.length - 1]; + if (position >= last.position) return last.color; + let i = 0; + while (sorted[i + 1].position < position) i++; + const before = sorted[i]; + const after = sorted[i + 1]; + if (after.position <= before.position) return after.color; + const t = (position - before.position) / (after.position - before.position); + const a = resolve(before.color); + const b = resolve(after.color); + if (!a || !b) return t < 0.5 ? before.color : after.color; + return toHex(mix(a, b, t)); +} + +export function luminance(color: Rgba): number { + const lin = (n: number): number => { const c = n / 255; return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }; + return 0.2126 * lin(color.r) + 0.7152 * lin(color.g) + 0.0722 * lin(color.b); +} + +export const DEFAULT_START = '#5b3cc4'; + +export function starterGradient(color: string): Gradient { + const gradient = blankGradient(); + gradient.angle = 135; + const given = color.trim(); + const base = given && isColor(given) && toRgba(given)?.a !== 0 && given.toLowerCase() !== 'currentcolor' ? given : DEFAULT_START; + const rgba = toRgba(base); + let second: string; + if (rgba) { + const target = luminance(rgba) > 0.4 ? { r: 0, g: 0, b: 0, a: rgba.a } : { r: 255, g: 255, b: 255, a: rgba.a }; + second = toHex(mix(rgba, target, 0.45)); + } else { + second = `color-mix(in srgb, ${base} 55%, white)`; + } + gradient.stops = [{ color: base, position: 0 }, { color: second, position: 100 }]; + return gradient; +} + +export function reverseStops(stops: readonly T[]): T[] { + return sortedStops(stops).reverse().map(stop => ({ ...stop, position: round(100 - stop.position) })); +} diff --git a/frontend/src/features/inspector/controls/gradient.ts b/frontend/src/features/inspector/controls/gradient.ts new file mode 100644 index 00000000..e639eb93 --- /dev/null +++ b/frontend/src/features/inspector/controls/gradient.ts @@ -0,0 +1,510 @@ +import { label, labelAttr, t } from '../../../i18n'; +import { element, keyed } from '../../../ui/dom'; +import { icon } from '../../../ui/icons'; +import { registerPickerTab, type ColorArea, type PickerApi } from './picker-api'; +import type { ColorToken } from './types'; +import { + colorAt, isColor, normaliseAngle, parseGradient, reverseStops, round, serializeGradient, sortedStops, starterGradient, stopList, toRgba, + type Gradient, type GradientStop, type RadialShape, +} from './gradient-model'; +import '../../../styles/control-gradient.css'; + +interface TabStop extends GradientStop { id: number } +interface TabGradient extends Gradient { stops: TabStop[] } + +const DIRECTIONS: readonly (readonly [number, string])[] = [ + [0, 'Up'], [45, 'Up right'], [90, 'Right'], [135, 'Down right'], [180, 'Down'], [225, 'Down left'], [270, 'Left'], [315, 'Up left'], +]; +const SIDE_ANGLE: Record = { top: 0, 'top right': 45, right: 90, 'bottom right': 135, bottom: 180, 'bottom left': 225, left: 270, 'top left': 315 }; +const MOVE_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End']); +const TOKEN = /var\(\s*(--[\w-]+)\s*(?:,\s*([^()]*(?:\([^()]*\)[^()]*)*))?\)/; + +function set(node: Element, name: string, next: string): void { + if (node.getAttribute(name) !== next) node.setAttribute(name, next); +} + +function style(node: HTMLElement, name: string, next: string): void { + if (node.style.getPropertyValue(name) !== next) node.style.setProperty(name, next); +} + +function paint(color: string, tokens: readonly ColorToken[]): string { + let text = color; + for (let i = 0; i < 8 && TOKEN.test(text); i++) { + text = text.replace(TOKEN, (_whole, name: string, fallback?: string) => { + const token = tokens.find(item => item.css.replace(/\s+/g, '') === `var(${name})`); + return token?.value.trim() || (fallback ?? '').trim() || 'transparent'; + }); + } + return text; +} + +function button(className: string, english: string): HTMLButtonElement { + const node = element('button', className); + node.type = 'button'; + label(node, english); + return node; +} + +function iconButton(className: string, name: 'plus' | 'trash' | 'arrow', english: string): HTMLButtonElement { + const node = element('button', className); + node.type = 'button'; + node.append(icon(name)); + labelAttr(node, 'aria-label', english); + labelAttr(node, 'title', english); + return node; +} + +function numberEntry(className: string, english: string, min: number, max: number): HTMLInputElement { + const node = element('input', className); + node.type = 'number'; + node.min = String(min); + node.max = String(max); + node.step = '1'; + node.inputMode = 'decimal'; + labelAttr(node, 'aria-label', english); + return node; +} + +function mount(panel: HTMLElement, api: PickerApi): { open(value: string): boolean; close(): void } { + let model: TabGradient | null = null; + let selected = 0; + let nextId = 1; + let proposal = false; + let held = false; + let areaStart: string | null = null; + const flight: string[] = []; + let drag: { id: number; snapshot: TabGradient; moved: boolean; pointer: number; startX: number } | null = null; + + const root = element('div', 'fw-grad'); + root.dataset.ownKeys = ''; + + const kinds = element('div', 'fw-grad-kinds'); + set(kinds, 'role', 'group'); + labelAttr(kinds, 'aria-label', 'Gradient type'); + const linear = button('fw-grad-choice', 'Linear'); + const radial = button('fw-grad-choice', 'Radial'); + kinds.append(linear, radial); + + const bar = element('div', 'fw-grad-bar'); + const fill = element('span', 'fw-grad-fill'); + const track = element('div', 'fw-grad-track'); + set(track, 'role', 'group'); + labelAttr(track, 'aria-label', 'Gradient stops'); + labelAttr(bar, 'title', 'Click to add a stop'); + bar.append(fill, track); + + const stopRow = element('div', 'fw-grad-row'); + const positionLabel = element('label', 'fw-grad-label'); + label(positionLabel, 'Position'); + const position = numberEntry('fw-grad-number', 'Stop position in percent', 0, 100); + const percent = element('span', 'fw-grad-unit', '%'); + const add = iconButton('fw-grad-icon', 'plus', 'Add stop'); + const remove = iconButton('fw-grad-icon', 'trash', 'Remove stop'); + positionLabel.append(position); + stopRow.append(positionLabel, percent, element('span', 'fw-grad-spacer'), add, remove); + + const area: ColorArea = api.colorArea({ + label: 'Stop color', + input(color) { const stop = current(); if (!stop) return; areaStart ??= stop.color; stop.color = color; pending(); }, + commit(color) { const stop = current(); areaStart = null; if (!stop) return; stop.color = color; save(); }, + }); + area.element.classList.add('fw-grad-area'); + + const shapeBox = element('div', 'fw-grad-shape'); + const angleGroup = element('div', 'fw-grad-angle'); + const angleRow = element('div', 'fw-grad-row'); + const angleLabel = element('label', 'fw-grad-label'); + label(angleLabel, 'Angle'); + const angle = numberEntry('fw-grad-number', 'Angle in degrees', 0, 360); + angleLabel.append(angle); + angleRow.append(angleLabel, element('span', 'fw-grad-unit', 'deg')); + const directions = element('div', 'fw-grad-directions'); + set(directions, 'role', 'group'); + labelAttr(directions, 'aria-label', 'Direction'); + const directionButtons = DIRECTIONS.map(([degrees, name]) => { + const node = iconButton('fw-grad-icon fw-grad-direction', 'arrow', name); + node.style.setProperty('--fw-grad-turn', `${degrees - 90}deg`); + node.addEventListener('click', () => { + if (!model) return; + model.angle = degrees; + model.to = ''; + save(); + }); + directions.append(node); + return node; + }); + angleGroup.append(angleRow, directions); + const radialGroup = element('div', 'fw-grad-radial'); + const shapeRow = element('div', 'fw-grad-row'); + const shapeLabel = element('span', 'fw-grad-label'); + label(shapeLabel, 'Shape'); + const shapes = element('div', 'fw-grad-kinds'); + set(shapes, 'role', 'group'); + labelAttr(shapes, 'aria-label', 'Shape'); + const circle = button('fw-grad-choice', 'Circle'); + const ellipse = button('fw-grad-choice', 'Ellipse'); + shapes.append(circle, ellipse); + shapeRow.append(shapeLabel, shapes); + radialGroup.append(shapeRow); + shapeBox.append(angleGroup, radialGroup); + + const actions = element('div', 'fw-grad-row fw-grad-actions'); + const reverse = button('fw-grad-action', 'Reverse'); + const use = button('fw-grad-action fw-grad-use', 'Use gradient'); + actions.append(reverse, element('span', 'fw-grad-spacer'), use); + + root.append(kinds, bar, stopRow, area.element, shapeBox, actions); + panel.append(root); + + const ordered = (): TabStop[] => model ? sortedStops(model.stops) : []; + const shade = (color: string): string => { + if (!/var\(/i.test(color)) return color; + const found = api.resolve(color); + return found ? `rgba(${Math.round(found.r)}, ${Math.round(found.g)}, ${Math.round(found.b)}, ${round(found.a)})` : paint(color, api.colors()); + }; + const current = (): TabStop | undefined => model?.stops.find(stop => stop.id === selected); + const css = (): string => model ? serializeGradient(model) : ''; + const clone = (from: TabGradient): TabGradient => ({ ...from, stops: from.stops.map(stop => ({ ...stop })) }); + const adopt = (gradient: Gradient): TabGradient => { + const ids = ordered().map(stop => stop.id); + return { ...gradient, stops: gradient.stops.map((stop, i) => ({ ...stop, id: ids[i] ?? nextId++ })) }; + }; + + function render(): void { + if (!model) return; + const stops = ordered(); + const kind = model.kind; + set(linear, 'aria-pressed', String(kind === 'linear')); + set(radial, 'aria-pressed', String(kind === 'radial')); + style(fill, 'background-image', `linear-gradient(to right, ${stopList(stops.map(stop => ({ color: shade(stop.color), position: stop.position })))})`); + const lasting = [...model.stops].sort((a, b) => a.id - b.id); + const live = new Set(lasting.map(stop => String(stop.id))); + const gone = (Array.from(track.children) as HTMLElement[]).filter(node => !live.has(node.dataset.key ?? '')); + if (gone.some(node => node.contains(document.activeElement))) rescue(live); + for (const node of gone) node.remove(); + keyed(track, lasting, stop => String(stop.id), () => { + const handle = element('div', 'fw-grad-handle'); + handle.tabIndex = 0; + set(handle, 'role', 'slider'); + set(handle, 'aria-valuemin', '0'); + set(handle, 'aria-valuemax', '100'); + set(handle, 'aria-orientation', 'horizontal'); + handle.append(element('span', 'fw-grad-chip')); + return handle; + }, (handle, stop) => { + const index = stops.indexOf(stop); + style(handle, 'left', `${stop.position}%`); + style(handle, '--fw-grad-stop', shade(stop.color)); + set(handle, 'aria-valuenow', String(stop.position)); + set(handle, 'aria-valuetext', t('Stop {0} of {1}, {2} percent', [index + 1, stops.length, stop.position])); + labelAttr(handle, 'aria-label', 'Gradient stop {0}', [index + 1]); + handle.classList.toggle('is-selected', stop.id === selected); + }); + const stop = current(); + if (stop && document.activeElement !== position) position.value = String(stop.position); + const fixed = model.stops.length <= 2; + if ((fixed && document.activeElement === remove) || (!proposal && document.activeElement === use)) rescue(live); + remove.disabled = fixed; + const nominal = model.to ? SIDE_ANGLE[model.to] : normaliseAngle(model.angle); + if (document.activeElement !== angle) angle.value = String(nominal); + directionButtons.forEach((node, i) => set(node, 'aria-pressed', String(DIRECTIONS[i][0] === nominal))); + set(circle, 'aria-pressed', String(model.shape === 'circle')); + set(ellipse, 'aria-pressed', String(model.shape === 'ellipse')); + const hiding = kind === 'linear' ? radialGroup : angleGroup; + if (hiding.contains(document.activeElement)) (kind === 'linear' ? linear : radial).focus({ preventScroll: true }); + angleGroup.hidden = kind !== 'linear'; + radialGroup.hidden = kind !== 'radial'; + root.classList.toggle('is-proposal', proposal); + use.disabled = !proposal; + } + + function rescue(live: ReadonlySet): void { + const handles = Array.from(track.children) as HTMLElement[]; + const target = handles.find(node => node.dataset.key === String(selected) && live.has(String(selected))) + ?? handles.find(node => live.has(node.dataset.key ?? '')) + ?? (model?.kind === 'radial' ? radial : linear); + target.focus({ preventScroll: true }); + } + + function leave(): void { + const dialog = panel.parentElement; + if (dialog && root.contains(document.activeElement) && dialog.hasAttribute('tabindex')) dialog.focus({ preventScroll: true }); + } + + function focusSelected(): void { + track.querySelector(`[data-key="${selected}"]`)?.focus({ preventScroll: true }); + } + + function select(id: number): void { + selected = id; + areaStart = null; + const stop = current(); + if (stop) area.set(stop.color); + } + + function pending(): void { + render(); + api.show(css()); + } + + function resync(): void { + const keep = ordered().findIndex(stop => stop.id === selected); + load(api.field().value(), keep); + } + + function save(): void { + if (!model) return; + proposal = false; + render(); + const text = css(); + if (text === api.field().value().trim()) { api.field().restore(); return; } + api.show(text); + flight.push(text); + api.commit(text).catch(resync).finally(() => { flight.splice(flight.indexOf(text), 1); }); + } + + function load(value: string, keepIndex = 0): boolean { + const text = value.trim(); + const parsed = parseGradient(text); + if (parsed) { + const before = model; + model = adopt(parsed); + if (before && parsed.kind === 'radial') { model.angle = before.angle; model.to = before.to; } + if (before && parsed.kind === 'linear') { model.shape = before.shape; model.size = before.size; model.at = before.at; } + proposal = false; + } else if (!text || isColor(text)) { + model = adopt(starterGradient(text || api.field().inherited())); + proposal = true; + } else { + model = null; + return false; + } + const stops = ordered(); + const handleFocused = track.contains(document.activeElement); + select(stops[Math.min(Math.max(keepIndex, 0), stops.length - 1)].id); + if (handleFocused) focusSelected(); + render(); + if (handleFocused && !track.contains(document.activeElement)) focusSelected(); + return true; + } + + function positionAt(clientX: number): number { + const box = track.getBoundingClientRect(); + if (!box.width) return 0; + return Math.round(Math.min(100, Math.max(0, (clientX - box.left) / box.width * 100))); + } + + function newColor(at: number): string { + if (!model) return '#000000'; + const stops = ordered(); + const after = stops.find(stop => stop.position >= at); + const before = [...stops].reverse().find(stop => stop.position <= at); + if (before && after && (before.color.includes('var(') || after.color.includes('var('))) { + return at - before.position <= after.position - at ? before.color : after.color; + } + return colorAt(stops, at, color => toRgba(shade(color))); + } + + function insert(at: number): TabStop | undefined { + if (!model) return undefined; + const stop: TabStop = { id: nextId++, color: newColor(at), position: at }; + model.stops.push(stop); + select(stop.id); + return stop; + } + + function cancel(restore = true): void { + if (!drag) return; + model = drag.snapshot; + if (track.hasPointerCapture(drag.pointer)) track.releasePointerCapture(drag.pointer); + drag = null; + root.classList.remove('is-dragging'); + const kept = model.stops.some(stop => stop.id === selected) ? selected : ordered()[0].id; + select(kept); + if (track.contains(document.activeElement)) focusSelected(); + if (restore) api.field().restore(); + render(); + } + + function finish(): void { + if (!drag) return; + const moved = drag.moved; + drag = null; + root.classList.remove('is-dragging'); + if (moved) save(); + } + + function remover(): void { + if (!model || model.stops.length <= 2) return; + const stops = ordered(); + const index = stops.findIndex(stop => stop.id === selected); + const handleFocused = track.contains(document.activeElement); + model.stops = model.stops.filter(stop => stop.id !== selected); + const rest = ordered(); + select(rest[Math.min(index, rest.length - 1)].id); + if (handleFocused || rest.length <= 2) focusSelected(); + save(); + } + + function begin(event: PointerEvent, id: number, moved: boolean, snapshot: TabGradient): void { + drag = { id, snapshot, moved, pointer: event.pointerId, startX: event.clientX }; + root.classList.add('is-dragging'); + track.setPointerCapture(event.pointerId); + } + + track.addEventListener('pointerdown', event => { + if (!model || event.button !== 0 || drag) return; + event.preventDefault(); + const handle = (event.target as Element).closest('.fw-grad-handle'); + const snapshot = clone(model); + if (handle) { + const id = Number(handle.dataset.key); + select(id); + handle.focus({ preventScroll: true }); + render(); + begin(event, id, false, snapshot); + return; + } + const stop = insert(positionAt(event.clientX)); + if (!stop) return; + begin(event, stop.id, true, snapshot); + pending(); + track.querySelector(`[data-key="${stop.id}"]`)?.focus({ preventScroll: true }); + }); + track.addEventListener('pointermove', event => { + if (!drag || event.pointerId !== drag.pointer || !model) return; + if (!drag.moved && Math.abs(event.clientX - drag.startX) < 3) return; + const stop = model.stops.find(item => item.id === drag?.id); + if (!stop) return; + const at = positionAt(event.clientX); + if (at === stop.position && drag.moved) return; + drag.moved = true; + stop.position = at; + pending(); + }); + track.addEventListener('pointerup', event => { if (drag && event.pointerId === drag.pointer) finish(); }); + track.addEventListener('pointercancel', event => { if (drag && event.pointerId === drag.pointer) cancel(); }); + track.addEventListener('lostpointercapture', event => { if (drag && event.pointerId === drag.pointer) finish(); }); + + track.addEventListener('keydown', event => { + const handle = (event.target as Element).closest('.fw-grad-handle'); + if (!handle || !model || event.ctrlKey || event.metaKey || event.altKey) return; + if (event.key === 'Escape' && drag) { + event.preventDefault(); + event.stopPropagation(); + cancel(); + return; + } + const stop = current(); + if (!stop || Number(handle.dataset.key) !== selected) return; + if (event.key === 'Delete' || event.key === 'Backspace') { + event.preventDefault(); + remover(); + return; + } + if (!MOVE_KEYS.has(event.key)) return; + event.preventDefault(); + const big = event.shiftKey || event.key === 'PageUp' || event.key === 'PageDown' ? 10 : 1; + let next = stop.position; + if (event.key === 'Home') next = 0; + else if (event.key === 'End') next = 100; + else if (event.key === 'ArrowLeft' || event.key === 'ArrowDown' || event.key === 'PageDown') next -= big; + else next += big; + next = round(Math.min(100, Math.max(0, next))); + if (next === stop.position) return; + stop.position = next; + held = true; + pending(); + }); + track.addEventListener('keyup', event => { + if (!held || !MOVE_KEYS.has(event.key)) return; + held = false; + save(); + }); + track.addEventListener('focusin', event => { + const handle = (event.target as Element).closest('.fw-grad-handle'); + const id = Number(handle?.dataset.key); + if (!handle || !model || drag || id === selected || !model.stops.some(stop => stop.id === id)) return; + select(id); + render(); + }); + track.addEventListener('focusout', () => { + if (!held) return; + held = false; + save(); + }); + + root.addEventListener('keydown', event => { + if (event.key !== 'Escape' || drag) return; + if (!area.cancel()) return; + event.preventDefault(); + event.stopPropagation(); + const stop = current(); + if (stop && areaStart !== null) stop.color = areaStart; + areaStart = null; + api.field().restore(); + render(); + }); + + linear.addEventListener('click', () => { if (model && model.kind !== 'linear') { model.kind = 'linear'; save(); } }); + radial.addEventListener('click', () => { if (model && model.kind !== 'radial') { model.kind = 'radial'; save(); } }); + const shape = (value: RadialShape): void => { if (model && model.shape !== value) { model.shape = value; save(); } }; + circle.addEventListener('click', () => shape('circle')); + ellipse.addEventListener('click', () => shape('ellipse')); + add.addEventListener('click', () => { + if (!model) return; + const stops = ordered(); + const index = stops.findIndex(stop => stop.id === selected); + const from = stops[index] ?? stops[0]; + const to = stops[index + 1] ?? stops[index - 1] ?? from; + insert(round(Math.round((from.position + to.position) / 2))); + save(); + }); + remove.addEventListener('click', remover); + reverse.addEventListener('click', () => { + if (!model) return; + model.stops = reverseStops(model.stops); + save(); + }); + use.addEventListener('click', () => { if (proposal) save(); }); + position.addEventListener('change', () => { + const stop = current(); + const value = Number(position.value); + if (!stop || position.value.trim() === '' || !Number.isFinite(value)) { render(); return; } + stop.position = round(Math.min(100, Math.max(0, value))); + save(); + }); + angle.addEventListener('change', () => { + const value = Number(angle.value); + if (!model || angle.value.trim() === '' || !Number.isFinite(value)) { render(); return; } + model.angle = normaliseAngle(value); + model.to = ''; + save(); + }); + + return { + open(value: string): boolean { + if (drag) cancel(); + const same = model && !proposal && (value.trim() === css() || flight.includes(value.trim())); + if (same) { render(); return true; } + const showing = root.getClientRects().length > 0; + if (!load(value, ordered().findIndex(stop => stop.id === selected))) { leave(); return false; } + return !proposal || showing; + }, + close(): void { + leave(); + cancel(false); + held = false; + areaStart = null; + }, + }; +} + +export function register(): void { + registerPickerTab({ + id: 'gradient', + label: 'Gradient', + accepts: key => key === 'background', + mount, + }); +} diff --git a/frontend/src/features/inspector/controls/index.ts b/frontend/src/features/inspector/controls/index.ts index 6d6a55c5..6587a7e3 100644 --- a/frontend/src/features/inspector/controls/index.ts +++ b/frontend/src/features/inspector/controls/index.ts @@ -6,6 +6,7 @@ import { readBrand } from '../../brand-kit'; import type { ColorToken, Control, ControlFactory, ControlHost, ControlKit, StyleField } from './types'; import { register as registerSlider } from './slider'; import { register as registerColor } from './color'; +import { register as registerGradient } from './gradient'; import { register as registerGrid } from './grid'; import '../../../styles/controls.css'; @@ -73,6 +74,7 @@ export function installControls(options: ControlOptions): InstalledKit { installed = true; registerSlider(); registerColor(); + registerGradient(); registerGrid(); } const stored = load(); diff --git a/frontend/src/styles/control-gradient.css b/frontend/src/styles/control-gradient.css new file mode 100644 index 00000000..479bb46f --- /dev/null +++ b/frontend/src/styles/control-gradient.css @@ -0,0 +1,28 @@ +.fw-grad { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--space-2); min-width: 0; } +.fw-grad-row { display: flex; align-items: center; gap: var(--space-2); min-height: var(--ctl-md); } +.fw-grad-spacer { flex: 1; } +.fw-grad-label { display: inline-flex; align-items: center; gap: var(--space-2); color: var(--text-secondary); font-size: var(--fs-11); white-space: nowrap; } +.fw-grad-unit { color: var(--text-muted); font-size: var(--fs-11); } +.fw-grad .fw-grad-number { width: 64px; min-height: var(--ctl-md); padding: 0 var(--space-2); font-variant-numeric: tabular-nums; } +.fw-grad-kinds { display: grid; grid-template-columns: 1fr 1fr; gap: 2px; padding: 2px; border: 1px solid var(--line-1); border-radius: var(--radius); background: var(--surface-field); flex: 1; } +.fw-grad .fw-grad-choice { min-height: var(--ctl-sm); padding: 0 var(--space-2); border-color: transparent; border-radius: var(--radius-sm); background: transparent; color: var(--text-secondary); font-size: var(--fs-11); } +.fw-grad .fw-grad-choice:hover { background: var(--bg-hover); } +.fw-grad .fw-grad-choice[aria-pressed='true'] { background: var(--surface-raised); color: var(--text-primary); } +.fw-grad-bar { position: relative; height: var(--ctl-md); margin: 0 var(--space-2) var(--space-3); border-radius: var(--radius-sm); background-color: var(--cv-checker-a); background-image: conic-gradient(var(--cv-checker-b) 25%, transparent 0 50%, var(--cv-checker-b) 0 75%, transparent 0); background-size: 8px 8px; cursor: copy; } +.fw-grad-fill { position: absolute; inset: 0; border-radius: inherit; box-shadow: inset 0 0 0 1px var(--border-soft); pointer-events: none; } +.fw-grad-track { position: absolute; inset: 0 0 calc(-1 * var(--space-3)); touch-action: none; } +.fw-grad-handle { position: absolute; bottom: 0; width: 14px; height: calc(100% - 4px); margin-left: -7px; border: 2px solid var(--text-primary); border-radius: var(--radius-xs); background-color: var(--cv-checker-a); background-image: conic-gradient(var(--cv-checker-b) 25%, transparent 0 50%, var(--cv-checker-b) 0 75%, transparent 0); background-size: 6px 6px; box-shadow: 0 0 0 1px var(--line-0), var(--shadow-sm); cursor: grab; } +.fw-grad-chip { position: absolute; inset: 0; background: var(--fw-grad-stop, transparent); } +.fw-grad-handle.is-selected { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fw-grad-handle:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 2px; } +.fw-grad.is-dragging .fw-grad-handle, .fw-grad.is-dragging .fw-grad-bar { cursor: grabbing; } +.fw-grad .fw-grad-icon { width: var(--ctl-md); min-height: var(--ctl-md); padding: 0; background: transparent; border-color: transparent; color: var(--text-secondary); } +.fw-grad .fw-grad-icon:hover:not(:disabled) { background: var(--bg-hover); color: var(--text-primary); } +.fw-grad-shape { display: grid; min-height: calc(var(--ctl-md) * 2 + var(--space-2)); align-content: start; } +.fw-grad-angle, .fw-grad-radial { display: grid; gap: var(--space-2); } +.fw-grad-directions { display: grid; grid-template-columns: repeat(8, minmax(0, 1fr)); gap: 2px; } +.fw-grad .fw-grad-direction { width: auto; min-width: 0; min-height: var(--ctl-sm); } +.fw-grad .fw-grad-direction .icon { transform: rotate(var(--fw-grad-turn, 0deg)); } +.fw-grad .fw-grad-direction[aria-pressed='true'] { background: var(--accent-soft); color: var(--accent-text); } +.fw-grad .fw-grad-action { min-height: var(--ctl-md); font-size: var(--fs-11); } +.fw-grad:not(.is-proposal) .fw-grad-use { visibility: hidden; } From 3d2105309fb1f16028fdd2be0cfaf7af17348629 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 01:41:26 -0500 Subject: [PATCH 25/31] docs(hashout): frontend v0.33.0, the control contract and its slots, values in flight and cut-off gestures, the keys a control keeps, fixed slider scales, how colors and gradients are written, the grid chooser, and the path above the canvas --- frontend/HASHOUT_LOG.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 51848a8a..5ebc71ed 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -1,5 +1,35 @@ # Frontend context map +## Controls beside the Design fields: sliders, a color picker with gradients, a grid chooser and the raw CSS switch · v0.33.0 (2026-11-27) + +The second of five releases (0.32.0 to 0.36.0) that answer the follow-up on issue #36. No engine, model or service change: style values stay CSS strings, so an older engine opens the same `.fweb` file. Everything below lives in `features/inspector/controls/`, its stylesheets `styles/controls.css` and `styles/control-{slider,color,gradient,grid}.css`, small wiring in `main.ts`, one rule in `commands/keymap.ts`, and the stage head (`styles/stage-head.css`, `styles/shell.css`, `features/crumbs.ts`). + +The contract (`controls/types.ts`): a control never owns a value. The text input that `addStyle()` makes stays visible and is the one stored value; tokens, `calc()`, anything typed, agents and `[data-style]` tests keep working, and removing a control cannot lose data. A control gets a `StyleField` with three slots, `lead` (inline before the input), `trail` (inline after it) and `below` (a row under it), mounts its elements into them once when it is created and afterwards only changes attributes, classes, text and `hidden`; popovers are created once in `#overlay-root` and shown or hidden. `sync(value, inherited)` is called after every `update()` and on every `input` and `change` of the input, with the input's text rather than the stored value (so a typed, uncommitted value moves the control too), and returns whether the control can show that value; on `false` the kit sets the field's `data-ctl` to `off`, which hides and inerts the slots but keeps their boxes, so a field never changes height. A control must never throw from `sync` or rewrite what was typed. While a gesture runs it calls `field.show(value)` (the input shows the pending value, nothing is sent), on release `field.commit(value)` exactly once, on Escape or a cancelled drag `field.restore()`; one gesture is one `node.update` and one undo step. `commit()` resolves when the engine answers and rejects with the engine's or the editor's sentence; the kit has then already put the input back, written the sentence to the status line and resynced the control, so a control shows no error of its own. + +The kit (`controls/index.ts`): `registerControl(keys, factory)` throws on a second registration of a key; `installControls()` calls the four modules' `register()` once and, for every registered key whose field is a text input, moves the existing input into `span.fw-ctl-row` between `lead` and `trail` (`row.append(lead, input, trail)`, so Tab follows what is drawn), adds `below` after the row, sets `label.htmlFor` to the input (`fw-style-`) and an `aria-label`, and adds the raw switch after the label's Reset. Clicks on anything in a slot that is not a native form control get `preventDefault`, because a `