diff --git a/README.md b/README.md index 77c7951..9ca00f3 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,45 @@ -# emailtemplate +# Mailadmin – Email Template System (R17 modular) +Stand: 2025-08-31 +## Struktur +mailadmin/ + inc/ + config.example.php # Deine echte config.php kommt hierhin (NICHT in public/) + public/ + index.php # Admin UI (helles Design) + api.php # JSON API (Dual-DB + Prefix) + tools/ + config-doctor.php # Prüft inc/config.php + db-doctor.php # Prüft DB-Verbindung + assets/ + css/toast.css + js/ + toast.js + app.js # entry (type=module) + api.js # API wrapper + ui-tabs.js # Tabs + ui-list.js # Liste + Vorschau + Löschen + Editor öffnen + ui-create.js # „Neu …“ dialog + ui-editor.js # Editor-Dialog + Handshake + editor/ + editor-core.php # LÄDT NUR LOKAL (kein CDN) + bridge-core.js + config.js # Bibliothek in Block-Leiste +## Vendor (lokal bereitstellen) +Lege die GrapesJS-Dateien lokal ab (kein CDN): +- mailadmin/public/vendor/grapesjs/grapes.min.css +- mailadmin/public/vendor/grapesjs/grapes.min.js +- mailadmin/public/vendor/grapesjs-preset-newsletter/grapesjs-preset-newsletter.min.js -## Getting started +## Datenbank +Nutze `schema.sql` (inkl. *NULL‑fähiger* Fremdschlüssel & ON DELETE SET NULL). +Prefix standardmäßig: `emailtemplate_`. -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +## Schnellstart +1) `mailadmin/inc/config.php` anlegen (siehe `config.example.php`). +2) `schema.sql` in deiner Templates-Datenbank ausführen. +3) Vendor-Dateien in `public/vendor/...` kopieren. +4) `public/tools/config-doctor.php` & `public/api.php?action=health` prüfen. +5) `public/index.php` öffnen → „Neu …“, „Vorschau“, „Im E‑Mail‑Editor öffnen“ etc. -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://gitlab.int.kusche.berlin/emailtemplate/emailtemplate.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.int.kusche.berlin/emailtemplate/emailtemplate/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..6aba98d --- /dev/null +++ b/README.txt @@ -0,0 +1 @@ +This archive contains the R17 modular Email Template System. Fill inc/config.php and vendor libs. \ No newline at end of file diff --git a/STATE.yaml b/STATE.yaml new file mode 100644 index 0000000..5333cb6 --- /dev/null +++ b/STATE.yaml @@ -0,0 +1,47 @@ +state_version: 1 +project: emailtemplate-suite +snapshot_label: "stand-2025-09-04" +editor: + bridge_core: "bridge-core.js" + grapesjs: "local vendor, no CDN" + blocks: + categories: ["Bausteine","Bibliothek","Bibliothek: Sections","Bibliothek: Blöcke","Default(last, closed)"] + features: + - "Snippets by value (HTML)" + - "Blocks/Sections als Referenzen (data-ref-*)" + - "Quelltext-Button (custom) aktiv" + - "Reload-Bibliothek-Button (Snippets) aktiv" + - "Light UI" +api: + file: "public/api.php" + features: + - "CRUD: templates, sections, blocks, snippets" + - "Items: template_items, section_items (sync)" + - "render: template|section ({{children}})" + - "health, debug=db" + db_profiles: + templates: true + project: optional + table_prefix: "emailtemplate_" +db: + schema_file: "schema.sql" + tables: + - emailtemplate_templates + - emailtemplate_sections + - emailtemplate_blocks + - emailtemplate_snippets + - emailtemplate_template_items + - emailtemplate_section_items +ui: + files: ["public/index.php","public/app.js","public/ui-list.js","public/ui-create.js","public/ui-editor.js"] + vendor: ["public/vendor/grapesjs/","public/vendor/grapesjs-preset-newsletter/"] +tools: + doctor: "public/tools/db-doctor.php" +compat_signature: + api: "ETS-API-2025-09-04" + bridge_core: "ETS-BRIDGE-2025-09-04" +notes: + - "DocumentRoot zeigt auf /public" + - "inc/config.php liegt außerhalb des Webroots" + - "kein Tailwind-CDN in Prod" + diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..82f3e80 --- /dev/null +++ b/composer.json @@ -0,0 +1,6 @@ +{ + "name": "ssh-w020abd8/staging", + "require": { + "tijsverkoyen/css-to-inline-styles": "^2.3" + } +} diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..7564226 --- /dev/null +++ b/composer.lock @@ -0,0 +1,139 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "ce66bd5061d136b6edd6dea47ae9354d", + "packages": [ + { + "name": "symfony/css-selector", + "version": "v7.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/css-selector.git", + "reference": "601a5ce9aaad7bf10797e3663faefce9e26c24e2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/css-selector/zipball/601a5ce9aaad7bf10797e3663faefce9e26c24e2", + "reference": "601a5ce9aaad7bf10797e3663faefce9e26c24e2", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\CssSelector\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Jean-François Simon", + "email": "jeanfrancois.simon@sensiolabs.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Converts CSS selectors to XPath expressions", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/css-selector/tree/v7.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-25T14:21:43+00:00" + }, + { + "name": "tijsverkoyen/css-to-inline-styles", + "version": "v2.3.0", + "source": { + "type": "git", + "url": "https://github.com/tijsverkoyen/CssToInlineStyles.git", + "reference": "0d72ac1c00084279c1816675284073c5a337c20d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/tijsverkoyen/CssToInlineStyles/zipball/0d72ac1c00084279c1816675284073c5a337c20d", + "reference": "0d72ac1c00084279c1816675284073c5a337c20d", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "php": "^7.4 || ^8.0", + "symfony/css-selector": "^5.4 || ^6.0 || ^7.0" + }, + "require-dev": { + "phpstan/phpstan": "^2.0", + "phpstan/phpstan-phpunit": "^2.0", + "phpunit/phpunit": "^8.5.21 || ^9.5.10" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.x-dev" + } + }, + "autoload": { + "psr-4": { + "TijsVerkoyen\\CssToInlineStyles\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Tijs Verkoyen", + "email": "css_to_inline_styles@verkoyen.eu", + "role": "Developer" + } + ], + "description": "CssToInlineStyles is a class that enables you to convert HTML-pages/files into HTML-pages/files with inline styles. This is very useful when you're sending emails.", + "homepage": "https://github.com/tijsverkoyen/CssToInlineStyles", + "support": { + "issues": "https://github.com/tijsverkoyen/CssToInlineStyles/issues", + "source": "https://github.com/tijsverkoyen/CssToInlineStyles/tree/v2.3.0" + }, + "time": "2024-12-21T16:25:41+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": false, + "prefer-lowest": false, + "platform": {}, + "platform-dev": {}, + "plugin-api-version": "2.6.0" +} diff --git a/config/domaindata.php b/config/domaindata.php new file mode 100644 index 0000000..fe8f705 --- /dev/null +++ b/config/domaindata.php @@ -0,0 +1,4 @@ + 0, + 'path' => '/', + 'domain' => APP_COOKIE_DOMAIN ?: '', + 'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'), + 'httponly' => true, + 'samesite' => 'Lax', + ]); + + session_start(); + } +} + + +// ----------------------------------------------------------- +// 2) Persistente Client-ID (für Tracking über Besuche hinweg) +// ----------------------------------------------------------- +if (php_sapi_name() !== 'cli') { + $clientId = $_COOKIE[$clientCookieName] ?? null; + + // Erwartet wird: 64 Hex-Zeichen (32 Bytes) + if ( + !is_string($clientId) || + $clientId === '' || + !preg_match('/^[a-f0-9]{64}$/', $clientId) + ) { + // neue ID erzeugen + try { + $clientId = bin2hex(random_bytes(32)); // 32 bytes → 64 hex + } catch (Throwable $e) { + $clientId = bin2hex(openssl_random_pseudo_bytes(32)); + } + + $cookieOpts = [ + 'expires' => time() + APP_CLIENT_COOKIE_LIFETIME, + 'path' => '/', + 'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'), + 'httponly' => false, // JS darf es lesen, wenn erwünscht + 'samesite' => 'Lax', + ]; + + if (!empty(APP_COOKIE_DOMAIN)) { + $cookieOpts['domain'] = APP_COOKIE_DOMAIN; + } + + setcookie($clientCookieName, $clientId, $cookieOpts); + $_COOKIE[$clientCookieName] = $clientId; + } + + // global verfügbar machen (NEUER NAME!) + $GLOBALS['cookie_client_id'] = $clientId; +} + + +// ----------------------------------------------------------- +// 3) Sprachlogik laden (bleibt sinnvoll zentral) +// ----------------------------------------------------------- +require_once __DIR__ . '/i18n.php'; + + +// ----------------------------------------------------------- +// 4) Rest des Systems laden (DB, Funktionen, Hilfs-Libs) +// ----------------------------------------------------------- +require_once __DIR__ . "/db.php"; +require_once __DIR__ . '/../src/functions.php'; diff --git a/config/i18n.php b/config/i18n.php new file mode 100644 index 0000000..2621bc8 --- /dev/null +++ b/config/i18n.php @@ -0,0 +1,397 @@ + 2) { + $code = substr($code, 0, 2); + } + + if ($code === '') { + return null; + } + + $label = isset($meta['label']) && $meta['label'] !== '' + ? (string)$meta['label'] + : strtoupper($code); + + $flag = isset($meta['flag']) ? (string)$meta['flag'] : ''; + + return [ + 'code' => $code, + 'label' => $label, + 'flag' => $flag, + ]; +} + +/** + * Alle verfügbaren Sprachen aus /public/assets/i18n/*.json ermitteln. + * Verfügbar = JSON mit meta.enabled === true. + * EN wird garantiert hinzugefügt (Fallback), falls nicht gefunden. + */ +function app_i18n_detect_available_languages(): array +{ + $baseDir = realpath(__DIR__ . '/../public/assets/i18n'); + if ($baseDir === false) { + // Wenn gar kein Verzeichnis da ist: minimaler EN-Fallback + return [ + 'en' => [ + 'code' => 'en', + 'label' => 'English', + 'flag' => '', + ], + ]; + } + + $files = glob($baseDir . '/*.json') ?: []; + $langs = []; + + foreach ($files as $file) { + $meta = app_i18n_load_language_meta_from_file($file); + if ($meta === null) { + continue; + } + + $code = $meta['code']; + + // Erste gültige Definition pro Code gewinnt + if (!isset($langs[$code])) { + $langs[$code] = $meta; + } + } + + // EN muss immer vorhanden sein (laut deiner Vorgabe) + if (!isset($langs['en'])) { + // Versuch: gibt es eine en.json, auch wenn enabled=false? + foreach ($files as $file) { + $base = strtolower(basename($file, '.json')); + if ($base === 'en') { + $json = @file_get_contents($file); + $data = json_decode($json, true); + $meta = is_array($data['meta'] ?? null) ? $data['meta'] : []; + + $label = isset($meta['label']) && $meta['label'] !== '' + ? (string)$meta['label'] + : 'English'; + $flag = isset($meta['flag']) ? (string)$meta['flag'] : ''; + + $langs['en'] = [ + 'code' => 'en', + 'label' => $label, + 'flag' => $flag, + ]; + break; + } + } + } + + // Wenn immer noch kein EN → minimaler Stub + if (!isset($langs['en'])) { + $langs['en'] = [ + 'code' => 'en', + 'label' => 'English', + 'flag' => '', + ]; + } + + ksort($langs); + + return $langs; +} + +/** + * Browsersprache aus HTTP_ACCEPT_LANGUAGE extrahieren (2-Buchstaben), + * aber nur, wenn sie in $available existiert. + */ +function app_i18n_detect_browser_lang(array $available): ?string +{ + $header = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? ''; + if ($header === '') { + return null; + } + + $parts = explode(',', $header); + foreach ($parts as $part) { + $part = trim($part); + if ($part === '') { + continue; + } + + $code = strtolower(substr($part, 0, 2)); // "de-DE" → "de" + if (isset($available[$code])) { + return $code; + } + } + + return null; +} + +/** + * Aktuelle Sprache bestimmen: + * 1) ?lang=xx (wenn in $available) + * 2) Browsersprache (wenn in $available) + * 3) Fallback "en" + */ +function app_i18n_resolve_current_lang(array $available): string +{ + // 1) URL-Parameter ?lang=xx + if (!empty($_GET['lang'])) { + $param = strtolower(substr($_GET['lang'], 0, 2)); + if (isset($available[$param])) { + return $param; + } + } + + // 2) Browsersprache + $browser = app_i18n_detect_browser_lang($available); + if ($browser !== null) { + return $browser; + } + + // 3) Standard EN + if (isset($available['en'])) { + return 'en'; + } + + // Sicherheitsfallback: erste verfügbare Sprache + $keys = array_keys($available); + return $keys[0] ?? 'en'; +} + +// ----------------------------------------------------- +// Bootstrap ausführen +// ----------------------------------------------------- + +$availableLangs = app_i18n_detect_available_languages(); +$currentLang = app_i18n_resolve_current_lang($availableLangs); + +// Global bereitstellen +$GLOBALS['availableLangs'] = $availableLangs; +$GLOBALS['lang'] = $currentLang; + +// Optional in Session merken (muss nicht, schadet aber auch nicht) +$_SESSION['lang'] = $currentLang; + +/** + * Frontend-Config für JS (usbConfig.i18n) + * → benutzt direkt die Meta-Daten aus den JSONs (code, label, flag) + */ +function app_i18n_get_frontend_config(): array +{ + return [ + 'current' => $GLOBALS['lang'] ?? 'en', + 'available' => $GLOBALS['availableLangs'] ?? [], + ]; +} + +/** + * Komplette JSON-Struktur für eine Sprache laden. + * Nutzt einfachen Request-Cache, damit pro Sprache nur einmal von Platte gelesen wird. + */ +function app_i18n_load_lang_json(string $lang): array +{ + static $cache = []; + + $lang = strtolower(substr($lang, 0, 5)); + + if (isset($cache[$lang])) { + return $cache[$lang]; + } + + $baseDir = realpath(__DIR__ . '/../public/assets/i18n'); + if ($baseDir === false) { + $cache[$lang] = []; + return $cache[$lang]; + } + + $path = $baseDir . '/' . $lang . '.json'; + if (!is_file($path)) { + // Fallback: en.json, falls vorhanden + $fallback = $baseDir . '/en.json'; + if (is_file($fallback)) { + $json = @file_get_contents($fallback); + $data = json_decode($json, true); + $cache[$lang] = is_array($data) ? $data : []; + return $cache[$lang]; + } + + $cache[$lang] = []; + return $cache[$lang]; + } + + $json = @file_get_contents($path); + $data = json_decode($json, true); + $cache[$lang] = is_array($data) ? $data : []; + + return $cache[$lang]; +} + +/** + * Aus einem Label einen stabilen i18n-Key für Nav-Anker bauen. + * Beispiel: "So funktioniert USBCheck!" -> "nav_so_funktioniert_usbcheck" + */ +function app_i18n_make_anchor_key(string $label): string +{ + // HTML-Entities entfernen (z. B. &) + $decoded = html_entity_decode($label, ENT_QUOTES | ENT_HTML5, 'UTF-8'); + + // Kleinbuchstaben + $decoded = mb_strtolower($decoded, 'UTF-8'); + + // Alles, was kein a-z oder 0-9 ist, durch Unterstrich ersetzen + $key = preg_replace('/[^a-z0-9]+/u', '_', $decoded); + + // Mehrfache Unterstriche trimmen + $key = trim($key, '_'); + + if ($key === '') { + $key = 'item'; + } + + // Prefix, damit klar ist, dass es Navigationskeys sind + return 'nav_' . $key; +} + +/** + * Nav-Anker für eine Seite aus der Sprachdatei holen. + * + * Haupt-Variante im JSON: + * + * "pages": { + * "landing": { + * "anchors": { + * "how": "So funktioniert USBCheck", + * "problem": "Warum gefälschte USB-Sticks gefährlich sind", + * "features": "Funktionen", + * "security": "Sicherheit", + * "faq": "FAQ" + * } + * } + * } + * + * Optional explizit: + * "anchors": { + * "how": { "label": "So funktioniert USBCheck", "i18n": "nav_how" }, + * "faq": { "i18n": "nav_faq" } + * } + * + * Rückgabe-Format: + * [ + * [ 'href' => '#how', 'label' => 'So funktioniert USBCheck', 'i18n' => 'nav_so_funktioniert_usbcheck' ], + * [ 'href' => '#faq', 'label' => '', 'i18n' => 'nav_faq' ], + * ] + */ +function app_get_nav_anchors(string $pageKey): array +{ + $lang = $GLOBALS['lang'] ?? 'en'; + $data = app_i18n_load_lang_json($lang); + + $cfg = $data['pages'][$pageKey]['anchors'] ?? null; + if (!is_array($cfg)) { + return []; + } + + $anchors = []; + + foreach ($cfg as $id => $value) { + $id = trim((string)$id); + if ($id === '') { + continue; + } + + $href = '#' . $id; + $label = ''; + $i18n = ''; + + if (is_string($value)) { + // String IMMER als Label übernehmen + $labelTrim = trim($value); + if ($labelTrim === '') { + continue; + } + + $label = $labelTrim; + // i18n-Key automatisch aus dem Label ableiten + $i18n = app_i18n_make_anchor_key($labelTrim); + + } elseif (is_array($value)) { + // Explizite Variante: + // "how": { "label": "...", "i18n": "nav_how" } + if (!empty($value['label'])) { + $label = trim((string)$value['label']); + } + if (!empty($value['i18n'])) { + $i18n = trim((string)$value['i18n']); + } + + if ($label === '' && $i18n === '') { + continue; + } + + // Wenn Label gesetzt, aber kein i18n: automatisch generieren + if ($label !== '' && $i18n === '') { + $i18n = app_i18n_make_anchor_key($label); + } + } else { + // Weder String noch Array → ignorieren + continue; + } + + $anchors[] = [ + 'href' => $href, + 'label' => $label, + 'i18n' => $i18n, + ]; + } + + return $anchors; +} diff --git a/config/prod/config.php b/config/prod/config.php new file mode 100644 index 0000000..b11bace --- /dev/null +++ b/config/prod/config.php @@ -0,0 +1,34 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, +]; + +try { + $pdo = new PDO( + "mysql:host={$DB_HOST};dbname={$DB_NAME};charset=utf8mb4", + $DB_USER, + $DB_PASS, + $options + ); +} catch (PDOException $e) { + // In Produktion Logging, keine Details ausgeben + http_response_code(500); + echo 'Database connection error.'; + exit; +} diff --git a/config/staging/config.php b/config/staging/config.php new file mode 100644 index 0000000..e2ea33f --- /dev/null +++ b/config/staging/config.php @@ -0,0 +1,36 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, +]; + +try { + $pdo = new PDO( + "mysql:host={$DB_HOST};dbname={$DB_NAME};charset=utf8mb4", + $DB_USER, + $DB_PASS, + $options + ); +} catch (PDOException $e) { + // In Produktion Logging, keine Details ausgeben + http_response_code(500); + echo 'Database connection error.'; + exit; +} diff --git a/inc/ApiKernel (Kopie).php b/inc/ApiKernel (Kopie).php new file mode 100644 index 0000000..79538fd --- /dev/null +++ b/inc/ApiKernel (Kopie).php @@ -0,0 +1,636 @@ +conf = $this->loadConfig(); + $this->cors(); + $this->setInput(); + $this->pdo = $this->getPdoTemplates(); + $this->resolveAction(); + $this->resolveTableMap(); + $this->authService = new AuthService($this->conf, $this->pdo); + } catch (Throwable $e) { + $this->fail('Initialization error', get_class($e) . ': ' . $e->getMessage(), 500); + } + } + + // --- Core Responder-Methoden (Unverändert) --- + + public function respond($data, int $code = 200): void + { + http_response_code($code); + echo is_string($data) ? $data : json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + exit; + } + + public function fail(string $msg, $detail = null, int $code = 400): void + { + $this->respond(['ok' => false, 'error' => $msg, 'detail' => $detail], $code); + } + + // --- Private Initialisierungs- & Utility-Methoden (Unverändert) --- + + private function loadConfig(): array { /* ... Logik bleibt unverändert ... */ + $paths = [ + __DIR__ . '/config.php', + __DIR__ . '/../config.php', + __DIR__ . '/../../config.php', + ]; + + foreach ($paths as $p) { + if (is_file($p)) { + $conf = @include $p; + if (is_array($conf)) return $conf; + } + } + $this->fail('Invalid config.php', 'config.php not found or not returning array', 500); + } + private function cors(): void { /* ... Logik bleibt unverändert ... */ + $cors = $this->conf['cors'] ?? '*'; + if ($cors) { + header('Access-Control-Allow-Origin: ' . $cors); + header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); + header('Access-Control-Allow-Headers: Content-Type, Authorization'); + header('Access-Control-Allow-Credentials: true'); + } + if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') $this->respond(['ok' => true]); + + if (!empty($this->conf['auth']['cookie'])) { + $c = $this->conf['auth']['cookie']; + $params = session_get_cookie_params(); + $params['lifetime'] = $c['lifetime'] ?? $params['lifetime']; + $params['path'] = $c['path'] ?? $params['path']; + $params['domain'] = $c['domain'] ?? $params['domain']; + $params['secure'] = $c['secure'] ?? $params['secure']; + $params['httponly'] = $c['httponly'] ?? $params['httponly']; + if (isset($c['samesite'])) $params['samesite'] = $c['samesite']; + session_set_cookie_params($params); + } + } + private function setInput(): void { /* ... Logik bleibt unverändert ... */ + $data = []; + $ct = $_SERVER['CONTENT_TYPE'] ?? ''; + if (stripos($ct, 'application/json') !== false) { + $raw = file_get_contents('php://input'); + if ($raw !== false && $raw !== '') { + $js = json_decode($raw, true); + if (is_array($js)) $data = $js; + } + } + foreach ($_POST as $k => $v) $data[$k] = $v; + foreach ($_GET as $k => $v) if (!array_key_exists($k, $data)) $data[$k] = $v; + $this->in = $data; + } + private function getPdoTemplates(): PDO { /* ... Logik bleibt unverändert ... */ + if (!isset($this->conf['templates']) || !is_array($this->conf['templates'])) { + $this->fail('Missing templates DB config', null, 500); + } + $c = $this->conf['templates']; + $host = $c['db_host'] ?? 'localhost'; + $db = $c['db_name'] ?? ($c['database'] ?? ''); + $user = $c['db_user'] ?? ($c['username'] ?? ''); + $pass = $c['db_pass'] ?? ($c['password'] ?? ''); + $charset = $c['db_charset'] ?? 'utf8mb4'; + $port = $c['db_port'] ?? 3306; + $dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset"; + $opt = [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ]; + return new PDO($dsn, $user, $pass, $opt); + } + private function resolveAction(): void { /* ... Logik bleibt unverändert ... */ + $action = $this->val($this->in, 'action', ''); + $resource = $this->val($this->in, 'resource', null); + $allowedResources = ['templates', 'sections', 'blocks', 'snippets']; + if ($resource && in_array($resource, $allowedResources, true) && strpos((string)$action, '.') === false) { + $verb = strtolower((string)$action); + if (in_array($verb, ['list', 'get', 'create', 'update', 'delete'], true)) $action = $resource . '.' . $verb; + } + $this->action = $action; + } + private function resolveTableMap(): void { /* ... Logik bleibt unverändert ... */ + $tables = $this->conf['tables'] ?? []; + $this->tableMap = [ + 'templates' => $tables['templates'] ?? 'emailtemplate_templates', + 'sections' => $tables['sections'] ?? 'emailtemplate_sections', + 'blocks' => $tables['blocks'] ?? 'emailtemplate_blocks', + 'snippets' => $tables['snippets'] ?? 'emailtemplate_snippets', + ]; + } + + private function val(array $in, $keys, $default = null) { /* ... Logik bleibt unverändert ... */ + if (!is_array($keys)) $keys = [$keys]; + foreach ($keys as $k) if (array_key_exists($k, $in)) return $in[$k]; + return $default; + } + private function firstExisting(array $columns, array $candidates): ?string { /* ... Logik bleibt unverändert ... */ + foreach ($candidates as $c) if (in_array($c, $columns, true)) return $c; + return null; + } + private function tableColumns(string $table): array { /* ... Logik bleibt unverändert ... */ + $cols = []; + $stmt = $this->pdo->query("SHOW COLUMNS FROM `$table`"); + foreach ($stmt->fetchAll() as $r) $cols[] = $r['Field']; + return $cols; + } + private function primaryKey(string $table): ?string { /* ... Logik bleibt unverändert ... */ + $stmt = $this->pdo->prepare("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'"); + $stmt->execute(); + $row = $stmt->fetch(); + return $row['Column_name'] ?? null; + } + private function requireAuth(): array { /* ... Logik bleibt unverändert ... */ + return $this->authService->requireAuth(); + } + private function pullId(array $src) { /* ... Logik bleibt unverändert ... */ + $aliases = ['id', 'item_id', 'template_id', 'tpl_id', 'section_id', 'sec_id', 'block_id', 'blk_id', 'snippet_id', 'snip_id']; + foreach ($aliases as $a) if (isset($src[$a]) && $src[$a] !== '') return $src[$a]; + return null; + } + private function tenantWhere(array $session): array { /* ... Logik bleibt unverändert ... */ + $multi = $this->conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; + + if (!$tenantCol) return ['', []]; + if (!$session) return [' AND 1=0 ', []]; + $val = $session[$mapSess] ?? null; + if ($val === null || $val === '') return [' AND 1=0 ', []]; + return [" AND `$tenantCol` = :__tenant", [':__tenant' => $val]]; + } + private function tenantAssign(array $session, array $columns): array { /* ... Logik bleibt unverändert ... */ + $multi = $this->conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; + + if (!$tenantCol || !in_array($tenantCol, $columns, true)) return []; + $val = $session[$mapSess] ?? null; + return ($val === null || $val === '') ? [] : [$tenantCol => $val]; + } + private function resolveIdCol(string $kind): array { /* ... Logik bleibt unverändert ... */ + $t = $this->tableMap[$kind]; + $cfg = $this->conf['columns'][$kind] ?? []; + $cols = $this->tableColumns($t); + $idCol = $cfg['id'] ?? ($this->firstExisting($cols, ['id']) ?: $this->primaryKey($t)); + if (!$idCol) $idCol = 'id'; + return [$idCol, $cols]; + } + private function parseHtmlToGjsComponents(string $html): array { /* ... Logik bleibt unverändert ... */ + if (trim($html) === '') return []; + + return [ + [ + 'type' => 'html', + 'content' => $html, + 'removable' => true, + 'draggable' => true, + 'droppable' => true, + 'copyable' => true, + 'selectable' => true, + 'editable' => false, + 'traits' => [], + ] + ]; + } + + // 💡 KORREKTUR: Bereinigungsmethode (von vorheriger Version übernommen) + private function cleanReferenceComponents(array $components): array { + foreach ($components as &$component) { + if (is_array($component) && isset($component['type'])) { + + if ($component['type'] === 'library-reference') { + if (isset($component['content'])) { + $component['content'] = ''; + } + if (isset($component['components'])) { + $component['components'] = []; + } + } + if (isset($component['components']) && is_array($component['components'])) { + $component['components'] = $this->cleanReferenceComponents($component['components']); + } + } + } + return $components; + } + + + // ================================================================= + // 🚀 NEUE CRUD HANDLER METHODEN (Logik aus run() extrahiert) + // ================================================================= + + /** + * Allgemeine Methode zur Handhabung von LIST-Anfragen. + */ + private function handleList(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $cfg = $this->conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? ($this->firstExisting($allCols, ['name']) ?: $idCol); + $descCol = $cfg['desc'] ?? $this->firstExisting($allCols, ['description', 'desc', 'descr']); + $catCol = $cfg['cat'] ?? $this->firstExisting($allCols, ['category', 'cat']); + $updCol = $cfg['upd'] ?? $this->firstExisting($allCols, ['updated_at', 'updated', 'updatedAt']); + $q = trim((string)$this->val($this->in, 'q', '')); + $limit = max(1, (int)$this->val($this->in, 'limit', 500)); + $offset = max(0, (int)$this->val($this->in, 'offset', 0)); + + $where = ' WHERE 1=1 '; + $params = []; + // Suchlogik (q) + if ($q !== '') { + $parts = ["`$nameCol` LIKE :q"]; + if ($descCol) $parts[] = "`$descCol` LIKE :q"; + if ($catCol) $parts[] = "`$catCol` LIKE :q"; + $where .= " AND (" . implode(' OR ', $parts) . ") "; + $params[':q'] = '%' . $q . '%'; + } + + // Filterlogik (parentFilters) + $parentFilters = [ + 'template_id' => $this->val($this->in, ['template_id', 'tpl_id'], null), + 'section_id' => $this->val($this->in, ['section_id', 'sec_id'], null), + 'block_id' => $this->val($this->in, ['block_id', 'blk_id'], null), + ]; + foreach ($parentFilters as $col => $v) { + if ($v === null || $v === '') continue; + if (in_array($col, $allCols, true)) { $where .= " AND `$col` = :$col "; $params[":$col"] = $v; } + } + + // Tenant-Filter + [$tw, $tp] = $this->tenantWhere($auth); + $where .= $tw; + foreach ($tp as $k => $v) $params[$k] = $v; + + $order = $updCol ? " ORDER BY `$updCol` DESC " : " ORDER BY `$nameCol` ASC "; + $sql = "SELECT * FROM `$t` $where $order LIMIT :off,:lim"; + $stmt = $this->pdo->prepare($sql); + + // Bind parameters + foreach ($params as $k => $v) $stmt->bindValue($k, $v, is_int($v) ? PDO::PARAM_INT : PDO::PARAM_STR); + $stmt->bindValue(':off', $offset, PDO::PARAM_INT); + $stmt->bindValue(':lim', $limit, PDO::PARAM_INT); + $stmt->execute(); + $rows = $stmt->fetchAll(); + + $out = []; + foreach ($rows as $r) { + $item = [ + 'id' => $r[$idCol] ?? null, + 'name' => $r[$nameCol] ?? null, + ]; + if ($descCol && isset($r[$descCol])) $item['desc'] = $r[$descCol]; + if ($catCol && isset($r[$catCol])) $item['category'] = $r[$catCol]; + if ($updCol && isset($r[$updCol])) $item['updated_at'] = $r[$updCol]; + + // Lade HTML und JSON aus den korrekten Spalten + $htmlCol = $this->firstExisting($allCols, ['html', 'body', 'markup', 'content']); + if ($htmlCol && isset($r[$htmlCol])) $item['html'] = (string)$r[$htmlCol]; + $jsonCol = $this->firstExisting($allCols, ['json_content']); + if ($jsonCol && isset($r[$jsonCol])) $item['content'] = $r[$jsonCol]; + + $out[] = $item; + } + $this->respond(['ok' => true, 'kind' => $kind, 'items' => $out, 'data' => $out, 'count' => count($out), 'offset' => $offset, 'limit' => $limit]); + } + + /** + * Allgemeine Methode zur Handhabung von GET-Anfragen. + */ + private function handleGet(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $id = $this->pullId($this->in); + if ($id === null || $id === '') $this->fail('id required', null, 422); + + [$tw, $tp] = $this->tenantWhere($auth); + $sql = "SELECT * FROM `$t` WHERE `$idCol` = :id" . $tw . " LIMIT 1"; + $stmt = $this->pdo->prepare($sql); + $stmt->bindValue(':id', $id); + foreach ($tp as $k => $v) $stmt->bindValue($k, $v); + $stmt->execute(); + $row = $stmt->fetch(); + if (!$row) $this->fail('Not found', ['kind' => $kind, 'id' => $id], 404); + $rowOut = ['id' => $row[$idCol] ?? $id] + $row; + + // Lade HTML und JSON aus den korrekten Spalten + $htmlCol = $this->firstExisting($allCols, ['html', 'body', 'markup', 'content']); + $topHtml = ($htmlCol && isset($row[$htmlCol])) ? (string)$row[$htmlCol] : null; + $jsonCol = $this->firstExisting($allCols, ['json_content']); + $topContent = ($jsonCol && isset($row[$jsonCol])) ? $row[$jsonCol] : null; + + $gjsComponents = []; + + if ($topContent !== null) { + $decodedContent = json_decode($topContent, true); + if (is_array($decodedContent)) { + $gjsComponents = $decodedContent; + } + } + + if (empty($gjsComponents) && $topHtml !== null) { + $gjsComponents = $this->parseHtmlToGjsComponents($topHtml); + } + + $this->respond([ + 'ok' => true, + 'kind' => $kind, + 'id' => $rowOut['id'], + 'item' => $rowOut, + 'data' => $rowOut, + 'html' => $topHtml, + 'content' => $topContent, + 'gjs_components' => $gjsComponents + ]); + } + + /** + * Allgemeine Methode zur Handhabung von CREATE-Anfragen (inkl. JSON-Bereinigung). + */ + private function handleCreate(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $cfg = $this->conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? ($this->firstExisting($allCols, ['name']) ?: $idCol); + $descCol = $cfg['desc'] ?? $this->firstExisting($allCols, ['description', 'desc', 'descr']); + $catCol = $cfg['cat'] ?? $this->firstExisting($allCols, ['category', 'cat']); + $updCol = $cfg['upd'] ?? $this->firstExisting($allCols, ['updated_at', 'updated', 'updatedAt']); + + $name = trim((string)$this->val($this->in, ['name', 'title'], '')); + if ($name === '') $this->fail('name required', null, 422); + + $desc = (string)$this->val($this->in, ['description', 'desc'], null); + $cat = (string)$this->val($this->in, ['category', 'cat'], null); + $html = (string)$this->val($this->in, ['html', 'body', 'markup'], null); + $json = $this->val($this->in, ['content_json', 'json', 'content', 'structure_json'], null); + $settings = $this->val($this->in, ['settings_json', 'settings'], null); + $templateId = $this->val($this->in, ['template_id', 'tpl_id'], null); + $sectionId = $this->val($this->in, ['section_id', 'sec_id'], null); + $blockId = $this->val($this->in, ['block_id', 'blk_id'], null); + + $data = [$nameCol => $name]; + if ($desc !== null && $descCol) $data[$descCol] = $desc; + if ($cat !== null && $catCol) $data[$catCol] = $cat; + + $htmlDbCol = $this->firstExisting($allCols, ($kind === 'snippets' ? ['content'] : ['html', 'body', 'markup'])); + $jsonDbCol = $this->firstExisting($allCols, ['json_content']); + + // --- LOGIK mit ERWEITERTER PRÜFUNG START --- + + // 1. JSON-Content behandeln + if ($json !== null) { + if ($jsonDbCol) { + $components = is_string($json) ? json_decode($json, true) : $json; + if (is_array($components)) { + $components = $this->cleanReferenceComponents($components); // BEREINIGUNG + $data[$jsonDbCol] = json_encode($components, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } else { + $data[$jsonDbCol] = is_string($json) ? $json : ''; + } + } else { + // FALLBACK: Wenn JSON gesendet wurde, aber keine json_content Spalte existiert, FEHLER ausgeben + $this->fail( + 'JSON content provided but no `json_content` column found', + ['table' => $t, 'available_cols' => $allCols], + 422 + ); + } + } + + // 2. HTML-Content speichern + if ($htmlDbCol && $html !== null) { + $data[$htmlDbCol] = $html; + } + // --- LOGIK mit ERWEITERTER PRÜFUNG ENDE --- + + $c = $this->firstExisting($allCols, ['settings_json', 'settings']); + if ($c && $settings !== null) $data[$c] = is_string($settings) ? $settings : json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + if ($templateId !== null && in_array('template_id', $allCols, true)) $data['template_id'] = $templateId; + if ($sectionId !== null && in_array('section_id', $allCols, true)) $data['section_id'] = $sectionId; + if ($blockId !== null && in_array('block_id', $allCols, true)) $data['block_id'] = $blockId; + + $data = $data + $this->tenantAssign($_SESSION['auth'] ?? [], $allCols); + + $now = date('Y-m-d H:i:s'); + $createdCol = $this->firstExisting($allCols, ['created_at', 'created', 'createdAt']); + if ($createdCol) $data[$createdCol] = $now; + if ($updCol) $data[$updCol] = $now; + + $fields = array_keys($data); + $place = array_map(fn($c) => ":$c", $fields); + $sql = "INSERT INTO `$t` (" . implode(',', array_map(fn($c) => "`$c`", $fields)) . ") VALUES (" . implode(',', $place) . ")"; + $stmt = $this->pdo->prepare($sql); + foreach ($data as $k => $v) $stmt->bindValue(":$k", $v); + $stmt->execute(); + $newId = $this->pdo->lastInsertId(); + + $out = ['id' => $newId, 'name' => $name]; + if ($desc !== null) $out['desc'] = $desc; + if ($cat !== null) $out['category'] = $cat; + $this->respond(['ok' => true, 'kind' => $kind, 'id' => $newId, 'item' => $out, 'data' => $out]); + } + + /** + * Allgemeine Methode zur Handhabung von UPDATE-Anfragen (inkl. JSON-Bereinigung). + */ + private function handleUpdate(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $cfg = $this->conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? ($this->firstExisting($allCols, ['name']) ?: $idCol); + $descCol = $cfg['desc'] ?? $this->firstExisting($allCols, ['description', 'desc', 'descr']); + $catCol = $cfg['cat'] ?? $this->firstExisting($allCols, ['category', 'cat']); + $updCol = $cfg['upd'] ?? $this->firstExisting($allCols, ['updated_at', 'updated', 'updatedAt']); + $id = $this->pullId($this->in); + if ($id === null || $id === '') $this->fail('id required', null, 422); + + $data = []; + $name = $this->val($this->in, ['name', 'title'], null); + $desc = $this->val($this->in, ['description', 'desc'], null); + $cat = $this->val($this->in, ['category', 'cat'], null); + $html = $this->val($this->in, ['html', 'body', 'markup'], null); + $json = $this->val($this->in, ['content_json', 'json', 'content', 'structure_json'], null); + $settings = $this->val($this->in, ['settings_json', 'settings'], null); + + if ($name !== null) $data[$nameCol] = (string)$name; + if ($desc !== null && $descCol) $data[$descCol] = (string)$desc; + if ($cat !== null && $catCol) $data[$catCol] = (string)$cat; + + $htmlDbCol = $this->firstExisting($allCols, ($kind === 'snippets' ? ['content'] : ['html', 'body', 'markup'])); + $jsonDbCol = $this->firstExisting($allCols, ['json_content']); + + // --- LOGIK mit ERWEITERTER PRÜFUNG START --- + + // 1. JSON-Content behandeln + if ($json !== null) { + if ($jsonDbCol) { + // Wenn JSON-Spalte existiert, JSON verarbeiten und speichern + $components = is_string($json) ? json_decode($json, true) : $json; + if (is_array($components)) { + $components = $this->cleanReferenceComponents($components); // BEREINIGUNG + $data[$jsonDbCol] = json_encode($components, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } else { + $data[$jsonDbCol] = is_string($json) ? $json : ''; + } + } else { + // FALLBACK: Wenn JSON gesendet wurde, aber keine json_content Spalte existiert, FEHLER ausgeben + $this->fail( + 'JSON content provided but no `json_content` column found', + ['table' => $t, 'available_cols' => $allCols], + 422 + ); + } + + // 2. Den zugehörigen HTML-Output speichern (wird vom Editor immer mitgesendet, wenn JSON da ist) + if ($html !== null && $htmlDbCol) { + $data[$htmlDbCol] = (string)$html; + } + } elseif ($html !== null && $htmlDbCol) { + // Wenn NUR HTML gesendet wird (für minimale Änderungen), speichern wir nur HTML. + $data[$htmlDbCol] = (string)$html; + } + // --- LOGIK mit ERWEITERTER PRÜFUNG ENDE --- + + $c = $this->firstExisting($allCols, ['settings_json', 'settings']); + if ($settings !== null && $c) $data[$c] = is_string($settings) ? $settings : json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + $tpl = $this->val($this->in, ['template_id', 'tpl_id'], null); + if ($tpl !== null && in_array('template_id', $allCols, true)) $data['template_id'] = $tpl; + $sec = $this->val($this->in, ['section_id', 'sec_id'], null); + if ($sec !== null && in_array('section_id', $allCols, true)) $data['section_id'] = $sec; + $blk = $this->val($this->in, ['block_id', 'blk_id'], null); + if ($blk !== null && in_array('block_id', $allCols, true)) $data['block_id'] = $blk; + + if ($updCol) $data[$updCol] = date('Y-m-d H:i:s'); + if (!$data) $this->fail('nothing to update', null, 422); + + [$tw, $tp] = $this->tenantWhere($auth); + $set = []; + foreach (array_keys($data) as $c) $set[] = "`$c` = :$c"; + $sql = "UPDATE `$t` SET " . implode(',', $set) . " WHERE `$idCol` = :__id" . $tw . " LIMIT 1"; + $stmt = $this->pdo->prepare($sql); + + foreach ($data as $k => $v) $stmt->bindValue(":$k", $v); + $stmt->bindValue(':__id', $id); + foreach ($tp as $k => $v) $stmt->bindValue($k, $v); + $stmt->execute(); + $this->respond(['ok' => true, 'kind' => $kind, 'id' => $id, 'updated' => array_keys($data)]); + } + + /** + * Allgemeine Methode zur Handhabung von DELETE-Anfragen. + */ + private function handleDelete(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $id = $this->pullId($this->in); + if ($id === null || $id === '') $this->fail('id required', null, 422); + + [$tw, $tp] = $this->tenantWhere($auth); + $sql = "DELETE FROM `$t` WHERE `$idCol` = :__id" . $tw . " LIMIT 1"; + $stmt = $this->pdo->prepare($sql); + $stmt->bindValue(':__id', $id); + foreach ($tp as $k => $v) $stmt->bindValue($k, $v); + $stmt->execute(); + $this->respond(['ok' => true, 'kind' => $kind, 'id' => $id, 'deleted' => true]); + } + + // ================================================================= + // 💡 Öffentliche run()-Methode (DEUTLICH VEREINFACHT) + // ================================================================= + + public function run(): void + { + header('Content-Type: application/json; charset=utf-8'); + + try { + // Extrahiere den Ressourcen-Typ und die Operation (z.B. 'templates' und 'list') + [$kind, $operation] = explode('.', $this->action, 2) + [1 => '']; + + switch ($this->action) { + case 'health': + $this->respond(['ok' => true, 'time' => date('c')]); + + /* ---------- AUTH ---------- */ + case 'auth.login': + $result = $this->authService->login($this->in); + $this->respond(['ok' => true] + $result); + break; + case 'auth.me': + if (empty($_SESSION['auth'])) $this->fail('Not authenticated', null, 401); + $this->respond(['ok' => true, 'user' => $_SESSION['auth']]); + break; + case 'auth.logout': + $this->authService->logout(); + $this->respond(['ok' => true]); + break; + + /* ---------- CRUD HANDLER ---------- */ + default: + if (in_array($kind, ['templates', 'sections', 'blocks', 'snippets'])) { + switch ($operation) { + case 'list': + $this->handleList($kind); + break; + case 'get': + $this->handleGet($kind); + break; + case 'create': + $this->handleCreate($kind); + break; + case 'update': + $this->handleUpdate($kind); + break; + case 'delete': + $this->handleDelete($kind); + break; + default: + $this->fail('Unknown operation for resource: ' . $this->action, null, 404); + break; + } + } else { + $this->fail('Unknown action', $this->action ?: 'missing', 404); + } + break; + } + } catch (Throwable $e) { + $this->fail('Server error', get_class($e) . ': ' . $e->getMessage(), 500); + } + } +} diff --git a/inc/ApiKernel.php b/inc/ApiKernel.php new file mode 100644 index 0000000..26cc516 --- /dev/null +++ b/inc/ApiKernel.php @@ -0,0 +1,657 @@ +conf = $this->loadConfig(); + $this->cors(); + $this->setInput(); + $this->pdo = $this->getPdoTemplates(); + $this->resolveAction(); + $this->resolveTableMap(); + $this->authService = new AuthService($this->conf, $this->pdo); + } catch (Throwable $e) { + // Im Fehlerfall ruft fail() die respond() Methode auf, die den Header setzt und den Buffer leert. + $this->fail('Initialization error', get_class($e) . ': ' . $e->getMessage(), 500); + } + } + + // --- Core Responder-Methoden (KORRIGIERT) --- + + public function respond($data, int $code = 200): void + { + // 1. Output-Puffer leeren, um jeglichen unbeabsichtigten Output zu verwerfen (z.B. PHP Notices). + if (ob_get_level() > 0) { + ob_clean(); + } + + // 2. 💡 KRITISCHE KORREKTUR: Content-Type Header setzen. + // Dies ist der entscheidende Schritt, der dem Browser sagt: "Dies ist JSON!" + if (!headers_sent() && !isset($this->conf['no_content_type'])) { + header('Content-Type: application/json; charset=utf-8'); + } + + http_response_code($code); + echo is_string($data) ? $data : json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + exit; + } + + public function fail(string $msg, $detail = null, int $code = 400): void + { + $this->respond(['ok' => false, 'error' => $msg, 'detail' => $detail], $code); + } + + // --- Private Initialisierungs- & Utility-Methoden (Unverändert) --- + + private function loadConfig(): array { /* ... Logik bleibt unverändert ... */ + $paths = [ + __DIR__ . '/config.php', + __DIR__ . '/../config.php', + __DIR__ . '/../../config.php', + ]; + + foreach ($paths as $p) { + if (is_file($p)) { + $conf = @include $p; + if (is_array($conf)) return $conf; + } + } + $this->fail('Invalid config.php', 'config.php not found or not returning array', 500); + } + private function cors(): void { /* ... Logik bleibt unverändert ... */ + $cors = $this->conf['cors'] ?? '*'; + if ($cors) { + header('Access-Control-Allow-Origin: ' . $cors); + header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); + header('Access-Control-Allow-Headers: Content-Type, Authorization'); + header('Access-Control-Allow-Credentials: true'); + } + if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') $this->respond(['ok' => true]); + + if (!empty($this->conf['auth']['cookie'])) { + $c = $this->conf['auth']['cookie']; + $params = session_get_cookie_params(); + $params['lifetime'] = $c['lifetime'] ?? $params['lifetime']; + $params['path'] = $c['path'] ?? $params['path']; + $params['domain'] = $c['domain'] ?? $params['domain']; + $params['secure'] = $c['secure'] ?? $params['secure']; + $params['httponly'] = $c['httponly'] ?? $params['httponly']; + if (isset($c['samesite'])) $params['samesite'] = $c['samesite']; + session_set_cookie_params($params); + } + } + private function setInput(): void { /* ... Logik bleibt unverändert ... */ + $data = []; + $ct = $_SERVER['CONTENT_TYPE'] ?? ''; + if (stripos($ct, 'application/json') !== false) { + $raw = file_get_contents('php://input'); + if ($raw !== false && $raw !== '') { + $js = json_decode($raw, true); + if (is_array($js)) $data = $js; + } + } + foreach ($_POST as $k => $v) $data[$k] = $v; + foreach ($_GET as $k => $v) if (!array_key_exists($k, $data)) $data[$k] = $v; + $this->in = $data; + } + private function getPdoTemplates(): PDO { /* ... Logik bleibt unverändert ... */ + if (!isset($this->conf['templates']) || !is_array($this->conf['templates'])) { + $this->fail('Missing templates DB config', null, 500); + } + $c = $this->conf['templates']; + $host = $c['db_host'] ?? 'localhost'; + $db = $c['db_name'] ?? ($c['database'] ?? ''); + $user = $c['db_user'] ?? ($c['username'] ?? ''); + $pass = $c['db_pass'] ?? ($c['password'] ?? ''); + $charset = $c['db_charset'] ?? 'utf8mb4'; + $port = $c['db_port'] ?? 3306; + $dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset"; + $opt = [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ]; + return new PDO($dsn, $user, $pass, $opt); + } + private function resolveAction(): void { /* ... Logik bleibt unverändert ... */ + $action = $this->val($this->in, 'action', ''); + $resource = $this->val($this->in, 'resource', null); + $allowedResources = ['templates', 'sections', 'blocks', 'snippets']; + if ($resource && in_array($resource, $allowedResources, true) && strpos((string)$action, '.') === false) { + $verb = strtolower((string)$action); + if (in_array($verb, ['list', 'get', 'create', 'update', 'delete'], true)) $action = $resource . '.' . $verb; + } + $this->action = $action; + } + private function resolveTableMap(): void { /* ... Logik bleibt unverändert ... */ + $tables = $this->conf['tables'] ?? []; + $this->tableMap = [ + 'templates' => $tables['templates'] ?? 'emailtemplate_templates', + 'sections' => $tables['sections'] ?? 'emailtemplate_sections', + 'blocks' => $tables['blocks'] ?? 'emailtemplate_blocks', + 'snippets' => $tables['snippets'] ?? 'emailtemplate_snippets', + ]; + } + + private function val(array $in, $keys, $default = null) { /* ... Logik bleibt unverändert ... */ + if (!is_array($keys)) $keys = [$keys]; + foreach ($keys as $k) if (array_key_exists($k, $in)) return $in[$k]; + return $default; + } + private function firstExisting(array $columns, array $candidates): ?string { /* ... Logik bleibt unverändert ... */ + foreach ($candidates as $c) if (in_array($c, $columns, true)) return $c; + return null; + } + private function tableColumns(string $table): array { /* ... Logik bleibt unverändert ... */ + $cols = []; + $stmt = $this->pdo->query("SHOW COLUMNS FROM `$table`"); + foreach ($stmt->fetchAll() as $r) $cols[] = $r['Field']; + return $cols; + } + private function primaryKey(string $table): ?string { /* ... Logik bleibt unverändert ... */ + $stmt = $this->pdo->prepare("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'"); + $stmt->execute(); + $row = $stmt->fetch(); + return $row['Column_name'] ?? null; + } + private function requireAuth(): array { /* ... Logik bleibt unverändert ... */ + return $this->authService->requireAuth(); + } + private function pullId(array $src) { /* ... Logik bleibt unverändert ... */ + $aliases = ['id', 'item_id', 'template_id', 'tpl_id', 'section_id', 'sec_id', 'block_id', 'blk_id', 'snippet_id', 'snip_id']; + foreach ($aliases as $a) if (isset($src[$a]) && $src[$a] !== '') return $src[$a]; + return null; + } + private function tenantWhere(array $session): array { /* ... Logik bleibt unverändert ... */ + $multi = $this->conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; + + if (!$tenantCol) return ['', []]; + if (!$session) return [' AND 1=0 ', []]; + $val = $session[$mapSess] ?? null; + if ($val === null || $val === '') return [' AND 1=0 ', []]; + return [" AND `$tenantCol` = :__tenant", [':__tenant' => $val]]; + } + private function tenantAssign(array $session, array $columns): array { /* ... Logik bleibt unverändert ... */ + $multi = $this->conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; + + if (!$tenantCol || !in_array($tenantCol, $columns, true)) return []; + $val = $session[$mapSess] ?? null; + return ($val === null || $val === '') ? [] : [$tenantCol => $val]; + } + private function resolveIdCol(string $kind): array { /* ... Logik bleibt unverändert ... */ + $t = $this->tableMap[$kind]; + $cfg = $this->conf['columns'][$kind] ?? []; + $cols = $this->tableColumns($t); + $idCol = $cfg['id'] ?? ($this->firstExisting($cols, ['id']) ?: $this->primaryKey($t)); + if (!$idCol) $idCol = 'id'; + return [$idCol, $cols]; + } + private function parseHtmlToGjsComponents(string $html): array { /* ... Logik bleibt unverändert ... */ + if (trim($html) === '') return []; + + return [ + [ + 'type' => 'html', + 'content' => $html, + 'removable' => true, + 'draggable' => true, + 'droppable' => true, + 'copyable' => true, + 'selectable' => true, + 'editable' => false, + 'traits' => [], + ] + ]; + } + + // 💡 Bereinigungsmethode + private function cleanReferenceComponents(array $components): array { + foreach ($components as &$component) { + if (is_array($component) && isset($component['type'])) { + + if ($component['type'] === 'library-reference') { + if (isset($component['content'])) { + $component['content'] = ''; + } + if (isset($component['components'])) { + $component['components'] = []; + } + } + if (isset($component['components']) && is_array($component['components'])) { + $component['components'] = $this->cleanReferenceComponents($component['components']); + } + } + } + return $components; + } + + + // ================================================================= + // 🚀 CRUD HANDLER METHODEN + // ================================================================= + + /** + * Allgemeine Methode zur Handhabung von LIST-Anfragen. + */ + private function handleList(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $cfg = $this->conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? ($this->firstExisting($allCols, ['name']) ?: $idCol); + $descCol = $cfg['desc'] ?? $this->firstExisting($allCols, ['description', 'desc', 'descr']); + $catCol = $cfg['cat'] ?? $this->firstExisting($allCols, ['category', 'cat']); + $updCol = $cfg['upd'] ?? $this->firstExisting($allCols, ['updated_at', 'updated', 'updatedAt']); + $q = trim((string)$this->val($this->in, 'q', '')); + $limit = max(1, (int)$this->val($this->in, 'limit', 500)); + $offset = max(0, (int)$this->val($this->in, 'offset', 0)); + + $where = ' WHERE 1=1 '; + $params = []; + // Suchlogik (q) + if ($q !== '') { + $parts = ["`$nameCol` LIKE :q"]; + if ($descCol) $parts[] = "`$descCol` LIKE :q"; + if ($catCol) $parts[] = "`$catCol` LIKE :q"; + $where .= " AND (" . implode(' OR ', $parts) . ") "; + $params[':q'] = '%' . $q . '%'; + } + + // Filterlogik (parentFilters) + $parentFilters = [ + 'template_id' => $this->val($this->in, ['template_id', 'tpl_id'], null), + 'section_id' => $this->val($this->in, ['section_id', 'sec_id'], null), + 'block_id' => $this->val($this->in, ['block_id', 'blk_id'], null), + ]; + foreach ($parentFilters as $col => $v) { + if ($v === null || $v === '') continue; + if (in_array($col, $allCols, true)) { $where .= " AND `$col` = :$col "; $params[":$col"] = $v; } + } + + // Tenant-Filter + [$tw, $tp] = $this->tenantWhere($auth); + $where .= $tw; + foreach ($tp as $k => $v) $params[$k] = $v; + + $order = $updCol ? " ORDER BY `$updCol` DESC " : " ORDER BY `$nameCol` ASC "; + $sql = "SELECT * FROM `$t` $where $order LIMIT :off,:lim"; + $stmt = $this->pdo->prepare($sql); + + // Bind parameters + foreach ($params as $k => $v) $stmt->bindValue($k, $v, is_int($v) ? PDO::PARAM_INT : PDO::PARAM_STR); + $stmt->bindValue(':off', $offset, PDO::PARAM_INT); + $stmt->bindValue(':lim', $limit, PDO::PARAM_INT); + $stmt->execute(); + $rows = $stmt->fetchAll(); + + $out = []; + foreach ($rows as $r) { + $item = [ + 'id' => $r[$idCol] ?? null, + 'name' => $r[$nameCol] ?? null, + ]; + if ($descCol && isset($r[$descCol])) $item['desc'] = $r[$descCol]; + if ($catCol && isset($r[$catCol])) $item['category'] = $r[$catCol]; + if ($updCol && isset($r[$updCol])) $item['updated_at'] = $r[$updCol]; + + // Lade HTML und JSON aus den korrekten Spalten + $htmlCol = $this->firstExisting($allCols, ['html', 'body', 'markup', 'content']); + if ($htmlCol && isset($r[$htmlCol])) $item['html'] = (string)$r[$htmlCol]; + $jsonCol = $this->firstExisting($allCols, ['json_content']); + if ($jsonCol && isset($r[$jsonCol])) $item['content'] = $r[$jsonCol]; + + $out[] = $item; + } + $this->respond(['ok' => true, 'kind' => $kind, 'items' => $out, 'data' => $out, 'count' => count($out), 'offset' => $offset, 'limit' => $limit]); + } + + /** + * Allgemeine Methode zur Handhabung von GET-Anfragen. + */ + private function handleGet(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $id = $this->pullId($this->in); + if ($id === null || $id === '') $this->fail('id required', null, 422); + + [$tw, $tp] = $this->tenantWhere($auth); + $sql = "SELECT * FROM `$t` WHERE `$idCol` = :id" . $tw . " LIMIT 1"; + $stmt = $this->pdo->prepare($sql); + $stmt->bindValue(':id', $id); + foreach ($tp as $k => $v) $stmt->bindValue($k, $v); + $stmt->execute(); + $row = $stmt->fetch(); + if (!$row) $this->fail('Not found', ['kind' => $kind, 'id' => $id], 404); + $rowOut = ['id' => $row[$idCol] ?? $id] + $row; + + // Lade HTML und JSON aus den korrekten Spalten + $htmlCol = $this->firstExisting($allCols, ['html', 'body', 'markup', 'content']); + $topHtml = ($htmlCol && isset($row[$htmlCol])) ? (string)$row[$htmlCol] : null; + $jsonCol = $this->firstExisting($allCols, ['json_content']); + $topContent = ($jsonCol && isset($row[$jsonCol])) ? $row[$jsonCol] : null; + + $gjsComponents = []; + + if ($topContent !== null) { + $decodedContent = json_decode($topContent, true); + if (is_array($decodedContent)) { + $gjsComponents = $decodedContent; + } + } + + if (empty($gjsComponents) && $topHtml !== null) { + $gjsComponents = $this->parseHtmlToGjsComponents($topHtml); + } + + $this->respond([ + 'ok' => true, + 'kind' => $kind, + 'id' => $rowOut['id'], + 'item' => $rowOut, + 'data' => $rowOut, + 'html' => $topHtml, + 'content' => $topContent, + 'gjs_components' => $gjsComponents + ]); + } + + /** + * Allgemeine Methode zur Handhabung von CREATE-Anfragen (inkl. JSON-Bereinigung). + */ + private function handleCreate(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $cfg = $this->conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? ($this->firstExisting($allCols, ['name']) ?: $idCol); + $descCol = $cfg['desc'] ?? $this->firstExisting($allCols, ['description', 'desc', 'descr']); + $catCol = $cfg['cat'] ?? $this->firstExisting($allCols, ['category', 'cat']); + $updCol = $cfg['upd'] ?? $this->firstExisting($allCols, ['updated_at', 'updated', 'updatedAt']); + + $name = trim((string)$this->val($this->in, ['name', 'title'], '')); + if ($name === '') $this->fail('name required', null, 422); + + $desc = (string)$this->val($this->in, ['description', 'desc'], null); + $cat = (string)$this->val($this->in, ['category', 'cat'], null); + $html = (string)$this->val($this->in, ['html', 'body', 'markup'], null); + $json = $this->val($this->in, ['content_json', 'json', 'content', 'structure_json'], null); + $settings = $this->val($this->in, ['settings_json', 'settings'], null); + $templateId = $this->val($this->in, ['template_id', 'tpl_id'], null); + $sectionId = $this->val($this->in, ['section_id', 'sec_id'], null); + $blockId = $this->val($this->in, ['block_id', 'blk_id'], null); + + $data = [$nameCol => $name]; + if ($desc !== null && $descCol) $data[$descCol] = $desc; + if ($cat !== null && $catCol) $data[$catCol] = $cat; + + $htmlDbCol = $this->firstExisting($allCols, ($kind === 'snippets' ? ['content'] : ['html', 'body', 'markup'])); + $jsonDbCol = $this->firstExisting($allCols, ['json_content']); + + // --- LOGIK mit ERWEITERTER PRÜFUNG START --- + + // 1. JSON-Content behandeln + if ($json !== null) { + if ($jsonDbCol) { + $components = is_string($json) ? json_decode($json, true) : $json; + if (is_array($components)) { + $components = $this->cleanReferenceComponents($components); // BEREINIGUNG + $data[$jsonDbCol] = json_encode($components, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } else { + $data[$jsonDbCol] = is_string($json) ? $json : ''; + } + } else { + // FALLBACK: Wenn JSON gesendet wurde, aber keine json_content Spalte existiert, FEHLER ausgeben + $this->fail( + 'JSON content provided but no `json_content` column found', + ['table' => $t, 'available_cols' => $allCols], + 422 + ); + } + } + + // 2. HTML-Content speichern + if ($htmlDbCol && $html !== null) { + $data[$htmlDbCol] = $html; + } + // --- LOGIK mit ERWEITERTER PRÜFUNG ENDE --- + + $c = $this->firstExisting($allCols, ['settings_json', 'settings']); + if ($c && $settings !== null) $data[$c] = is_string($settings) ? $settings : json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + if ($templateId !== null && in_array('template_id', $allCols, true)) $data['template_id'] = $templateId; + if ($sectionId !== null && in_array('section_id', $allCols, true)) $data['section_id'] = $sectionId; + if ($blockId !== null && in_array('block_id', $allCols, true)) $data['block_id'] = $blockId; + + $data = $data + $this->tenantAssign($_SESSION['auth'] ?? [], $allCols); + + $now = date('Y-m-d H:i:s'); + $createdCol = $this->firstExisting($allCols, ['created_at', 'created', 'createdAt']); + if ($createdCol) $data[$createdCol] = $now; + if ($updCol) $data[$updCol] = $now; + + $fields = array_keys($data); + $place = array_map(fn($c) => ":$c", $fields); + $sql = "INSERT INTO `$t` (" . implode(',', array_map(fn($c) => "`$c`", $fields)) . ") VALUES (" . implode(',', $place) . ")"; + $stmt = $this->pdo->prepare($sql); + foreach ($data as $k => $v) $stmt->bindValue(":$k", $v); + $stmt->execute(); + $newId = $this->pdo->lastInsertId(); + + $out = ['id' => $newId, 'name' => $name]; + if ($desc !== null) $out['desc'] = $desc; + if ($cat !== null) $out['category'] = $cat; + $this->respond(['ok' => true, 'kind' => $kind, 'id' => $newId, 'item' => $out, 'data' => $out]); + } + + /** + * Allgemeine Methode zur Handhabung von UPDATE-Anfragen (inkl. JSON-Bereinigung). + */ + private function handleUpdate(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $cfg = $this->conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? ($this->firstExisting($allCols, ['name']) ?: $idCol); + $descCol = $cfg['desc'] ?? $this->firstExisting($allCols, ['description', 'desc', 'descr']); + $catCol = $cfg['cat'] ?? $this->firstExisting($allCols, ['category', 'cat']); + $updCol = $cfg['upd'] ?? $this->firstExisting($allCols, ['updated_at', 'updated', 'updatedAt']); + $id = $this->pullId($this->in); + if ($id === null || $id === '') $this->fail('id required', null, 422); + + $data = []; + $name = $this->val($this->in, ['name', 'title'], null); + $desc = $this->val($this->in, ['description', 'desc'], null); + $cat = $this->val($this->in, ['category', 'cat'], null); + $html = $this->val($this->in, ['html', 'body', 'markup'], null); + $json = $this->val($this->in, ['content_json', 'json', 'content', 'structure_json'], null); + $settings = $this->val($this->in, ['settings_json', 'settings'], null); + + if ($name !== null) $data[$nameCol] = (string)$name; + if ($desc !== null && $descCol) $data[$descCol] = (string)$desc; + if ($cat !== null && $catCol) $data[$catCol] = (string)$cat; + + $htmlDbCol = $this->firstExisting($allCols, ($kind === 'snippets' ? ['content'] : ['html', 'body', 'markup'])); + $jsonDbCol = $this->firstExisting($allCols, ['json_content']); + + // --- LOGIK mit ERWEITERTER PRÜFUNG START --- + + // 1. JSON-Content behandeln + if ($json !== null) { + if ($jsonDbCol) { + // Wenn JSON-Spalte existiert, JSON verarbeiten und speichern + $components = is_string($json) ? json_decode($json, true) : $json; + if (is_array($components)) { + $components = $this->cleanReferenceComponents($components); // BEREINIGUNG + $data[$jsonDbCol] = json_encode($components, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } else { + $data[$jsonDbCol] = is_string($json) ? $json : ''; + } + } else { + // FALLBACK: Wenn JSON gesendet wurde, aber keine json_content Spalte existiert, FEHLER ausgeben + $this->fail( + 'JSON content provided but no `json_content` column found', + ['table' => $t, 'available_cols' => $allCols], + 422 + ); + } + + // 2. Den zugehörigen HTML-Output speichern (wird vom Editor immer mitgesendet, wenn JSON da ist) + if ($html !== null && $htmlDbCol) { + $data[$htmlDbCol] = (string)$html; + } + } elseif ($html !== null && $htmlDbCol) { + // Wenn NUR HTML gesendet wird (für minimale Änderungen), speichern wir nur HTML. + $data[$htmlDbCol] = (string)$html; + } + // --- LOGIK mit ERWEITERTER PRÜFUNG ENDE --- + + $c = $this->firstExisting($allCols, ['settings_json', 'settings']); + if ($settings !== null && $c) $data[$c] = is_string($settings) ? $settings : json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + $tpl = $this->val($this->in, ['template_id', 'tpl_id'], null); + if ($tpl !== null && in_array('template_id', $allCols, true)) $data['template_id'] = $tpl; + $sec = $this->val($this->in, ['section_id', 'sec_id'], null); + if ($sec !== null && in_array('section_id', $allCols, true)) $data['section_id'] = $sec; + $blk = $this->val($this->in, ['block_id', 'blk_id'], null); + if ($blk !== null && in_array('block_id', $allCols, true)) $data['block_id'] = $blk; + + if ($updCol) $data[$updCol] = date('Y-m-d H:i:s'); + if (!$data) $this->fail('nothing to update', null, 422); + + [$tw, $tp] = $this->tenantWhere($auth); + $set = []; + foreach (array_keys($data) as $c) $set[] = "`$c` = :$c"; + $sql = "UPDATE `$t` SET " . implode(',', $set) . " WHERE `$idCol` = :__id" . $tw . " LIMIT 1"; + $stmt = $this->pdo->prepare($sql); + + foreach ($data as $k => $v) $stmt->bindValue(":$k", $v); + $stmt->bindValue(':__id', $id); + foreach ($tp as $k => $v) $stmt->bindValue($k, $v); + $stmt->execute(); + $this->respond(['ok' => true, 'kind' => $kind, 'id' => $id, 'updated' => array_keys($data)]); + } + + /** + * Allgemeine Methode zur Handhabung von DELETE-Anfragen. + */ + private function handleDelete(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $id = $this->pullId($this->in); + if ($id === null || $id === '') $this->fail('id required', null, 422); + + [$tw, $tp] = $this->tenantWhere($auth); + $sql = "DELETE FROM `$t` WHERE `$idCol` = :__id" . $tw . " LIMIT 1"; + $stmt = $this->pdo->prepare($sql); + $stmt->bindValue(':__id', $id); + foreach ($tp as $k => $v) $stmt->bindValue($k, $v); + $stmt->execute(); + $this->respond(['ok' => true, 'kind' => $kind, 'id' => $id, 'deleted' => true]); + } + + // ================================================================= + // 💡 Öffentliche run()-Methode (KORRIGIERT) + // ================================================================= + + public function run(): void + { + // 💡 KORREKTUR: Der Content-Type Header wird hier entfernt, da er jetzt in respond() + // zentralisiert wurde, um sicherzustellen, dass er auch bei Fehlern im Konstruktor oder + // im try-Block korrekt gesetzt wird. + // header('Content-Type: application/json; charset=utf-8'); // DIESE ZEILE ENTFERNT + + try { + // Extrahiere den Ressourcen-Typ und die Operation (z.B. 'templates' und 'list') + [$kind, $operation] = explode('.', $this->action, 2) + [1 => '']; + + switch ($this->action) { + case 'health': + $this->respond(['ok' => true, 'time' => date('c')]); + + /* ---------- AUTH ---------- */ + case 'auth.login': + $result = $this->authService->login($this->in); + $this->respond(['ok' => true] + $result); + break; + case 'auth.me': + if (empty($_SESSION['auth'])) $this->fail('Not authenticated', null, 401); + $this->respond(['ok' => true, 'user' => $_SESSION['auth']]); + break; + case 'auth.logout': + $this->authService->logout(); + $this->respond(['ok' => true]); + break; + + /* ---------- CRUD HANDLER ---------- */ + default: + if (in_array($kind, ['templates', 'sections', 'blocks', 'snippets'])) { + switch ($operation) { + case 'list': + $this->handleList($kind); + break; + case 'get': + $this->handleGet($kind); + break; + case 'create': + $this->handleCreate($kind); + break; + case 'update': + $this->handleUpdate($kind); + break; + case 'delete': + $this->handleDelete($kind); + break; + default: + $this->fail('Unknown operation for resource: ' . $this->action, null, 404); + break; + } + } else { + $this->fail('Unknown action', $this->action ?: 'missing', 404); + } + break; + } + } catch (Throwable $e) { + $this->fail('Server error', get_class($e) . ': ' . $e->getMessage(), 500); + } + } +} diff --git a/inc/AuthService.php b/inc/AuthService.php new file mode 100644 index 0000000..f0112d4 --- /dev/null +++ b/inc/AuthService.php @@ -0,0 +1,105 @@ +conf = $conf; + $this->pdo = $pdo; + } + + // --- Private Utility Methoden --- + + private function fail(string $msg, $detail = null, int $code = 400): void + { + // Wir müssen hier direkt antworten, da wir das Fail-Verhalten des Kernels benötigen. + // Im ApiKernel werden wir die respond/fail-Methoden als public lassen, + // um sie hier injizieren zu können, oder wir lassen sie hier im Global Scope + // (WENN Sie die ursprünglichen globalen Funktionen respond/fail wieder zulassen). + // Für eine saubere Kapselung injizieren wir die Respond-Logik. + // HIER verwenden wir eine einfache JSON-Antwort, da die fail-Methode + // normalerweise den gesamten Kernel stoppt. Wir nutzen exit. + + http_response_code($code); + echo json_encode(['ok'=>false,'error'=>$msg,'detail'=>$detail], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + exit; + } + + private function verifyPassword(string $input, string $stored, array $authDbConf): bool + { + if (preg_match('~^\$2[aby]\$~', $stored) || strpos($stored, '$argon2') === 0) return password_verify($input, $stored); + $legacy = strtolower($authDbConf['legacy'] ?? ''); + if ($legacy === 'md5') return hash_equals($stored, md5($input)); + if ($legacy === 'sha1') return hash_equals($stored, sha1($input)); + if (password_get_info($stored)['algo'] !== 0) return password_verify($input, $stored); + return hash_equals($stored, $input); + } + + // --- Public Service Methoden --- + + public function requireAuth(): array + { + if (empty($_SESSION['auth'])) $this->fail('Not authenticated', null, 401); + return $_SESSION['auth']; + } + + public function logout(): bool + { + $_SESSION = []; + if (session_id() !== '') session_destroy(); + return true; + } + + public function login(array $in): array + { + $authDb = $this->conf['auth']['db'] ?? []; + $colUser = $authDb['col_user'] ?? 'email'; + $colPass = $authDb['col_pass'] ?? 'password'; + $colName = $authDb['col_name'] ?? 'name'; + $colId = $authDb['col_id'] ?? 'id'; + $colStatus = $authDb['col_status']?? null; + $activeValues = $authDb['active_values'] ?? ['active','1',1]; + $table = $authDb['table'] ?? 'emailtemplate_users'; + + $identifier = trim((string)($in['username'] ?? $in['user'] ?? $in['email'] ?? $in['login'] ?? '')); + $password = (string)($in['password'] ?? $in['pass'] ?? $in['pwd'] ?? ''); + + if ($identifier === '' || $password === '') $this->fail('username/password required', null, 422); + + $stmt = $this->pdo->prepare("SELECT * FROM `$table` WHERE `$colUser` = :u LIMIT 1"); + $stmt->execute([':u'=>$identifier]); + $row = $stmt->fetch(); + + if (!$row) $this->fail('Invalid credentials', null, 401); + + if ($colStatus && isset($row[$colStatus])) { + if (!in_array($row[$colStatus], $activeValues, true)) { + $this->fail('Account inactive', null, 403); + } + } + + $stored = (string)($row[$colPass] ?? ''); + if ($stored === '' || !$this->verifyPassword($password, $stored, $authDb)) { + $this->fail('Invalid credentials', null, 401); + } + + $_SESSION['auth'] = [ + 'id' => $row[$colId] ?? null, + 'name' => $row[$colName] ?? ($row[$colUser] ?? $identifier), + 'email' => $row[$colUser] ?? $identifier, + 'at' => time(), + ]; + + $token = base64_encode(hash('sha256', ($_SESSION['auth']['id'] ?? $identifier).'|'.session_id(), true)); + return ['user'=>$_SESSION['auth'], 'token'=>$token]; + } +} diff --git a/inc/OUTDATED auth_helpers.php b/inc/OUTDATED auth_helpers.php new file mode 100644 index 0000000..6ad3f69 --- /dev/null +++ b/inc/OUTDATED auth_helpers.php @@ -0,0 +1,138 @@ + 0, + 'path' => $cookiePath, + 'domain' => $cookieDomain, + 'secure' => $cookieSecure, + 'httponly' => $cookieHttpOnly, + 'samesite' => $cookieSameSite, + ]); + session_start(); + } +} + +/** ===== Auth Core ===== */ +function auth_login(PDO $pdoCustomers, array $cfg, string $email, string $password): array { + auth_start_session($cfg); + + $sql = "SELECT cu.id, cu.customer_id, cu.email, cu.password_hash, cu.role, + c.slug AS customer_slug, c.plan, c.status + FROM customer_users cu + JOIN customers c ON c.id = cu.customer_id + WHERE cu.email = :email AND cu.is_active = 1 + LIMIT 1"; + $st = $pdoCustomers->prepare($sql); + $st->execute([':email' => $email]); + $u = $st->fetch(PDO::FETCH_ASSOC); + + if (!$u || !password_verify($password, $u['password_hash'])) { + return ['ok' => false, 'error' => 'invalid_credentials']; + } + if (($u['status'] ?? 'active') !== 'active') { + return ['ok' => false, 'error' => 'customer_inactive']; + } + + // neue Session-ID, alte wird invalidiert + session_regenerate_id(true); + + $_SESSION['user'] = [ + 'id' => (int)$u['id'], + 'email' => $u['email'], + 'role' => $u['role'], + 'customer_id' => (int)$u['customer_id'], + 'customer_slug' => $u['customer_slug'], + 'plan' => $u['plan'], + ]; + return ['ok' => true, 'user' => $_SESSION['user']]; +} + +function auth_logout(array $cfg): void { + auth_start_session($cfg); + + // Sessiondaten löschen + $_SESSION = []; + + // Cookie-Parameter aus der aktiven Session + $params = session_get_cookie_params(); + $name = session_name(); + + // Kandidaten für Domain/Path, um "falsch" gesetzte Cookies sicher zu treffen + $host = $_SERVER['HTTP_HOST'] ?? ''; + $cfgDomain = $cfg['auth']['cookie_domain'] ?? ''; + $paths = array_values(array_unique([$params['path'] ?? '/', '/', ''])); + $domains = array_values(array_unique([ + $params['domain'] ?? '', + $cfgDomain, + $host, + ltrim($host, '.'), + (strpos($host, '.') !== false ? '.' . ltrim($host, '.') : $host), + ])); + + // Alle Varianten invalidieren (secure/httponly wie gesetzt) + foreach ($paths as $p) { + foreach ($domains as $d) { + if ($d === null) continue; + setcookie($name, '', time() - 3600, $p, $d, $params['secure'] ?? true, $params['httponly'] ?? true); + } + // zusätzlich: ohne Domain (trifft Host-spezifische Cookies) + setcookie($name, '', time() - 3600, $p, '', $params['secure'] ?? true, $params['httponly'] ?? true); + } + + // Session beenden + session_destroy(); + session_write_close(); + + // In Staging aggressiv: Browser bitten, Cookies zu löschen (nicht jeder Browser respektiert das sofort) + if (($cfg['env'] ?? 'prod') === 'staging') { + header('Clear-Site-Data: "cookies"', false); + } +} + +function auth_require(array $cfg): void { + auth_start_session($cfg); + if (empty($_SESSION['user'])) { + http_response_code(401); + header('Content-Type: application/json; charset=utf-8'); + echo json_encode(['ok' => false, 'error' => 'unauthorized']); + exit; + } +} + +function require_role(array $cfg, array $roles): void { + auth_start_session($cfg); + $r = $_SESSION['user']['role'] ?? null; + if (!$r || !in_array($r, $roles, true)) { + http_response_code(403); + header('Content-Type: application/json; charset=utf-8'); + echo json_encode(['ok' => false, 'error' => 'forbidden']); + exit; + } +} + +function current_user(array $cfg): ?array { + auth_start_session($cfg); + return $_SESSION['user'] ?? null; +} + +function current_customer_id(array $cfg): ?int { + $u = current_user($cfg); + return $u['customer_id'] ?? null; +} + diff --git a/inc/OUTDATED bootstrap.php b/inc/OUTDATED bootstrap.php new file mode 100644 index 0000000..6a6c05c --- /dev/null +++ b/inc/OUTDATED bootstrap.php @@ -0,0 +1,232 @@ +false,'error'=>$msg,'detail'=>$detail], $code); +} + +// RESTLICHE HELFER (MÜSSEN KEINE GLOBALS VERWENDEN) +function load_config(): array { + $paths = [ + __DIR__ . '/config.php', + __DIR__ . '/../config.php', + __DIR__ . '/../../config.php', + ]; + + foreach ($paths as $p) { + if (is_file($p)) { + $conf = @include $p; + if (is_array($conf)) return $conf; + } + } + fail('Invalid config.php', 'config.php not found or not returning array', 500); +} + +function cors(array $conf): void { + $cors = $conf['cors'] ?? '*'; + if ($cors) { + header('Access-Control-Allow-Origin: ' . $cors); + header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); + header('Access-Control-Allow-Headers: Content-Type, Authorization'); + header('Access-Control-Allow-Credentials: true'); + } + if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') respond(['ok'=>true]); +} + +function get_input(): array { + $data = []; + $ct = $_SERVER['CONTENT_TYPE'] ?? ''; + if (stripos($ct, 'application/json') !== false) { + $raw = file_get_contents('php://input'); + if ($raw !== false && $raw !== '') { + $js = json_decode($raw, true); + if (is_array($js)) $data = $js; + } + } + foreach ($_POST as $k=>$v) $data[$k]=$v; + foreach ($_GET as $k=>$v) if (!array_key_exists($k,$data)) $data[$k]=$v; + return $data; +} + +function val(array $in, $keys, $default=null) { + if (!is_array($keys)) $keys = [$keys]; + foreach ($keys as $k) if (array_key_exists($k,$in)) return $in[$k]; + return $default; +} + +function first_existing(array $columns, array $candidates): ?string { + foreach ($candidates as $c) if (in_array($c, $columns, true)) return $c; + return null; +} + +function pdo_templates(array $conf): PDO { + if (!isset($conf['templates']) || !is_array($conf['templates'])) { + fail('Missing templates DB config', null, 500); + } + $c = $conf['templates']; + $host = $c['db_host'] ?? 'localhost'; + $db = $c['db_name'] ?? ($c['database'] ?? ''); + $user = $c['db_user'] ?? ($c['username'] ?? ''); + $pass = $c['db_pass'] ?? ($c['password'] ?? ''); + $charset = $c['db_charset'] ?? 'utf8mb4'; + $port = $c['db_port'] ?? 3306; + $dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset"; + $opt = [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ]; + return new PDO($dsn, $user, $pass, $opt); +} + +function verify_password(string $input, string $stored, array $authDbConf): bool { + if (preg_match('~^\$2[aby]\$~', $stored) || strpos($stored, '$argon2') === 0) return password_verify($input, $stored); + $legacy = strtolower($authDbConf['legacy'] ?? ''); + if ($legacy === 'md5') return hash_equals($stored, md5($input)); + if ($legacy === 'sha1') return hash_equals($stored, sha1($input)); + if (password_get_info($stored)['algo'] !== 0) return password_verify($input, $stored); + return hash_equals($stored, $input); +} + +function table_columns(PDO $pdo, string $table): array { + $cols = []; + $stmt = $pdo->query("SHOW COLUMNS FROM `$table`"); + foreach ($stmt->fetchAll() as $r) $cols[] = $r['Field']; + return $cols; +} + +function primary_key(PDO $pdo, string $table): ?string { + $stmt = $pdo->prepare("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'"); + $stmt->execute(); + $row = $stmt->fetch(); + return $row['Column_name'] ?? null; +} + + +// --- Neue, reguläre Funktionen (ersetzen Closures) --- + +function requireAuth(): array { + // Muss auf globale $_SESSION zugreifen + if (empty($_SESSION['auth'])) fail('Not authenticated', null, 401); + return $_SESSION['auth']; +} + +function pullId(array $src) { + $aliases = ['id','item_id','template_id','tpl_id','section_id','sec_id','block_id','blk_id','snippet_id','snip_id']; + foreach ($aliases as $a) if (isset($src[$a]) && $src[$a] !== '') return $src[$a]; + return null; +} + +function tenantWhere(array $session): array { + // Muss auf globale $conf zugreifen, um $tenantCol und $mapSess zu erhalten + global $conf; + $multi = $conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; + + if (!$tenantCol) return ['', []]; + if (!$session) return [' AND 1=0 ', []]; + $val = $session[$mapSess] ?? null; + if ($val===null || $val==='') return [' AND 1=0 ', []]; + return [" AND `$tenantCol` = :__tenant", [':__tenant'=>$val]]; +} + +function tenantAssign(array $session, array $columns): array { + // Muss auf globale $conf zugreifen + global $conf; + $multi = $conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; + + if (!$tenantCol || !in_array($tenantCol, $columns, true)) return []; + $val = $session[$mapSess] ?? null; + return ($val===null || $val==='') ? [] : [$tenantCol => $val]; +} + +function resolveIdCol(string $kind): array { + // Muss auf globale $conf, $pdo, und $tableMap zugreifen + global $conf, $pdo, $tableMap; + + $t = $tableMap[$kind]; + $cfg = $conf['columns'][$kind] ?? []; + $cols = table_columns($pdo, $t); + $idCol = $cfg['id'] ?? (in_array('id', $cols, true) ? 'id' : primary_key($pdo, $t)); + if (!$idCol) $idCol = 'id'; + return [$idCol, $cols]; +} + +// --- Haupt-Setup-Logik (Setzt die globalen Variablen) --- + +try { + // Deklariere alle Variablen, die im Router von api.php benötigt werden, als global + global $conf, $pdo, $in, $action, $tableMap; + + // 1. Globale Konfiguration und CORS + $conf = load_config(); + cors($conf); + + // 2. Cookie-Parameter setzen + if (!empty($conf['auth']['cookie'])) { + $c = $conf['auth']['cookie']; + $params = session_get_cookie_params(); + $params['lifetime'] = $c['lifetime'] ?? $params['lifetime']; + $params['path'] = $c['path'] ?? $params['path']; + $params['domain'] = $c['domain'] ?? $params['domain']; + $params['secure'] = $c['secure'] ?? $params['secure']; + $params['httponly'] = $c['httponly'] ?? $params['httponly']; + if (isset($c['samesite'])) $params['samesite'] = $c['samesite']; + session_set_cookie_params($params); + } + + // 3. Input-Daten abrufen + $in = get_input(); + + // 4. Datenbankverbindung herstellen + $pdo = pdo_templates($conf); + + // 5. Action / Resource auflösen + $action = val($in, 'action', ''); + $resource = val($in, 'resource', null); + $allowedResources = ['templates','sections','blocks','snippets']; + if ($resource && in_array($resource, $allowedResources, true) && strpos((string)$action, '.') === false) { + $verb = strtolower((string)$action); + if (in_array($verb, ['list','get','create','update','delete'], true)) $action = $resource.'.'.$verb; + } + + // 6. Tabellenzuweisungen + $tables = $conf['tables'] ?? []; + $tableMap = [ + 'templates' => $tables['templates'] ?? 'emailtemplate_templates', + 'sections' => $tables['sections'] ?? 'emailtemplate_sections', + 'blocks' => $tables['blocks'] ?? 'emailtemplate_blocks', + 'snippets' => $tables['snippets'] ?? 'emailtemplate_snippets', + ]; + +} catch (Throwable $e) { + // Fehler während der Initialisierung abfangen + fail('Initialization error', get_class($e).': '.$e->getMessage(), 500); +} diff --git a/inc/OUTDATED config.example.php b/inc/OUTDATED config.example.php new file mode 100644 index 0000000..a990df8 --- /dev/null +++ b/inc/OUTDATED config.example.php @@ -0,0 +1,36 @@ + [ + 'db_host' => '127.0.0.1', + 'db_port' => 3306, + 'db_name' => 'YOUR_DB_NAME', + 'db_user' => 'YOUR_DB_USER', + 'db_pass' => 'YOUR_DB_PASS', + 'db_charset' => 'utf8mb4', + 'prefix' => 'emailtemplate_', + ], + 'project' => [ + 'db_host' => '127.0.0.1', + 'db_port' => 3306, + 'db_name' => 'YOUR_PROJECT_DB', + 'db_user' => 'YOUR_PROJECT_USER', + 'db_pass' => 'YOUR_PROJECT_PASS', + 'db_charset' => 'utf8mb4', + ], + + // SMTP / Testversand + 'smtp' => [ + 'host' => getenv('SMTP_HOST') ?: '', + 'port' => getenv('SMTP_PORT') ?: 587, + 'user' => getenv('SMTP_USER') ?: '', + 'pass' => getenv('SMTP_PASS') ?: '', + 'secure' => getenv('SMTP_SECURE') ?: 'tls', + 'from_email' => getenv('SMTP_FROM_EMAIL') ?: 'no-reply@example.com', + 'from_name' => getenv('SMTP_FROM_NAME') ?: 'EmailTemplate', + ], + + // Export-API: statische API-Keys + 'export' => [ + 'api_keys' => explode(',', getenv('EXPORT_API_KEYS') ?: 'dev-key-123'), + ], +]; diff --git a/inc/api_kernel_log.txt b/inc/api_kernel_log.txt new file mode 100644 index 0000000..21abd13 --- /dev/null +++ b/inc/api_kernel_log.txt @@ -0,0 +1,259 @@ + + + +[2025-10-31 01:21:54] --- Get::blocks - Raw JSON from DB --- +Array +( + [topContent] => {"dataSources":[],"assets":[],"styles":[{"selectors":[],"selectorsAdd":"*","style":{"box-sizing":"border-box"}},{"selectors":[],"selectorsAdd":"body","style":{"margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px"}}],"pages":[{"frames":[{"component":{"type":"wrapper","stylable":["background","background-color","background-image","background-repeat","background-attachment","background-position","background-size"],"components":[{"type":"library-reference","content":"Alles Neu macht der Mai","lib-kind":"snippets","lib-id":1}],"head":{"type":"head"},"docEl":{"tagName":"html"}},"id":"P4uy9DBKbT5yTO4c"}],"type":"main","id":"dJ5hyxgFUxsCWgbi"}],"symbols":[]} +) + + +[2025-10-31 01:21:54] --- Get::blocks - Decoded JSON --- +Array +( + [decodedContent] => Array + ( + [dataSources] => Array + ( + ) + + [assets] => Array + ( + ) + + [styles] => Array + ( + [0] => Array + ( + [selectors] => Array + ( + ) + + [selectorsAdd] => * + [style] => Array + ( + [box-sizing] => border-box + ) + + ) + + [1] => Array + ( + [selectors] => Array + ( + ) + + [selectorsAdd] => body + [style] => Array + ( + [margin-top] => 0px + [margin-right] => 0px + [margin-bottom] => 0px + [margin-left] => 0px + ) + + ) + + ) + + [pages] => Array + ( + [0] => Array + ( + [frames] => Array + ( + [0] => Array + ( + [component] => Array + ( + [type] => wrapper + [stylable] => Array + ( + [0] => background + [1] => background-color + [2] => background-image + [3] => background-repeat + [4] => background-attachment + [5] => background-position + [6] => background-size + ) + + [components] => Array + ( + [0] => Array + ( + [type] => library-reference + [content] => Alles Neu macht der Mai + [lib-kind] => snippets + [lib-id] => 1 + ) + + ) + + [head] => Array + ( + [type] => head + ) + + [docEl] => Array + ( + [tagName] => html + ) + + ) + + [id] => P4uy9DBKbT5yTO4c + ) + + ) + + [type] => main + [id] => dJ5hyxgFUxsCWgbi + ) + + ) + + [symbols] => Array + ( + ) + + ) + +) + + +[2025-10-31 01:21:54] --- Get::blocks - Final Gjs Components --- +Array +( + [count] => 5 + [first_component] => N/A +) + + +[2025-10-31 01:21:54] --- Get::blocks - Raw JSON from DB --- +Array +( + [topContent] => {"dataSources":[],"assets":[],"styles":[{"selectors":[],"selectorsAdd":"*","style":{"box-sizing":"border-box"}},{"selectors":[],"selectorsAdd":"body","style":{"margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px"}}],"pages":[{"frames":[{"component":{"type":"wrapper","stylable":["background","background-color","background-image","background-repeat","background-attachment","background-position","background-size"],"components":[{"type":"library-reference","content":"Alles Neu macht der Mai","lib-kind":"snippets","lib-id":1}],"head":{"type":"head"},"docEl":{"tagName":"html"}},"id":"P4uy9DBKbT5yTO4c"}],"type":"main","id":"dJ5hyxgFUxsCWgbi"}],"symbols":[]} +) + + +[2025-10-31 01:21:54] --- Get::blocks - Decoded JSON --- +Array +( + [decodedContent] => Array + ( + [dataSources] => Array + ( + ) + + [assets] => Array + ( + ) + + [styles] => Array + ( + [0] => Array + ( + [selectors] => Array + ( + ) + + [selectorsAdd] => * + [style] => Array + ( + [box-sizing] => border-box + ) + + ) + + [1] => Array + ( + [selectors] => Array + ( + ) + + [selectorsAdd] => body + [style] => Array + ( + [margin-top] => 0px + [margin-right] => 0px + [margin-bottom] => 0px + [margin-left] => 0px + ) + + ) + + ) + + [pages] => Array + ( + [0] => Array + ( + [frames] => Array + ( + [0] => Array + ( + [component] => Array + ( + [type] => wrapper + [stylable] => Array + ( + [0] => background + [1] => background-color + [2] => background-image + [3] => background-repeat + [4] => background-attachment + [5] => background-position + [6] => background-size + ) + + [components] => Array + ( + [0] => Array + ( + [type] => library-reference + [content] => Alles Neu macht der Mai + [lib-kind] => snippets + [lib-id] => 1 + ) + + ) + + [head] => Array + ( + [type] => head + ) + + [docEl] => Array + ( + [tagName] => html + ) + + ) + + [id] => P4uy9DBKbT5yTO4c + ) + + ) + + [type] => main + [id] => dJ5hyxgFUxsCWgbi + ) + + ) + + [symbols] => Array + ( + ) + + ) + +) + + +[2025-10-31 01:21:54] --- Get::blocks - Final Gjs Components --- +Array +( + [count] => 5 + [first_component] => N/A +) diff --git a/inc/config.php b/inc/config.php new file mode 100644 index 0000000..3f2ed05 --- /dev/null +++ b/inc/config.php @@ -0,0 +1,76 @@ + [ + 'db_host' => getenv('DB_TPL_HOST') ?: 'localhost', + 'db_name' => getenv('DB_TPL_NAME') ?: 'd044ae9e', + 'db_user' => getenv('DB_TPL_USER') ?: 'd044ae9e', + 'db_pass' => getenv('DB_TPL_PASS') ?: '9BVUn)Töcü@ÖVÜfgO8!J', + 'db_charset' => 'utf8', + 'prefix' => getenv('DB_TPL_PREFIX') ?: 'emailtemplate_', + + ], + 'project' => [ + 'db_host' => getenv('DB_TPL_HOST') ?: 'w0207fd0.kasserver.com', + 'db_name' => getenv('DB_TPL_NAME') ?: 'd0444c25', + 'db_user' => getenv('DB_TPL_USER') ?: 'd0444c25', + 'db_pass' => getenv('DB_TPL_PASS') ?: '/7ü9+§ÄfkiQvGPr§2Op7', + 'db_charset' => 'utf8', + ], + 'cors' => getenv('CORS_ORIGIN') ?: '*', + 'env' => 'staging', + 'base_url' => 'https://staging.emailtemplate.it', + 'auth' => [ + 'session_name' => 'et_session', + 'cookie_domain' => 'staging.emailtemplate.it', + 'cookie_secure' => true, + 'cookie_httponly'=> true, + 'cookie_samesite'=> 'Lax', + 'db' => [ + 'table' => 'customer_users', + 'col_user' => 'email', // alternativ: 'username' + 'col_pass' => 'password_hash', + 'col_name' => 'name', // optional + 'col_id' => 'id', // optional + 'col_status' => 'is_active', // optional + 'active_values'=> ['active','1',1], // optional + 'legacy' => 'md5' // optional: 'md5' | 'sha1' | 'plain' (sonst bcrypt/argon2) + ], + + ], +'smtp' => [ + 'host' => 'smtp.example.com', + 'port' => 587, + 'user' => 'smtp-user', + 'pass' => 'smtp-pass', + 'secure' => 'tls', // oder 'ssl' + 'from_email' => 'no-reply@example.com', + 'from_name' => 'EmailTemplate', +], +'export' => [ + 'api_keys' => ['dev-key-123', 'noch-ein-key'], // füge hier deine Keys ein +], + 'multi' => [ + // Spalte in ALLEN Content-Tabellen, die dem Besitzer/Mandanten entspricht: + 'tenant_col' => 'customer_id', // <— falls es bei dir z. B. 'owner_id' heißt: entsprechend anpassen. + // Welche Session-Info darauf gemappt wird: + 'map_session_to' => 'id', // 'id' (Default) | 'email' | 'name' + ], + + // optional: abweichende Tabellennamen/Spalten: + 'tables' => [ + 'templates' => 'emailtemplate_templates', + 'sections' => 'emailtemplate_sections', + 'blocks' => 'emailtemplate_blocks', + 'snippets' => 'emailtemplate_snippets', + ], + 'columns' => [ + // Nur anpassen, wenn deine Spaltennamen abweichen + 'templates' => ['id'=>'id','name'=>'name','desc'=>null,'cat'=>null,'upd'=>'updated_at'], + 'sections' => ['id'=>'id','name'=>'name','cat'=>null,'upd'=>'updated_at'], + 'blocks' => ['id'=>'id','name'=>'name','cat'=>'category','upd'=>'updated_at'], + 'snippets' => ['id'=>'id','name'=>'name','cat'=>'category','upd'=>'updated_at'], + ], +]; + diff --git a/public/api (Kopie).php b/public/api (Kopie).php new file mode 100644 index 0000000..60e81b1 --- /dev/null +++ b/public/api (Kopie).php @@ -0,0 +1,525 @@ +false,'error'=>$msg,'detail'=>$detail], $code); +} + +function load_config(): array { + $paths = [ + __DIR__ . '/../inc/config.php', + __DIR__ . '/inc/config.php', + __DIR__ . '/config.php', + ]; + + foreach ($paths as $p) { + if (is_file($p)) { + $conf = @include $p; + if (is_array($conf)) return $conf; + } + } + fail('Invalid config.php', 'config.php not found or not returning array', 500); +} + +function cors(array $conf): void { + $cors = $conf['cors'] ?? '*'; + if ($cors) { + header('Access-Control-Allow-Origin: ' . $cors); + header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); + header('Access-Control-Allow-Headers: Content-Type, Authorization'); + header('Access-Control-Allow-Credentials: true'); + } + if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') respond(['ok'=>true]); +} + +function get_input(): array { + $data = []; + $ct = $_SERVER['CONTENT_TYPE'] ?? ''; + if (stripos($ct, 'application/json') !== false) { + $raw = file_get_contents('php://input'); + if ($raw !== false && $raw !== '') { + $js = json_decode($raw, true); + if (is_array($js)) $data = $js; + } + } + foreach ($_POST as $k=>$v) $data[$k]=$v; + foreach ($_GET as $k=>$v) if (!array_key_exists($k,$data)) $data[$k]=$v; + return $data; +} + +function val(array $in, $keys, $default=null) { + if (!is_array($keys)) $keys = [$keys]; + foreach ($keys as $k) if (array_key_exists($k,$in)) return $in[$k]; + return $default; +} + +/** + * Inline-Styling für E-Mail-Templates (nutzt TijsVerkoyen/CssToInlineStyles) + * + * Diese Funktion steht nur bereit, wird aber noch nicht verwendet. + * @param string $html + * @param string|null $css + * @return string + */ +function inline_css(string $html, ?string $css = null): string { + // 1. Klasse existiert nicht + if (!class_exists('\TijsVerkoyen\CssToInlineStyles\CssToInlineStyles')) { + return $html; + } + + // 2. Direkte Instanziierung und Aufruf in einer einzigen Zeile + $result = (new \TijsVerkoyen\CssToInlineStyles\CssToInlineStyles($html, $css))->convert(); + + return $result; +} + +/* ===================== DB helpers ===================== */ +function pdo_templates(array $conf): PDO { + if (!isset($conf['templates']) || !is_array($conf['templates'])) { + fail('Missing templates DB config', null, 500); + } + $c = $conf['templates']; + $host = $c['db_host'] ?? 'localhost'; + $db = $c['db_name'] ?? ($c['database'] ?? ''); + $user = $c['db_user'] ?? ($c['username'] ?? ''); + $pass = $c['db_pass'] ?? ($c['password'] ?? ''); + $charset = $c['db_charset'] ?? 'utf8mb4'; + $port = $c['db_port'] ?? 3306; + $dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset"; + $opt = [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ]; + return new PDO($dsn, $user, $pass, $opt); +} + +function verify_password(string $input, string $stored, array $authDbConf): bool { + if (preg_match('~^\$2[aby]\$~', $stored) || strpos($stored, '$argon2') === 0) return password_verify($input, $stored); + $legacy = strtolower($authDbConf['legacy'] ?? ''); + if ($legacy === 'md5') return hash_equals($stored, md5($input)); + if ($legacy === 'sha1') return hash_equals($stored, sha1($input)); + if ($legacy === 'plain')return hash_equals($stored, $input); + if (password_get_info($stored)['algo'] !== 0) return password_verify($input, $stored); + return hash_equals($stored, $input); +} + +/* ============ schema helpers ============ */ +function table_columns(PDO $pdo, string $table): array { + $cols = []; + $stmt = $pdo->query("SHOW COLUMNS FROM `$table`"); + foreach ($stmt->fetchAll() as $r) $cols[] = $r['Field']; + return $cols; +} + +function primary_key(PDO $pdo, string $table): ?string { + $stmt = $pdo->prepare("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'"); + $stmt->execute(); + $row = $stmt->fetch(); + return $row['Column_name'] ?? null; +} + +function first_existing(array $columns, array $candidates): ?string { + foreach ($candidates as $c) if (in_array($c, $columns, true)) return $c; + return null; +} + +/* ===================== Boot ===================== */ +try { + $conf = load_config(); + cors($conf); + // if (session_status() === PHP_SESSION_NONE) session_start(); + if (!empty($conf['auth']['cookie'])) { + $c = $conf['auth']['cookie']; + $params = session_get_cookie_params(); + $params['lifetime'] = $c['lifetime'] ?? $params['lifetime']; + $params['path'] = $c['path'] ?? $params['path']; + $params['domain'] = $c['domain'] ?? $params['domain']; + $params['secure'] = $c['secure'] ?? $params['secure']; + $params['httponly'] = $c['httponly'] ?? $params['httponly']; + if (isset($c['samesite'])) $params['samesite'] = $c['samesite']; + session_set_cookie_params($params); + } + + $in = get_input(); + + /* ---- Compat: ?resource=blocks&action=list -> blocks.list ---- */ + $action = val($in, 'action', ''); + $resource = val($in, 'resource', null); + $allowedResources = ['templates','sections','blocks','snippets']; + if ($resource && in_array($resource, $allowedResources, true) && strpos((string)$action, '.') === false) { + $verb = strtolower((string)$action); + if (in_array($verb, ['list','get','create','update','delete'], true)) $action = $resource.'.'.$verb; + } + + /* ---- Multi-tenant ---- */ + $multi = $conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; // 'id'|'email'|'name' + + $tenantWhere = function(array $session) use ($tenantCol, $mapSess) { + if (!$tenantCol) return ['', []]; + if (!$session) return [' AND 1=0 ', []]; + $val = $session[$mapSess] ?? null; + if ($val===null || $val==='') return [' AND 1=0 ', []]; + return [" AND `$tenantCol` = :__tenant", [':__tenant'=>$val]]; + }; + + $tenantAssign = function(array $session, array $columns) use ($tenantCol, $mapSess) { + if (!$tenantCol || !in_array($tenantCol, $columns, true)) return []; + $val = $session[$mapSess] ?? null; + return ($val===null || $val==='') ? [] : [$tenantCol => $val]; + }; + + $requireAuth = function() { + if (empty($_SESSION['auth'])) fail('Not authenticated', null, 401); + return $_SESSION['auth']; + }; + + /* ---- config tables/columns ---- */ + $tables = $conf['tables'] ?? []; + $tableMap = [ + 'templates' => $tables['templates'] ?? 'emailtemplate_templates', + 'sections' => $tables['sections'] ?? 'emailtemplate_sections', + 'blocks' => $tables['blocks'] ?? 'emailtemplate_blocks', + 'snippets' => $tables['snippets'] ?? 'emailtemplate_snippets', + ]; + + $colsDefault = [ + 'id' => 'id', + 'name' => 'name', + 'desc' => 'description', + 'cat' => 'category', + 'upd' => 'updated_at', + ]; + + $pdo = pdo_templates($conf); + + /* helper: resolve id column for a table */ + $resolveIdCol = function(string $kind) use ($conf, $colsDefault, $tableMap, $pdo) { + $t = $tableMap[$kind]; + $cfg = $conf['columns'][$kind] ?? []; + $cols = table_columns($pdo, $t); + $idCol = $cfg['id'] ?? (in_array('id', $cols, true) ? 'id' : primary_key($pdo, $t)); + if (!$idCol) $idCol = 'id'; // fallback + return [$idCol, $cols]; + }; + + /* helper: accept many id aliases */ + $pullId = function(array $src) { + $aliases = ['id','item_id','template_id','tpl_id','section_id','sec_id','block_id','blk_id','snippet_id','snip_id']; + foreach ($aliases as $a) if (isset($src[$a]) && $src[$a] !== '') return $src[$a]; + return null; + }; + + /* ===================== Router ===================== */ + switch ($action) { + case 'health': + respond(['ok'=>true,'time'=>date('c')]); + + /* ---------- AUTH ---------- */ + case 'auth.login': { + $identifier = trim((string)val($in, ['username','user','email','login'], '')); + $password = (string)val($in, ['password','pass','pwd'], ''); + if ($identifier === '' || $password === '') fail('username/password required', null, 422); + $authDb = $conf['auth']['db'] ?? []; + $table = $authDb['table'] ?? 'emailtemplate_users'; + $colUser = $authDb['col_user'] ?? 'email'; + $colPass = $authDb['col_pass'] ?? 'password'; + $colName = $authDb['col_name'] ?? 'name'; + $colId = $authDb['col_id'] ?? 'id'; + $colStatus = $authDb['col_status']?? null; + $activeValues = $authDb['active_values'] ?? ['active','1',1]; + + $stmt = $pdo->prepare("SELECT * FROM `$table` WHERE `$colUser` = :u LIMIT 1"); + + $stmt->execute([':u'=>$identifier]); + $row = $stmt->fetch(); + if (!$row) fail('Invalid credentials', null, 401); + if ($colStatus && isset($row[$colStatus])) { + if (!in_array($row[$colStatus], $activeValues, true)) { + fail('Account inactive', null, 403); + } + } + + $stored = (string)($row[$colPass] ?? ''); + if ($stored === '' || !verify_password($password, $stored, $authDb)) { + fail('Invalid credentials', null, 401); + } + + $_SESSION['auth'] = [ + 'id' => $row[$colId] ?? null, + 'name' => $row[$colName] ?? ($row[$colUser] ?? $identifier), + 'email' => $row[$colUser] ?? $identifier, + 'at' => time(), + ]; + $token = base64_encode(hash('sha256', ($_SESSION['auth']['id'] ?? $identifier).'|'.session_id(), true)); + respond(['ok'=>true,'user'=>$_SESSION['auth'],'token'=>$token]); + } + + case 'auth.me': + if (empty($_SESSION['auth'])) fail('Not authenticated', null, 401); + respond(['ok'=>true,'user'=>$_SESSION['auth']]); + case 'auth.logout': + $_SESSION = []; + if (session_id() !== '') session_destroy(); + + respond(['ok'=>true]); + + /* ---------- LIST (mit Parent-Filtern) ---------- */ + case 'templates.list': + case 'sections.list': + case 'blocks.list': + case 'snippets.list': { + $auth = $requireAuth(); + $kind = explode('.', $action)[0]; + $t = $tableMap[$kind]; + [$idCol, $allCols] = $resolveIdCol($kind); + $cfg = $conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? (in_array('name',$allCols,true) ? 'name' : $idCol); + $descCol = $cfg['desc'] ?? first_existing($allCols, ['description','desc','descr']); + $catCol = $cfg['cat'] ?? first_existing($allCols, ['category','cat']); + $updCol = $cfg['upd'] ?? first_existing($allCols, ['updated_at','updated','updatedAt']); + $q = trim((string)val($in,'q','')); + $limit = max(1, (int)val($in,'limit', 500)); + $offset = max(0, (int)val($in,'offset',0)); + $where = ' WHERE 1=1 '; + $params = []; + if ($q !== '') { + $parts = ["`$nameCol` LIKE :q"]; + if ($descCol) $parts[] = "`$descCol` LIKE :q"; + if ($catCol) $parts[] = "`$catCol` LIKE :q"; + $where .= " AND (".implode(' OR ', $parts).") "; + $params[':q'] = '%'.$q.'%'; + } + + // Parent-Filtern (falls Spalten existieren) + $parentFilters = [ + 'template_id' => val($in, ['template_id','tpl_id'], null), + 'section_id' => val($in, ['section_id','sec_id'], null), + 'block_id' => val($in, ['block_id','blk_id'], null), + ]; + foreach ($parentFilters as $col => $v) { + if ($v === null || $v === '') continue; + if (in_array($col, $allCols, true)) { $where .= " AND `$col` = :$col "; $params[":$col"] = $v; } + } + + // Mandant + [$tw,$tp] = $tenantWhere($auth); + $where .= $tw; foreach ($tp as $k=>$v) $params[$k]=$v; + $order = $updCol ? " ORDER BY `$updCol` DESC " : " ORDER BY `$nameCol` ASC "; + $sql = "SELECT * FROM `$t` $where $order LIMIT :off,:lim"; + $stmt = $pdo->prepare($sql); + foreach ($params as $k=>$v) $stmt->bindValue($k,$v,is_int($v)?PDO::PARAM_INT:PDO::PARAM_STR); + $stmt->bindValue(':off',$offset,PDO::PARAM_INT); + $stmt->bindValue(':lim',$limit,PDO::PARAM_INT); + $stmt->execute(); + $rows = $stmt->fetchAll(); + + $out = []; + foreach ($rows as $r) { + $item = [ + 'id' => $r[$idCol] ?? null, + 'name' => $r[$nameCol] ?? null, + ]; + if ($descCol && isset($r[$descCol])) $item['desc'] = $r[$descCol]; + if ($catCol && isset($r[$catCol])) $item['category'] = $r[$catCol]; + if ($updCol && isset($r[$updCol])) $item['updated_at'] = $r[$updCol]; + $out[] = $item; + } + respond(['ok'=>true,'kind'=>$kind,'items'=>$out,'data'=>$out,'count'=>count($out),'offset'=>$offset,'limit'=>$limit]); + } + + /* ---------- GET (JETZT mit top-level html/content) ---------- */ + case 'templates.get': + case 'sections.get': + case 'blocks.get': + case 'snippets.get': { + $auth = $requireAuth(); + $kind = explode('.', $action)[0]; + $t = $tableMap[$kind]; + [$idCol, $allCols] = $resolveIdCol($kind); + $id = $pullId($in); + if ($id === null || $id === '') fail('id required', null, 422); + [$tw,$tp] = $tenantWhere($auth); + $sql = "SELECT * FROM `$t` WHERE `$idCol` = :id".$tw." LIMIT 1"; + $stmt = $pdo->prepare($sql); + $stmt->bindValue(':id', $id); + foreach ($tp as $k=>$v) $stmt->bindValue($k,$v); + $stmt->execute(); + $row = $stmt->fetch(); + if (!$row) fail('Not found', ['kind'=>$kind,'id'=>$id], 404); + $rowOut = ['id' => $row[$idCol] ?? $id] + $row; + + // NEU: Spalten für HTML/JSON erkennen und top-level ausgeben + $htmlCol = first_existing($allCols, ['html','body','markup']); + $jsonCol = first_existing($allCols, ['content_json','json','content','structure_json']); + $topHtml = ($htmlCol && isset($row[$htmlCol])) ? (string)$row[$htmlCol] : null; + $topContent = ($jsonCol && isset($row[$jsonCol])) ? $row[$jsonCol] : null; + + respond([ + 'ok'=>true, + 'kind'=>$kind, + 'id'=>$rowOut['id'], + 'item'=>$rowOut, + 'data'=>$rowOut, + 'html'=>$topHtml, // <— wichtig für Vorschau + 'content'=>$topContent // optional (z. B. GrapesJS JSON) + ]); + } + + /* ---------- CREATE ---------- */ + case 'templates.create': + case 'sections.create': + case 'blocks.create': + case 'snippets.create': { + $auth = $requireAuth(); + $kind = explode('.', $action)[0]; + $t = $tableMap[$kind]; + [$idCol, $allCols] = $resolveIdCol($kind); + $cfg = $conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? (in_array('name',$allCols,true) ? 'name' : $idCol); + $descCol = $cfg['desc'] ?? first_existing($allCols, ['description','desc','descr']); + $catCol = $cfg['cat'] ?? first_existing($allCols, ['category','cat']); + $updCol = $cfg['upd'] ?? first_existing($allCols, ['updated_at','updated','updatedAt']); + $name = trim((string)val($in, ['name','title'], '')); + if ($name === '') fail('name required', null, 422); + $desc = (string)val($in, ['description','desc'], null); + $cat = (string)val($in, ['category','cat'], null); + $html = (string)val($in, ['html','body','markup'], null); + $json = val($in, ['content_json','json','content','structure_json'], null); + $settings = val($in, ['settings_json','settings'], null); + $templateId = val($in, ['template_id','tpl_id'], null); + $sectionId = val($in, ['section_id','sec_id'], null); + $blockId = val($in, ['block_id','blk_id'], null); + $data = [ $nameCol => $name ]; + if ($desc !== null && $descCol) $data[$descCol] = $desc; + if ($cat !== null && $catCol) $data[$catCol] = $cat; + $c = first_existing($allCols, ['html','body','markup']); if ($c && $html !== null) $data[$c]=$html; + $c = first_existing($allCols, ['content_json','json','content','structure_json']); if ($c && $json !== null) $data[$c]= is_string($json)?$json:json_encode($json, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + $c = first_existing($allCols, ['settings_json','settings']); if ($c && $settings !== null) $data[$c]= is_string($settings)?$settings:json_encode($settings, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + if ($templateId !== null && in_array('template_id',$allCols,true)) $data['template_id']=$templateId; + if ($sectionId !== null && in_array('section_id',$allCols,true)) $data['section_id']=$sectionId; + if ($blockId !== null && in_array('block_id',$allCols,true)) $data['block_id']=$blockId; + $data = $data + $tenantAssign($_SESSION['auth'] ?? [], $allCols); + $now = date('Y-m-d H:i:s'); + $createdCol = first_existing($allCols, ['created_at','created','createdAt']); + if ($createdCol) $data[$createdCol] = $now; + if ($updCol) $data[$updCol] = $now; + $fields = array_keys($data); + $place = array_map(fn($c)=>":$c", $fields); + $sql = "INSERT INTO `$t` (".implode(',', array_map(fn($c)=>"`$c`",$fields)).") VALUES (".implode(',', $place).")"; + $stmt = $pdo->prepare($sql); + foreach ($data as $k=>$v) $stmt->bindValue(":$k", $v); + $stmt->execute(); + $newId = $pdo->lastInsertId(); + $out = ['id'=>$newId,'name'=>$name]; + if ($desc !== null) $out['desc']=$desc; + if ($cat !== null) $out['category']=$cat; + respond(['ok'=>true,'kind'=>$kind,'id'=>$newId,'item'=>$out,'data'=>$out]); + } + + /* ---------- UPDATE ---------- */ + case 'templates.update': + case 'sections.update': + case 'blocks.update': + case 'snippets.update': { + $auth = $requireAuth(); + $kind = explode('.', $action)[0]; + $t = $tableMap[$kind]; + [$idCol, $allCols] = $resolveIdCol($kind); + $cfg = $conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? (in_array('name',$allCols,true) ? 'name' : $idCol); + $descCol = $cfg['desc'] ?? first_existing($allCols, ['description','desc','descr']); + $catCol = $cfg['cat'] ?? first_existing($allCols, ['category','cat']); + $updCol = $cfg['upd'] ?? first_existing($allCols, ['updated_at','updated','updatedAt']); + $id = $pullId($in); + if ($id === null || $id === '') fail('id required', null, 422); + $data = []; + $name = val($in, ['name','title'], null); + $desc = val($in, ['description','desc'], null); + $cat = val($in, ['category','cat'], null); + $html = val($in, ['html','body','markup'], null); + $json = val($in, ['content_json','json','content','structure_json'], null); + $settings = val($in, ['settings_json','settings'], null); + if ($name !== null) $data[$nameCol] = (string)$name; + if ($desc !== null && $descCol) $data[$descCol] = (string)$desc; + if ($cat !== null && $catCol) $data[$catCol] = (string)$cat; + $c = first_existing($allCols, ['html','body','markup']); if ($html !== null && $c) $data[$c]=(string)$html; + $c = first_existing($allCols, ['content_json','json','content','structure_json']); if ($json !== null && $c) $data[$c]= is_string($json)?$json:json_encode($json, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + $c = first_existing($allCols, ['settings_json','settings']); if ($settings !== null && $c) $data[$c]= is_string($settings)?$settings:json_encode($settings, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + $tpl = val($in, ['template_id','tpl_id'], null); if ($tpl !== null && in_array('template_id',$allCols,true)) $data['template_id']=$tpl; + $sec = val($in, ['section_id','sec_id'], null); if ($sec !== null && in_array('section_id',$allCols,true)) $data['section_id']=$sec; + $blk = val($in, ['block_id','blk_id'], null); if ($blk !== null && in_array('block_id',$allCols,true)) $data['block_id']=$blk; + if ($updCol) $data[$updCol] = date('Y-m-d H:i:s'); + if (!$data) fail('nothing to update', null, 422); + [$tw,$tp] = $tenantWhere($auth); + $set = []; foreach (array_keys($data) as $c) $set[] = "`$c` = :$c"; + $sql = "UPDATE `$t` SET ".implode(',',$set)." WHERE `$idCol` = :__id".$tw." LIMIT 1"; + $stmt = $pdo->prepare($sql); + foreach ($data as $k=>$v) $stmt->bindValue(":$k", $v); + $stmt->bindValue(':__id', $id); + foreach ($tp as $k=>$v) $stmt->bindValue($k,$v); + $stmt->execute(); + respond(['ok'=>true,'kind'=>$kind,'id'=>$id,'updated'=>array_keys($data)]); + } + + /* ---------- DELETE ---------- */ + case 'templates.delete': + case 'sections.delete': + case 'blocks.delete': + case 'snippets.delete': { + $auth = $requireAuth(); + $kind = explode('.', $action)[0]; + $t = $tableMap[$kind]; + [$idCol, $allCols] = $resolveIdCol($kind); + $id = $pullId($in); + if ($id === null || $id === '') fail('id required', null, 422); + [$tw,$tp] = $tenantWhere($auth); + $sql = "DELETE FROM `$t` WHERE `$idCol` = :__id".$tw." LIMIT 1"; + $stmt = $pdo->prepare($sql); + $stmt->bindValue(':__id', $id); + foreach ($tp as $k=>$v) $stmt->bindValue($k,$v); + $stmt->execute(); + respond(['ok'=>true,'kind'=>$kind,'id'=>$id,'deleted'=>true]); + } + + /* ---------- Platzhalter für kommende Features ---------- */ + case 'render.preview': + fail('Not implemented', 'Preview wird im Feature-Patch geliefert', 501); + case 'templates.test_send': + fail('Not implemented', 'Testversand wird im Feature-Patch geliefert', 501); + case 'export.render': + fail('Not implemented', 'Export-API wird im Feature-Patch geliefert', 501); + default: + fail('Unknown action', $action ?: 'missing', 404); + } +} catch (Throwable $e) { + fail('Server error', get_class($e).': '.$e->getMessage(), 500); +} diff --git a/public/api-original.php b/public/api-original.php new file mode 100644 index 0000000..cfb6653 --- /dev/null +++ b/public/api-original.php @@ -0,0 +1,1017 @@ +false,'error'=>$msg,'detail'=>$detail], $code); + +} + +function load_config(): array { + + $paths = [ + + __DIR__ . '/../inc/config.php', + + __DIR__ . '/inc/config.php', + + __DIR__ . '/config.php', + + ]; + + foreach ($paths as $p) { + + if (is_file($p)) { + + $conf = @include $p; + + if (is_array($conf)) return $conf; + + } + + } + + fail('Invalid config.php', 'config.php not found or not returning array', 500); + +} + +function cors(array $conf): void { + + $cors = $conf['cors'] ?? '*'; + + if ($cors) { + + header('Access-Control-Allow-Origin: ' . $cors); + + header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); + + header('Access-Control-Allow-Headers: Content-Type, Authorization'); + + header('Access-Control-Allow-Credentials: true'); + + } + + if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') respond(['ok'=>true]); + +} + +function get_input(): array { + + $data = []; + + $ct = $_SERVER['CONTENT_TYPE'] ?? ''; + + if (stripos($ct, 'application/json') !== false) { + + $raw = file_get_contents('php://input'); + + if ($raw !== false && $raw !== '') { + + $js = json_decode($raw, true); + + if (is_array($js)) $data = $js; + + } + + } + + foreach ($_POST as $k=>$v) $data[$k]=$v; + + foreach ($_GET as $k=>$v) if (!array_key_exists($k,$data)) $data[$k]=$v; + + return $data; + +} + +function val(array $in, $keys, $default=null) { + + if (!is_array($keys)) $keys = [$keys]; + + foreach ($keys as $k) if (array_key_exists($k,$in)) return $in[$k]; + + return $default; + +} + + + +/* ===================== DB helpers ===================== */ + +function pdo_templates(array $conf): PDO { + + if (!isset($conf['templates']) || !is_array($conf['templates'])) { + + fail('Missing templates DB config', null, 500); + + } + + $c = $conf['templates']; + + $host = $c['db_host'] ?? 'localhost'; + + $db = $c['db_name'] ?? ($c['database'] ?? ''); + + $user = $c['db_user'] ?? ($c['username'] ?? ''); + + $pass = $c['db_pass'] ?? ($c['password'] ?? ''); + + $charset = $c['db_charset'] ?? 'utf8mb4'; + + $port = $c['db_port'] ?? 3306; + + $dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset"; + + $opt = [ + + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + + ]; + + return new PDO($dsn, $user, $pass, $opt); + +} + +function verify_password(string $input, string $stored, array $authDbConf): bool { + + if (preg_match('~^\$2[aby]\$~', $stored) || strpos($stored, '$argon2') === 0) return password_verify($input, $stored); + + $legacy = strtolower($authDbConf['legacy'] ?? ''); + + if ($legacy === 'md5') return hash_equals($stored, md5($input)); + + if ($legacy === 'sha1') return hash_equals($stored, sha1($input)); + + if ($legacy === 'plain')return hash_equals($stored, $input); + + if (password_get_info($stored)['algo'] !== 0) return password_verify($input, $stored); + + return hash_equals($stored, $input); + +} + + + +/* ============ schema helpers ============ */ + +function table_columns(PDO $pdo, string $table): array { + + $cols = []; + + $stmt = $pdo->query("SHOW COLUMNS FROM `$table`"); + + foreach ($stmt->fetchAll() as $r) $cols[] = $r['Field']; + + return $cols; + +} + +function primary_key(PDO $pdo, string $table): ?string { + + $stmt = $pdo->prepare("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'"); + + $stmt->execute(); + + $row = $stmt->fetch(); + + return $row['Column_name'] ?? null; + +} + +function first_existing(array $columns, array $candidates): ?string { + + foreach ($candidates as $c) if (in_array($c, $columns, true)) return $c; + + return null; + +} + + + +/* ===================== Boot ===================== */ + +try { + + $conf = load_config(); + + cors($conf); + + if (session_status() === PHP_SESSION_NONE) session_start(); + + if (!empty($conf['auth']['cookie'])) { + + $c = $conf['auth']['cookie']; + + $params = session_get_cookie_params(); + + $params['lifetime'] = $c['lifetime'] ?? $params['lifetime']; + + $params['path'] = $c['path'] ?? $params['path']; + + $params['domain'] = $c['domain'] ?? $params['domain']; + + $params['secure'] = $c['secure'] ?? $params['secure']; + + $params['httponly'] = $c['httponly'] ?? $params['httponly']; + + if (isset($c['samesite'])) $params['samesite'] = $c['samesite']; + + session_set_cookie_params($params); + + } + + + + $in = get_input(); + + + + /* ---- Compat: ?resource=blocks&action=list -> blocks.list ---- */ + + $action = val($in, 'action', ''); + + $resource = val($in, 'resource', null); + + $allowedResources = ['templates','sections','blocks','snippets']; + + if ($resource && in_array($resource, $allowedResources, true) && strpos((string)$action, '.') === false) { + + $verb = strtolower((string)$action); + + if (in_array($verb, ['list','get','create','update','delete'], true)) $action = $resource.'.'.$verb; + + } + + + + /* ---- Multi-tenant ---- */ + + $multi = $conf['multi'] ?? []; + + $tenantCol = $multi['tenant_col'] ?? null; + + $mapSess = $multi['map_session_to'] ?? 'id'; // 'id'|'email'|'name' + + + + $tenantWhere = function(array $session) use ($tenantCol, $mapSess) { + + if (!$tenantCol) return ['', []]; + + if (!$session) return [' AND 1=0 ', []]; + + $val = $session[$mapSess] ?? null; + + if ($val===null || $val==='') return [' AND 1=0 ', []]; + + return [" AND `$tenantCol` = :__tenant", [':__tenant'=>$val]]; + + }; + + $tenantAssign = function(array $session, array $columns) use ($tenantCol, $mapSess) { + + if (!$tenantCol || !in_array($tenantCol, $columns, true)) return []; + + $val = $session[$mapSess] ?? null; + + return ($val===null || $val==='') ? [] : [$tenantCol => $val]; + + }; + + $requireAuth = function() { + + if (empty($_SESSION['auth'])) fail('Not authenticated', null, 401); + + return $_SESSION['auth']; + + }; + + + + /* ---- config tables/columns ---- */ + + $tables = $conf['tables'] ?? []; + + $tableMap = [ + + 'templates' => $tables['templates'] ?? 'emailtemplate_templates', + + 'sections' => $tables['sections'] ?? 'emailtemplate_sections', + + 'blocks' => $tables['blocks'] ?? 'emailtemplate_blocks', + + 'snippets' => $tables['snippets'] ?? 'emailtemplate_snippets', + + ]; + + $colsDefault = [ + + 'id' => 'id', + + 'name' => 'name', + + 'desc' => 'description', + + 'cat' => 'category', + + 'upd' => 'updated_at', + + ]; + + + + $pdo = pdo_templates($conf); + + + + /* helper: resolve id column for a table */ + + $resolveIdCol = function(string $kind) use ($conf, $colsDefault, $tableMap, $pdo) { + + $t = $tableMap[$kind]; + + $cfg = $conf['columns'][$kind] ?? []; + + $cols = table_columns($pdo, $t); + + $idCol = $cfg['id'] ?? (in_array('id', $cols, true) ? 'id' : primary_key($pdo, $t)); + + if (!$idCol) $idCol = 'id'; // fallback + + return [$idCol, $cols]; + + }; + + + + /* helper: accept many id aliases */ + + $pullId = function(array $src) { + + $aliases = ['id','item_id','template_id','tpl_id','section_id','sec_id','block_id','blk_id','snippet_id','snip_id']; + + foreach ($aliases as $a) if (isset($src[$a]) && $src[$a] !== '') return $src[$a]; + + return null; + + }; + + + + /* ===================== Router ===================== */ + + switch ($action) { + + case 'health': + + respond(['ok'=>true,'time'=>date('c')]); + + + + /* ---------- AUTH ---------- */ + + case 'auth.login': { + + $identifier = trim((string)val($in, ['username','user','email','login'], '')); + + $password = (string)val($in, ['password','pass','pwd'], ''); + + if ($identifier === '' || $password === '') fail('username/password required', null, 422); + + + + $authDb = $conf['auth']['db'] ?? []; + + $table = $authDb['table'] ?? 'emailtemplate_users'; + + $colUser = $authDb['col_user'] ?? 'email'; + + $colPass = $authDb['col_pass'] ?? 'password'; + + $colName = $authDb['col_name'] ?? 'name'; + + $colId = $authDb['col_id'] ?? 'id'; + + $colStatus = $authDb['col_status']?? null; + + $activeValues = $authDb['active_values'] ?? ['active','1',1]; + + + + $stmt = $pdo->prepare("SELECT * FROM `$table` WHERE `$colUser` = :u LIMIT 1"); + + $stmt->execute([':u'=>$identifier]); + + $row = $stmt->fetch(); + + if (!$row) fail('Invalid credentials', null, 401); + + + + if ($colStatus && isset($row[$colStatus])) { + + if (!in_array($row[$colStatus], $activeValues, true)) { + + fail('Account inactive', null, 403); + + } + + } + + + + $stored = (string)($row[$colPass] ?? ''); + + if ($stored === '' || !verify_password($password, $stored, $authDb)) { + + fail('Invalid credentials', null, 401); + + } + + + + $_SESSION['auth'] = [ + + 'id' => $row[$colId] ?? null, + + 'name' => $row[$colName] ?? ($row[$colUser] ?? $identifier), + + 'email' => $row[$colUser] ?? $identifier, + + 'at' => time(), + + ]; + + $token = base64_encode(hash('sha256', ($_SESSION['auth']['id'] ?? $identifier).'|'.session_id(), true)); + + respond(['ok'=>true,'user'=>$_SESSION['auth'],'token'=>$token]); + + } + + + + case 'auth.me': + + if (empty($_SESSION['auth'])) fail('Not authenticated', null, 401); + + respond(['ok'=>true,'user'=>$_SESSION['auth']]); + + + + case 'auth.logout': + + $_SESSION = []; + + if (session_id() !== '') session_destroy(); + + respond(['ok'=>true]); + + + + /* ---------- LIST (mit Parent-Filtern) ---------- */ + + case 'templates.list': + + case 'sections.list': + + case 'blocks.list': + + case 'snippets.list': { + + $auth = $requireAuth(); + + + + $kind = explode('.', $action)[0]; + + $t = $tableMap[$kind]; + + [$idCol, $allCols] = $resolveIdCol($kind); + + $cfg = $conf['columns'][$kind] ?? []; + + $nameCol = $cfg['name'] ?? (in_array('name',$allCols,true) ? 'name' : $idCol); + + $descCol = $cfg['desc'] ?? first_existing($allCols, ['description','desc','descr']); + + $catCol = $cfg['cat'] ?? first_existing($allCols, ['category','cat']); + + $updCol = $cfg['upd'] ?? first_existing($allCols, ['updated_at','updated','updatedAt']); + + + + $q = trim((string)val($in,'q','')); + + $limit = max(1, (int)val($in,'limit', 500)); + + $offset = max(0, (int)val($in,'offset',0)); + + + + $where = ' WHERE 1=1 '; + + $params = []; + + + + if ($q !== '') { + + $parts = ["`$nameCol` LIKE :q"]; + + if ($descCol) $parts[] = "`$descCol` LIKE :q"; + + if ($catCol) $parts[] = "`$catCol` LIKE :q"; + + $where .= " AND (".implode(' OR ', $parts).") "; + + $params[':q'] = '%'.$q.'%'; + + } + + + + // Parent-Filtern (falls Spalten existieren) + + $parentFilters = [ + + 'template_id' => val($in, ['template_id','tpl_id'], null), + + 'section_id' => val($in, ['section_id','sec_id'], null), + + 'block_id' => val($in, ['block_id','blk_id'], null), + + ]; + + foreach ($parentFilters as $col => $v) { + + if ($v === null || $v === '') continue; + + if (in_array($col, $allCols, true)) { $where .= " AND `$col` = :$col "; $params[":$col"] = $v; } + + } + + + + // Mandant + + [$tw,$tp] = $tenantWhere($auth); + + $where .= $tw; foreach ($tp as $k=>$v) $params[$k]=$v; + + + + $order = $updCol ? " ORDER BY `$updCol` DESC " : " ORDER BY `$nameCol` ASC "; + + $sql = "SELECT * FROM `$t` $where $order LIMIT :off,:lim"; + + $stmt = $pdo->prepare($sql); + + foreach ($params as $k=>$v) $stmt->bindValue($k,$v,is_int($v)?PDO::PARAM_INT:PDO::PARAM_STR); + + $stmt->bindValue(':off',$offset,PDO::PARAM_INT); + + $stmt->bindValue(':lim',$limit,PDO::PARAM_INT); + + $stmt->execute(); + + $rows = $stmt->fetchAll(); + + + + $out = []; + + foreach ($rows as $r) { + + $item = [ + + 'id' => $r[$idCol] ?? null, + + 'name' => $r[$nameCol] ?? null, + + ]; + + if ($descCol && isset($r[$descCol])) $item['desc'] = $r[$descCol]; + + if ($catCol && isset($r[$catCol])) $item['category'] = $r[$catCol]; + + if ($updCol && isset($r[$updCol])) $item['updated_at'] = $r[$updCol]; + + $out[] = $item; + + } + + respond(['ok'=>true,'kind'=>$kind,'items'=>$out,'data'=>$out,'count'=>count($out),'offset'=>$offset,'limit'=>$limit]); + + } + + + + /* ---------- GET (JETZT mit top-level html/content) ---------- */ + + case 'templates.get': + + case 'sections.get': + + case 'blocks.get': + + case 'snippets.get': { + + $auth = $requireAuth(); + + + + $kind = explode('.', $action)[0]; + + $t = $tableMap[$kind]; + + [$idCol, $allCols] = $resolveIdCol($kind); + + + + $id = $pullId($in); + + if ($id === null || $id === '') fail('id required', null, 422); + + + + [$tw,$tp] = $tenantWhere($auth); + + $sql = "SELECT * FROM `$t` WHERE `$idCol` = :id".$tw." LIMIT 1"; + + $stmt = $pdo->prepare($sql); + + $stmt->bindValue(':id', $id); + + foreach ($tp as $k=>$v) $stmt->bindValue($k,$v); + + $stmt->execute(); + + $row = $stmt->fetch(); + + if (!$row) fail('Not found', ['kind'=>$kind,'id'=>$id], 404); + + + + $rowOut = ['id' => $row[$idCol] ?? $id] + $row; + + + + // NEU: Spalten für HTML/JSON erkennen und top-level ausgeben + + $htmlCol = first_existing($allCols, ['html','body','markup']); + + $jsonCol = first_existing($allCols, ['content_json','json','content','structure_json']); + + $topHtml = ($htmlCol && isset($row[$htmlCol])) ? (string)$row[$htmlCol] : null; + + $topContent = ($jsonCol && isset($row[$jsonCol])) ? $row[$jsonCol] : null; + + + + respond([ + + 'ok'=>true, + + 'kind'=>$kind, + + 'id'=>$rowOut['id'], + + 'item'=>$rowOut, + + 'data'=>$rowOut, + + 'html'=>$topHtml, // <— wichtig für Vorschau + + 'content'=>$topContent // optional (z. B. GrapesJS JSON) + + ]); + + } + + + + /* ---------- CREATE ---------- */ + + case 'templates.create': + + case 'sections.create': + + case 'blocks.create': + + case 'snippets.create': { + + $auth = $requireAuth(); + + + + $kind = explode('.', $action)[0]; + + $t = $tableMap[$kind]; + + [$idCol, $allCols] = $resolveIdCol($kind); + + $cfg = $conf['columns'][$kind] ?? []; + + $nameCol = $cfg['name'] ?? (in_array('name',$allCols,true) ? 'name' : $idCol); + + $descCol = $cfg['desc'] ?? first_existing($allCols, ['description','desc','descr']); + + $catCol = $cfg['cat'] ?? first_existing($allCols, ['category','cat']); + + $updCol = $cfg['upd'] ?? first_existing($allCols, ['updated_at','updated','updatedAt']); + + + + $name = trim((string)val($in, ['name','title'], '')); + + if ($name === '') fail('name required', null, 422); + + + + $desc = (string)val($in, ['description','desc'], null); + + $cat = (string)val($in, ['category','cat'], null); + + $html = (string)val($in, ['html','body','markup'], null); + + $json = val($in, ['content_json','json','content','structure_json'], null); + + $settings = val($in, ['settings_json','settings'], null); + + + + $templateId = val($in, ['template_id','tpl_id'], null); + + $sectionId = val($in, ['section_id','sec_id'], null); + + $blockId = val($in, ['block_id','blk_id'], null); + + + + $data = [ $nameCol => $name ]; + + if ($desc !== null && $descCol) $data[$descCol] = $desc; + + if ($cat !== null && $catCol) $data[$catCol] = $cat; + + + + $c = first_existing($allCols, ['html','body','markup']); if ($c && $html !== null) $data[$c]=$html; + + $c = first_existing($allCols, ['content_json','json','content','structure_json']); if ($c && $json !== null) $data[$c]= is_string($json)?$json:json_encode($json, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + + $c = first_existing($allCols, ['settings_json','settings']); if ($c && $settings !== null) $data[$c]= is_string($settings)?$settings:json_encode($settings, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + + + + if ($templateId !== null && in_array('template_id',$allCols,true)) $data['template_id']=$templateId; + + if ($sectionId !== null && in_array('section_id',$allCols,true)) $data['section_id']=$sectionId; + + if ($blockId !== null && in_array('block_id',$allCols,true)) $data['block_id']=$blockId; + + + + $data = $data + $tenantAssign($_SESSION['auth'] ?? [], $allCols); + + + + $now = date('Y-m-d H:i:s'); + + $createdCol = first_existing($allCols, ['created_at','created','createdAt']); + + if ($createdCol) $data[$createdCol] = $now; + + if ($updCol) $data[$updCol] = $now; + + + + $fields = array_keys($data); + + $place = array_map(fn($c)=>":$c", $fields); + + $sql = "INSERT INTO `$t` (".implode(',', array_map(fn($c)=>"`$c`",$fields)).") VALUES (".implode(',', $place).")"; + + $stmt = $pdo->prepare($sql); + + foreach ($data as $k=>$v) $stmt->bindValue(":$k", $v); + + $stmt->execute(); + + $newId = $pdo->lastInsertId(); + + + + $out = ['id'=>$newId,'name'=>$name]; + + if ($desc !== null) $out['desc']=$desc; + + if ($cat !== null) $out['category']=$cat; + + respond(['ok'=>true,'kind'=>$kind,'id'=>$newId,'item'=>$out,'data'=>$out]); + + } + + + + /* ---------- UPDATE ---------- */ + + case 'templates.update': + + case 'sections.update': + + case 'blocks.update': + + case 'snippets.update': { + + $auth = $requireAuth(); + + + + $kind = explode('.', $action)[0]; + + $t = $tableMap[$kind]; + + [$idCol, $allCols] = $resolveIdCol($kind); + + $cfg = $conf['columns'][$kind] ?? []; + + $nameCol = $cfg['name'] ?? (in_array('name',$allCols,true) ? 'name' : $idCol); + + $descCol = $cfg['desc'] ?? first_existing($allCols, ['description','desc','descr']); + + $catCol = $cfg['cat'] ?? first_existing($allCols, ['category','cat']); + + $updCol = $cfg['upd'] ?? first_existing($allCols, ['updated_at','updated','updatedAt']); + + + + $id = $pullId($in); + + if ($id === null || $id === '') fail('id required', null, 422); + + + + $data = []; + + $name = val($in, ['name','title'], null); + + $desc = val($in, ['description','desc'], null); + + $cat = val($in, ['category','cat'], null); + + $html = val($in, ['html','body','markup'], null); + + $json = val($in, ['content_json','json','content','structure_json'], null); + + $settings = val($in, ['settings_json','settings'], null); + + + + if ($name !== null) $data[$nameCol] = (string)$name; + + if ($desc !== null && $descCol) $data[$descCol] = (string)$desc; + + if ($cat !== null && $catCol) $data[$catCol] = (string)$cat; + + $c = first_existing($allCols, ['html','body','markup']); if ($html !== null && $c) $data[$c]=(string)$html; + + $c = first_existing($allCols, ['content_json','json','content','structure_json']); if ($json !== null && $c) $data[$c]= is_string($json)?$json:json_encode($json, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + + $c = first_existing($allCols, ['settings_json','settings']); if ($settings !== null && $c) $data[$c]= is_string($settings)?$settings:json_encode($settings, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + + + + $tpl = val($in, ['template_id','tpl_id'], null); if ($tpl !== null && in_array('template_id',$allCols,true)) $data['template_id']=$tpl; + + $sec = val($in, ['section_id','sec_id'], null); if ($sec !== null && in_array('section_id',$allCols,true)) $data['section_id']=$sec; + + $blk = val($in, ['block_id','blk_id'], null); if ($blk !== null && in_array('block_id',$allCols,true)) $data['block_id']=$blk; + + + + if ($updCol) $data[$updCol] = date('Y-m-d H:i:s'); + + if (!$data) fail('nothing to update', null, 422); + + + + [$tw,$tp] = $tenantWhere($auth); + + $set = []; foreach (array_keys($data) as $c) $set[] = "`$c` = :$c"; + + $sql = "UPDATE `$t` SET ".implode(',',$set)." WHERE `$idCol` = :__id".$tw." LIMIT 1"; + + $stmt = $pdo->prepare($sql); + + foreach ($data as $k=>$v) $stmt->bindValue(":$k", $v); + + $stmt->bindValue(':__id', $id); + + foreach ($tp as $k=>$v) $stmt->bindValue($k,$v); + + $stmt->execute(); + + + + respond(['ok'=>true,'kind'=>$kind,'id'=>$id,'updated'=>array_keys($data)]); + + } + + + + /* ---------- DELETE ---------- */ + + case 'templates.delete': + + case 'sections.delete': + + case 'blocks.delete': + + case 'snippets.delete': { + + $auth = $requireAuth(); + + + + $kind = explode('.', $action)[0]; + + $t = $tableMap[$kind]; + + [$idCol, $allCols] = $resolveIdCol($kind); + + + + $id = $pullId($in); + + if ($id === null || $id === '') fail('id required', null, 422); + + + + [$tw,$tp] = $tenantWhere($auth); + + $sql = "DELETE FROM `$t` WHERE `$idCol` = :__id".$tw." LIMIT 1"; + + $stmt = $pdo->prepare($sql); + + $stmt->bindValue(':__id', $id); + + foreach ($tp as $k=>$v) $stmt->bindValue($k,$v); + + $stmt->execute(); + + + + respond(['ok'=>true,'kind'=>$kind,'id'=>$id,'deleted'=>true]); + + } + + + + /* ---------- Platzhalter für kommende Features ---------- */ + + case 'render.preview': + + fail('Not implemented', 'Preview wird im Feature-Patch geliefert', 501); + + case 'templates.test_send': + + fail('Not implemented', 'Testversand wird im Feature-Patch geliefert', 501); + + case 'export.render': + + fail('Not implemented', 'Export-API wird im Feature-Patch geliefert', 501); + + + + default: + + fail('Unknown action', $action ?: 'missing', 404); + + } + + + +} catch (Throwable $e) { + + fail('Server error', get_class($e).': '.$e->getMessage(), 500); + +} diff --git a/public/api.php b/public/api.php new file mode 100644 index 0000000..3541a75 --- /dev/null +++ b/public/api.php @@ -0,0 +1,15 @@ +run(); diff --git a/public/api.php.txt b/public/api.php.txt new file mode 100644 index 0000000..255b234 --- /dev/null +++ b/public/api.php.txt @@ -0,0 +1,492 @@ + false, + 'error' => 'internal', + 'type' => get_class($e), + 'msg' => $e->getMessage(), + 'file' => basename($e->getFile()), + 'line' => $e->getLine(), + ], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + exit; +}); + +/* ------------------------- Helpers ------------------------- */ +function json_out(array $data, int $code = 200): void { + http_response_code($code); + header('Content-Type: application/json; charset=utf-8'); + echo json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + exit; +} +function in_json(): array { + $raw = file_get_contents('php://input') ?: ''; + if ($raw === '') return []; + $j = json_decode($raw, true); + return is_array($j) ? $j : []; +} + +/* ------------------------- Config laden ------------------------- */ +// Parent /inc/config.php (wie von dir beschrieben) +$cfgFile = dirname(__DIR__) . '/inc/config.php'; +if (!is_file($cfgFile)) { + json_out(['ok'=>false,'error'=>'config_missing','hint'=>'config.php nicht gefunden','path'=>$cfgFile], 500); +} +$CFG = include $cfgFile; +if (!is_array($CFG)) { + json_out(['ok'=>false,'error'=>'config_invalid','hint'=>'config.php muss ein Array zurückgeben'], 500); +} +$ENV = $CFG['env'] ?? 'prod'; + +/* ------------------------- PDO-Factories ------------------------- */ +function pdo_from_cfg(?array $dbc): ?PDO { + if (!$dbc) return null; + $dsn = sprintf( + 'mysql:host=%s;dbname=%s;charset=%s', + $dbc['db_host'] ?? 'localhost', + $dbc['db_name'] ?? '', + $dbc['db_charset']?? 'utf8mb4' + ); + return new PDO($dsn, $dbc['db_user'] ?? '', $dbc['db_pass'] ?? '', [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ]); +} +$pdoTpl = pdo_from_cfg($CFG['templates'] ?? null); // Template-Daten +$pdoCust = pdo_from_cfg(($CFG['customers'] ?? null) ?: ($CFG['templates'] ?? null)); // Kunden/Users + +$TPL_DB = $CFG['templates']['db_name'] ?? null; // für information_schema + +function has_column(PDO $pdo, ?string $db, string $table, string $col): bool { + if (!$db) return false; + $st = $pdo->prepare("SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA=:db AND TABLE_NAME=:t AND COLUMN_NAME=:c + LIMIT 1"); + $st->execute([':db'=>$db, ':t'=>$table, ':c'=>$col]); + return (bool)$st->fetchColumn(); +} + +/* ------------------------- Auth (Helper oder Fallback) ------------------------- */ +$authFile = dirname(__DIR__) . '/inc/auth_helpers.php'; +$useHelpers = is_file($authFile); +if ($useHelpers) { + require_once $authFile; // stellt auth_start_session(), auth_require(), auth_logout(), require_role() bereit +} else { + // interner Fallback – kompatibel zu deinen Erwartungen + function auth_start_session(array $CFG): void { + $secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'); + session_set_cookie_params([ + 'httponly' => true, + 'samesite' => 'Lax', + 'secure' => $secure, + 'path' => rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/' + ]); + session_name('et_session'); + if (session_status() !== PHP_SESSION_ACTIVE) session_start(); + } + function auth_require(array $CFG): void { + auth_start_session($CFG); + if (empty($_SESSION['user'])) { + json_out(['ok'=>false,'error'=>'unauthorized'], 401); + } + } + function auth_logout(array $CFG): void { + auth_start_session($CFG); + $_SESSION = []; + if (ini_get('session.use_cookies')) { + $p = session_get_cookie_params(); + setcookie(session_name(), '', time()-42000, $p['path'], $p['domain'] ?? '', $p['secure'], $p['httponly']); + } + session_destroy(); + } + function require_role(array $CFG, array $roles): void { + auth_start_session($CFG); + $r = $_SESSION['user']['role'] ?? null; + if (!$r || !in_array($r, $roles, true)) json_out(['ok'=>false,'error'=>'forbidden'], 403); + } +} + +/* ------------------------- Routing + Legacy-Mapping ------------------------- */ +$action = $_GET['action'] ?? $_POST['action'] ?? null; + +// Alt: ?resource=blocks&action=list|get|create|update|delete|sync +if (!empty($_GET['resource'])) { + $res = (string)$_GET['resource']; + $act = (string)($_GET['action'] ?? ''); + $allowed = ['templates','sections','blocks','snippets','assets','template_items','section_items']; + if (in_array($res, $allowed, true)) { + if ($act === 'list') $action = $res.'.list'; + if ($act === 'get') $action = $res.'.get'; + if ($act === 'create') $action = $res.'.create'; + if ($act === 'update') $action = $res.'.update'; + if ($act === 'delete') $action = $res.'.delete'; + if ($act === 'sync') $action = $res.'.sync'; + } +} + +/* ------------------------- Meta/Health ------------------------- */ +if ($action === 'health' || $action === 'ping') json_out(['ok'=>true,'env'=>$ENV,'time'=>date('c')]); +if ($action === 'version') json_out(['ok'=>true,'version'=>'2025-09-05','env'=>$ENV]); + +/* ------------------------- Diagnose (leichtgewichtig) ------------------------- */ +if ($action === 'debug.diag') { + $diag = [ + 'php' => PHP_VERSION, + 'pdo' => extension_loaded('pdo'), + 'pdo_mysql'=> extension_loaded('pdo_mysql'), + 'cfg' => ['templates'=>!!$pdoTpl, 'customers'=>!!$pdoCust], + ]; + json_out(['ok'=>true,'diag'=>$diag]); +} + +/* ------------------------- STAGING: User-Debug ------------------------- */ +if (in_array($action, ['debug.users','debug.users.check','debug.users.setpass','debug.users.peek'], true)) { + if ($ENV !== 'staging') json_out(['ok'=>false,'error'=>'forbidden'], 403); + if (!$pdoCust) json_out(['ok'=>false,'error'=>'customers_db_not_configured'], 500); + + if ($action === 'debug.users') { + $email = isset($_GET['email']) ? trim((string)$_GET['email']) : ''; + if ($email !== '') { + $st = $pdoCust->prepare("SELECT id, customer_id, email, role, is_active, created_at, updated_at + FROM customer_users WHERE email=:email"); + $st->execute([':email'=>$email]); + $rows = $st->fetchAll(); + } else { + $st = $pdoCust->query("SELECT id, customer_id, email, role, is_active, created_at, updated_at + FROM customer_users ORDER BY id DESC LIMIT 50"); + $rows = $st->fetchAll(); + } + json_out(['ok'=>true,'items'=>$rows]); + } + + if ($action === 'debug.users.check') { + $in = in_json(); + $email = trim((string)($in['email'] ?? '')); + $pass = (string)($in['password'] ?? ''); + if ($email==='' || $pass==='') json_out(['ok'=>false,'error'=>'missing_params'], 400); + $st = $pdoCust->prepare("SELECT id, customer_id, email, password_hash, role, is_active FROM customer_users + WHERE email=:email LIMIT 1"); + $st->execute([':email'=>$email]); + $u = $st->fetch(); + if (!$u) json_out(['ok'=>true,'exists'=>false,'password_match'=>false]); + json_out(['ok'=>true,'exists'=>true,'password_match'=>password_verify($pass,$u['password_hash'])]); + } + + if ($action === 'debug.users.setpass') { + $in = in_json(); + $email = trim((string)($in['email'] ?? '')); + $pass = (string)($in['password'] ?? ''); + if ($email==='' || $pass==='') json_out(['ok'=>false,'error'=>'missing_params'], 400); + $st = $pdoCust->prepare("SELECT id FROM customer_users WHERE email=:email LIMIT 1"); + $st->execute([':email'=>$email]); + $u = $st->fetch(); + if (!$u) json_out(['ok'=>false,'error'=>'user_not_found'], 404); + $hash = password_hash($pass, PASSWORD_DEFAULT); + $upd = $pdoCust->prepare("UPDATE customer_users SET password_hash=:h, is_active=1 WHERE id=:id"); + $upd->execute([':h'=>$hash, ':id'=>$u['id']]); + json_out(['ok'=>true,'set'=>true]); + } + + if ($action === 'debug.users.peek') { + $email = isset($_GET['email']) ? trim((string)$_GET['email']) : ''; + if ($email==='') json_out(['ok'=>false,'error'=>'missing_email'], 400); + $st = $pdoCust->prepare("SELECT id, customer_id, email, LENGTH(password_hash) len + FROM customer_users WHERE email=:email"); + $st->execute([':email'=>$email]); + json_out(['ok'=>true,'user'=>$st->fetch()]); + } +} + +/* ------------------------- AUTH: Login / Logout / Me ------------------------- */ +if ($action === 'auth.login') { + $in = in_json(); + $email = trim(strtolower((string)($in['email'] ?? ''))); + $pass = (string)($in['password'] ?? ''); + if ($email==='' || $pass==='') json_out(['ok'=>false,'error'=>'missing_credentials'], 400); + if (!$pdoCust) json_out(['ok'=>false,'error'=>'customers_db_not_configured'], 500); + + // Mehrfachkunden mit gleicher Mail erlauben → best match über password_verify + $st = $pdoCust->prepare("SELECT cu.id, cu.customer_id, cu.email, cu.password_hash, cu.role, cu.is_active, + c.slug AS customer_slug, c.plan, c.status + FROM customer_users cu + JOIN customers c ON c.id = cu.customer_id + WHERE cu.email=:email"); + $st->execute([':email'=>$email]); + $rows = $st->fetchAll(); + + $match = null; + foreach ($rows as $r) { + if ((int)$r['is_active'] === 1 && !empty($r['password_hash']) && password_verify($pass, $r['password_hash'])) { + $match = $r; break; + } + } + if (!$match) json_out(['ok'=>false,'error'=>'invalid_credentials'], 401); + if (($match['status'] ?? 'active') !== 'active') json_out(['ok'=>false,'error'=>'customer_inactive'], 403); + + auth_start_session($CFG); + $_SESSION['user'] = [ + 'id' => (int)$match['id'], + 'email' => $match['email'], + 'role' => $match['role'], + 'customer_id' => (int)$match['customer_id'], + 'customer_slug' => $match['customer_slug'], + 'plan' => $match['plan'] ?? null, + ]; + json_out(['ok'=>true,'user'=>$_SESSION['user']]); +} + +if ($action === 'auth.logout') { auth_logout($CFG); json_out(['ok'=>true]); } + +if ($action === 'auth.me') { + auth_start_session($CFG); + json_out(['ok'=>!empty($_SESSION['user']), 'user'=>$_SESSION['user'] ?? null]); +} + +/* ------------------------- ab hier: geschützt ------------------------- */ +$public = ['auth.login','auth.logout','auth.me','health','ping','version','debug.diag','debug.users','debug.users.check','debug.users.setpass','debug.users.peek']; +if (!in_array($action, $public, true)) auth_require($CFG); + +$customerId = (int)($_SESSION['user']['customer_id'] ?? 0); + +/* ------------------------- Templates ------------------------- */ +if ($action === 'templates.list') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $st = $pdoTpl->prepare("SELECT id, name, updated_at + FROM emailtemplate_templates + WHERE customer_id = :cid + ORDER BY updated_at DESC, id DESC + LIMIT 1000"); + $st->execute([':cid'=>$customerId]); + json_out(['ok'=>true,'items'=>$st->fetchAll()]); +} + +if ($action === 'templates.get') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $id = isset($_GET['id']) ? (int)$_GET['id'] : (int)($_POST['id'] ?? 0); + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + $hasHtml = has_column($pdoTpl, $TPL_DB, 'emailtemplate_templates', 'html'); + $cols = $hasHtml ? "id, customer_id, name, html, updated_at" : "id, customer_id, name, NULL AS html, updated_at"; + $st = $pdoTpl->prepare("SELECT $cols FROM emailtemplate_templates WHERE id=:id AND customer_id=:cid LIMIT 1"); + $st->execute([':id'=>$id, ':cid'=>$customerId]); + $row = $st->fetch(); + if (!$row) json_out(['ok'=>false,'error'=>'not_found'], 404); + json_out(['ok'=>true,'item'=>$row]); +} + +if ($action === 'templates.create') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in = in_json(); + $name = trim((string)($in['name'] ?? '')); + $html = (string)($in['html'] ?? ''); + if ($name==='') json_out(['ok'=>false,'error'=>'name_required'], 400); + $hasHtml = has_column($pdoTpl, $TPL_DB, 'emailtemplate_templates', 'html'); + + if ($hasHtml) { + $st = $pdoTpl->prepare("INSERT INTO emailtemplate_templates (customer_id,name,html,created_at,updated_at) + VALUES (:cid,:name,:html,NOW(),NOW())"); + $st->execute([':cid'=>$customerId, ':name'=>$name, ':html'=>$html]); + } else { + $st = $pdoTpl->prepare("INSERT INTO emailtemplate_templates (customer_id,name,created_at,updated_at) + VALUES (:cid,:name,NOW(),NOW())"); + $st->execute([':cid'=>$customerId, ':name'=>$name]); + } + json_out(['ok'=>true,'id'=>(int)$pdoTpl->lastInsertId()]); +} + +if ($action === 'templates.update') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in = in_json(); + $id = (int)($in['id'] ?? 0); + $name = array_key_exists('name',$in) ? trim((string)$in['name']) : null; + $html = array_key_exists('html',$in) ? (string)$in['html'] : null; + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + + $hasHtml = has_column($pdoTpl, $TPL_DB, 'emailtemplate_templates', 'html'); + $sets=[]; $p=[':id'=>$id, ':cid'=>$customerId]; + if ($name!==null) { $sets[]="name=:name"; $p[':name']=$name; } + if ($hasHtml && $html!==null) { $sets[]="html=:html"; $p[':html']=$html; } + if (!$sets) json_out(['ok'=>false,'error'=>'nothing_to_update'], 400); + + $sql = "UPDATE emailtemplate_templates SET ".implode(',',$sets).", updated_at=NOW() WHERE id=:id AND customer_id=:cid"; + $st = $pdoTpl->prepare($sql); + $st->execute($p); + json_out(['ok'=>true,'updated'=>$st->rowCount()]); +} + +if ($action === 'templates.delete') { + require_role($CFG, ['owner','admin']); + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in = in_json(); $id=(int)($in['id'] ?? 0); + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + $pdoTpl->beginTransaction(); + try { + $pdoTpl->prepare("DELETE FROM emailtemplate_template_items WHERE template_id=:id AND customer_id=:cid")->execute([':id'=>$id, ':cid'=>$customerId]); + $pdoTpl->prepare("DELETE FROM emailtemplate_templates WHERE id=:id AND customer_id=:cid")->execute([':id'=>$id, ':cid'=>$customerId]); + $pdoTpl->commit(); + json_out(['ok'=>true]); + } catch (Throwable $e) { $pdoTpl->rollBack(); throw $e; } +} + +/* ------------------------- Sections ------------------------- */ +if ($action === 'sections.list') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $templateId = isset($_GET['template_id']) ? (int)$_GET['template_id'] : 0; + if ($templateId>0) { + $st = $pdoTpl->prepare("SELECT id, template_id, name, z_index, type, updated_at + FROM emailtemplate_sections + WHERE customer_id=:cid AND template_id=:tid + ORDER BY z_index ASC, id ASC + LIMIT 1000"); + $st->execute([':cid'=>$customerId, ':tid'=>$templateId]); + } else { + $st = $pdoTpl->prepare("SELECT id, template_id, name, z_index, type, updated_at + FROM emailtemplate_sections + WHERE customer_id=:cid + ORDER BY template_id ASC, z_index ASC, id ASC + LIMIT 1000"); + $st->execute([':cid'=>$customerId]); + } + json_out(['ok'=>true,'items'=>$st->fetchAll()]); +} + +if ($action === 'sections.get') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $id = isset($_GET['id']) ? (int)$_GET['id'] : (int)($_POST['id'] ?? 0); + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + $st = $pdoTpl->prepare("SELECT id, customer_id, template_id, name, z_index, type, updated_at + FROM emailtemplate_sections + WHERE id=:id AND customer_id=:cid + LIMIT 1"); + $st->execute([':id'=>$id, ':cid'=>$customerId]); + $row = $st->fetch(); + if (!$row) json_out(['ok'=>false,'error'=>'not_found'], 404); + json_out(['ok'=>true,'item'=>$row]); +} + +/* ------------------------- Blocks ------------------------- */ +if ($action === 'blocks.list') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $st = $pdoTpl->prepare("SELECT id, name, category, updated_at + FROM emailtemplate_blocks + WHERE customer_id=:cid + ORDER BY name ASC + LIMIT 1000"); + $st->execute([':cid'=>$customerId]); + json_out(['ok'=>true,'items'=>$st->fetchAll()]); +} + +if ($action === 'blocks.get') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $id = isset($_GET['id']) ? (int)$_GET['id'] : (int)($_POST['id'] ?? 0); + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + $st = $pdoTpl->prepare("SELECT id, customer_id, name, category, updated_at + FROM emailtemplate_blocks + WHERE id=:id AND customer_id=:cid + LIMIT 1"); + $st->execute([':id'=>$id, ':cid'=>$customerId]); + $row = $st->fetch(); + if (!$row) json_out(['ok'=>false,'error'=>'not_found'], 404); + json_out(['ok'=>true,'item'=>$row]); +} + +if ($action === 'blocks.create') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in=in_json(); $name=trim((string)($in['name']??'')); $cat=trim((string)($in['category']??'')); + if ($name==='') json_out(['ok'=>false,'error'=>'name_required'], 400); + $st=$pdoTpl->prepare("INSERT INTO emailtemplate_blocks (customer_id,name,category,created_at,updated_at) + VALUES (:cid,:name,COALESCE(NULLIF(:cat,''),'Default'),NOW(),NOW())"); + $st->execute([':cid'=>$customerId, ':name'=>$name, ':cat'=>$cat]); + json_out(['ok'=>true,'id'=>(int)$pdoTpl->lastInsertId()]); +} + +if ($action === 'blocks.update') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in=in_json(); $id=(int)($in['id']??0); $name=trim((string)($in['name']??'')); $cat=trim((string)($in['category']??'')); + if ($id<=0 || $name==='') json_out(['ok'=>false,'error'=>'invalid_params'], 400); + $st=$pdoTpl->prepare("UPDATE emailtemplate_blocks + SET name=:name, category=COALESCE(NULLIF(:cat,''),category), updated_at=NOW() + WHERE id=:id AND customer_id=:cid"); + $st->execute([':name'=>$name, ':cat'=>$cat, ':id'=>$id, ':cid'=>$customerId]); + json_out(['ok'=>true,'updated'=>$st->rowCount()]); +} + +if ($action === 'blocks.delete') { + require_role($CFG, ['owner','admin']); + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in=in_json(); $id=(int)($in['id']??0); + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + $st=$pdoTpl->prepare("DELETE FROM emailtemplate_blocks WHERE id=:id AND customer_id=:cid"); + $st->execute([':id'=>$id, ':cid'=>$customerId]); + json_out(['ok'=>true,'deleted'=>$st->rowCount()]); +} + +/* ------------------------- Snippets ------------------------- */ +if ($action === 'snippets.list') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $st=$pdoTpl->prepare("SELECT id, name, category, updated_at + FROM emailtemplate_snippets + WHERE customer_id=:cid + ORDER BY name ASC + LIMIT 1000"); + $st->execute([':cid'=>$customerId]); + json_out(['ok'=>true,'items'=>$st->fetchAll()]); +} + +if ($action === 'snippets.get') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $id = isset($_GET['id']) ? (int)$_GET['id'] : (int)($_POST['id'] ?? 0); + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + $st=$pdoTpl->prepare("SELECT id, customer_id, name, category, updated_at + FROM emailtemplate_snippets + WHERE id=:id AND customer_id=:cid + LIMIT 1"); + $st->execute([':id'=>$id, ':cid'=>$customerId]); + $row=$st->fetch(); + if (!$row) json_out(['ok'=>false,'error'=>'not_found'], 404); + json_out(['ok'=>true,'item'=>$row]); +} + +/* ------------------------- Assets (READ) ------------------------- */ +if ($action === 'assets.list') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $st=$pdoTpl->prepare("SELECT id, name, type, mime_type, size_bytes, public_url, updated_at + FROM emailtemplate_assets + WHERE customer_id=:cid + ORDER BY updated_at DESC, id DESC + LIMIT 200"); + $st->execute([':cid'=>$customerId]); + json_out(['ok'=>true,'items'=>$st->fetchAll()]); +} + +/* ------------------------- Editor-Referenzen (Placeholders) ------------------------- */ +if ($action === 'template_items.sync') { json_out(['ok'=>true]); } +if ($action === 'section_items.sync') { json_out(['ok'=>true]); } + +/* ------------------------- Render (Fallback) ------------------------- */ +if ($action === 'render.preview') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in = in_json(); + $templateId = (int)($in['template_id'] ?? 0); + if ($templateId<=0) json_out(['ok'=>false,'error'=>'template_id_required'], 400); + $st = $pdoTpl->prepare("SELECT id, name FROM emailtemplate_templates WHERE id=:id AND customer_id=:cid LIMIT 1"); + $st->execute([':id'=>$templateId, ':cid'=>$customerId]); + $tpl = $st->fetch(); + if (!$tpl) json_out(['ok'=>false,'error'=>'not_found'], 404); + $html = "\n
Preview okay.
"; + json_out(['ok'=>true, 'template'=>$tpl, 'html'=>$html]); +} + +/* ------------------------- Fallback ------------------------- */ +json_out(['ok'=>false,'error'=>'unknown_action','action'=>$action], 404); + diff --git a/public/assets/css/admin.css b/public/assets/css/admin.css new file mode 100644 index 0000000..03146f4 --- /dev/null +++ b/public/assets/css/admin.css @@ -0,0 +1,167 @@ +/* ============================================================ + Admin Theme (SCOPED) + - wirkt NUR unter bzw. .page-login + - keine globalen Resets (html/body/a/…) + - GrapesJS (gjs-…) wird nicht angetastet + ============================================================ */ + +/* ---- Farb- & UI-Variablen ---- */ +body.page-admin, +body.page-login { + --bg: #f7f7fb; + --panel: #ffffff; + --text: #222222; + --muted: #666666; + --border: #e7e7ee; + --accent: #5b7cff; + --accent-600:#3f5ff7; + --danger: #e74c3c; + --ok: #2ecc71; + + background: var(--bg); + color: var(--text); + font: 14px/1.45 system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji"; +} + +/* ---- Links / Text ---- */ +.page-admin a, +.page-login a { + color: inherit; + text-decoration: none; +} +.page-admin .muted, +.page-login .muted { color: var(--muted); } + +/* ---- Container ---- */ +.page-admin .container { max-width: 1200px; margin: 20px auto; padding: 0 16px; } + +/* ============================================================ + ADMIN (Dashboard, Listen, Editor-Rahmen) + ============================================================ */ + +/* ---- Topbar ---- */ +.page-admin .topbar { + display: flex; align-items: center; justify-content: space-between; + gap: 10px; padding: 10px 16px; background: rgba(255,255,255,.9); + backdrop-filter: saturate(140%) blur(6px); + border-bottom: 1px solid var(--border); + position: sticky; top: 0; z-index: 50; +} +.page-admin .brand { font-size: 16px; margin: 0; font-weight: 600; } +.page-admin .topbar .right { display: flex; gap: 8px; align-items: center; } + +/* ---- Buttons (leicht, neutral) ---- */ +.page-admin .btn { + display:inline-flex; align-items:center; gap:.5rem; + padding:.38rem .75rem; border-radius:.7rem; + border:1px solid var(--border); background:#fff; + font-size:.9rem; cursor:pointer; transition:.15s background-color, .15s border-color, .15s box-shadow; +} +.page-admin .btn:hover { background:#f8fafc; } +.page-admin .btn-primary { border-color: var(--accent); background: var(--accent); color:#fff; } +.page-admin .btn-primary:hover { background: var(--accent-600); border-color: var(--accent-600); } +.page-admin .btn-danger { border-color:#fecaca; color:#b91c1c; } +.page-admin .btn-danger:hover { background:#fef2f2; } + +/* ---- Chips ---- */ +.page-admin .chip { + display:inline-flex; align-items:center; gap:.35rem; + padding:.15rem .55rem; border-radius:999px; + background:#f1f5f9; color:#334155; font-size:.75rem; border:1px solid var(--border); +} +.page-admin .chip .dot { width:.5rem; height:.5rem; border-radius:999px; background:#64748b; } + +/* ---- Cards & Rows ---- */ +.page-admin .card { + background: var(--panel); border:1px solid var(--border); + border-radius: 12px; padding: 16px; margin-bottom: 16px; +} +.page-admin .row { + display:flex; gap:12px; align-items:center; justify-content:space-between; flex-wrap:wrap; +} +.page-admin .row .left, +.page-admin .row .right { display:flex; gap:10px; align-items:center; } + +/* ---- Tabs (Header-Tabs) ---- */ +.page-admin .tab { + padding:8px 12px; border:1px solid var(--border); + border-radius:999px; background:#fff; cursor:pointer; font-size:.9rem; +} +.page-admin .tab.active { background:var(--accent); border-color:var(--accent); color:#fff; } + +/* ---- Tabellen/Listen ---- */ +.page-admin .list { + width:100%; border-collapse: separate; border-spacing: 0; background: #fff; + border:1px solid var(--border); border-radius: 12px; overflow: hidden; +} +.page-admin .list thead th { + text-align:left; padding:10px 12px; background:#fafafe; color:#374151; font-weight:600; font-size:.92rem; + border-bottom:1px solid var(--border); +} +.page-admin .list tbody td { + padding:10px 12px; border-bottom:1px solid var(--border); vertical-align: top; font-size:.92rem; +} +.page-admin .list tbody tr:hover td { background:#fafafa; } +.page-admin .empty { + text-align:center; padding:28px; color:var(--muted); font-size:.95rem; background:#fff; border:1px dashed var(--border); border-radius:12px; +} + +/* ---- Formulare ---- */ +.page-admin input[type="text"], +.page-admin input[type="email"], +.page-admin input[type="number"], +.page-admin input[type="search"], +.page-admin textarea, +.page-admin select { + width:100%; border:1px solid var(--border); border-radius:10px; padding:10px 12px; margin:8px 0; background:#fff; + font: inherit; color: inherit; +} +.page-admin textarea { min-height: 110px; resize: vertical; } +.page-admin label { display:block; margin:12px 0 6px; color:#334155; font-size:.92rem; } + +/* ---- Dialoge / Backdrop ---- */ +.page-admin dialog::backdrop { background: rgba(15,23,42,.35); } +.page-admin .dialog-head { + display:flex; align-items:center; gap:10px; justify-content:space-between; + padding:10px 14px; background:var(--panel); border-bottom:1px solid var(--border); +} + +/* ---- Preview Dialog ---- */ +.page-admin .previewDialog { width:min(900px,95vw); border:none; border-radius:12px; padding:0; overflow:hidden; } +.page-admin .previewHead { display:flex; justify-content:space-between; align-items:center; gap:10px; padding:10px 14px; background:var(--panel); border-bottom:1px solid var(--border); } +.page-admin .previewBody { height:min(70vh,700px); } +.page-admin .previewBody iframe { width:100%; height:100%; border:0; background:#fafafa; } + +/* ---- Utility ---- */ +.page-admin .truncate { max-width:22rem; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; } +.page-admin .hidden { display:none !important; } +.page-admin .muted-12 { font-size:12px; color:var(--muted); } + +/* ============================================================ + LOGIN (Karte in der Mitte) + ============================================================ */ + +.page-login .loginWrap { display:grid; place-items:center; min-height: 55vh; } +.page-login .loginCard { + width:min(420px,95vw); background: var(--panel); border:1px solid var(--border); + border-radius:16px; box-shadow:0 10px 30px rgba(2,6,23,.06); padding:28px; +} +.page-login h1 { margin:0 0 8px; font-size:20px; } +.page-login p { margin:0 0 18px; color:#475569; } +.page-login label { display:block; margin:12px 0 6px; color:#334155; } +.page-login input[type="email"], +.page-login input[type="text"], +.page-login input[type="password"] { + width:100%; padding:12px; border:1px solid #cbd5e1; border-radius:10px; font-size:15px; background:#fff; +} +.page-login .btn-login { + width:100%; margin-top:16px; padding:12px; border:0; border-radius:12px; + background:#111827; color:#fff; font-weight:600; cursor:pointer; +} +.page-login .mini { margin-top:10px; text-align:center; } +.page-login .hint { font-size:12px; color:var(--muted); } + +/* ABSOLUTER UI-FIX: Versteckt die hartnäckige Bibliothek-Kategorie */ +.gjs-block-category[data-id="Bibliothek"] { + display: none !important; +} diff --git a/public/assets/css/app.css b/public/assets/css/app.css new file mode 100644 index 0000000..f91b27f --- /dev/null +++ b/public/assets/css/app.css @@ -0,0 +1,25 @@ +/* Auth-Guard: bis zum erfolgreichen auth.me nichts anzeigen */ +html.auth-pending header, +html.auth-pending main { + display: none !important; +} + +:root { color-scheme: light; } + +.btn{ + display:inline-flex;align-items:center;gap:.5rem; + padding:.35rem .7rem;border-radius:.7rem;border:1px solid #e5e7eb; + background:#fff;font-size:.9rem;cursor:pointer; +} +.btn:hover{background:#f8fafc} +.btn-danger{border-color:#fecaca;color:#b91c1c} +.btn-danger:hover{background:#fef2f2} + +.chip{display:inline-flex;align-items:center;gap:.35rem;padding:.15rem .5rem;border-radius:999px;background:#f1f5f9;color:#334155;font-size:.75rem;border:1px solid #e5e7eb} +.chip .dot{width:.5rem;height:.5rem;border-radius:999px;background:#64748b} + +dialog::backdrop{background:rgba(15,23,42,.3)} +#toast-root{z-index:2147483647} +.truncate{max-width:22rem;overflow:hidden;white-space:nowrap;text-overflow:ellipsis} +.hidden{display:none} + diff --git a/public/assets/css/toast.css b/public/assets/css/toast.css new file mode 100644 index 0000000..9dcd978 --- /dev/null +++ b/public/assets/css/toast.css @@ -0,0 +1,48 @@ +/* assets/css/toast.css */ +/* Works whether the root is in or inside a (top layer) */ +.toast-root, #toast-root { + position: fixed; /* relative to viewport even inside dialog's top layer */ + inset: 0; + pointer-events: none; + z-index: 2147483647; + font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; +} + +.toast { + pointer-events: auto; + position: fixed; + right: 16px; + top: 16px; + min-width: 240px; + max-width: 420px; + border-radius: 12px; + padding: 12px 14px; + box-shadow: 0 10px 30px rgba(2, 6, 23, .25), 0 2px 8px rgba(2,6,23,.12); + color: #0f172a; + background: #ffffff; + border: 1px solid rgba(148,163,184,.35); + display: flex; + align-items: flex-start; + gap: 10px; + animation: toast-slide-in .18s ease-out; +} + +.toast + .toast { margin-top: 12px; } + +.toast .icon { font-size: 18px; line-height: 1; margin-top: 2px; } +.toast .content { flex: 1; font-size: 14px; line-height: 1.35; } +.toast .close { appearance: none; border: 0; background: transparent; font-size: 16px; color: #475569; cursor: pointer; padding: 2px 4px; } + +/* success (green) by default */ +.toast.success { border-color: #86efac; background: #ecfdf5; color: #065f46; } +.toast.success .icon { color: #10b981; } + +/* error (red) */ +.toast.error { border-color: #fecaca; background: #fff1f2; color: #7f1d1d; } +.toast.error .icon { color: #ef4444; } + +@keyframes toast-slide-in { + from { transform: translateY(-6px); opacity: 0; } + to { transform: translateY(0); opacity: 1; } +} + diff --git a/public/assets/js/api.js b/public/assets/js/api.js new file mode 100644 index 0000000..c7953ac --- /dev/null +++ b/public/assets/js/api.js @@ -0,0 +1,109 @@ +// assets/js/api.js +const API = "api.php"; + +/** ---- intern: Hilfen ---- */ +function withTs(url) { + const sep = url.includes("?") ? "&" : "?"; + return `${url}${sep}t=${Date.now()}`; // no-store Absicherung +} + +async function parseJsonSafe(res) { + const text = await res.text(); + try { + return JSON.parse(text); + } catch (e) { + console.error("API: invalid JSON", { status: res.status, text }); + return null; + } +} + +// ... oberer Teil unverändert ... + +/** zentraler Fetch-Wrapper: Credentials, no-store, 401→Login */ +async function apiFetch(url, init = {}) { + const res = await fetch(withTs(url), { + credentials: "include", + cache: "no-store", + ...init, + }); + if (res.status === 401) { + window.location.href = "/login.php"; + throw new Error("unauthorized"); + } + return res; +} + +/** ---- Public API ---- */ + +/** + * Action-Call: + * - apiAction('auth.me') + * - apiAction('sections.list', { method:'GET', data:{ template_id: 123 } }) + * - apiAction('templates.create', { method:'POST', data:{ name:'...' } }) + */ +export async function apiAction( + action, + { method = "GET", data = null, headers = {} } = {} +) { + let url = `${API}?action=${encodeURIComponent(action)}`; + const init = { method, headers: { ...headers } }; + + // GET/HEAD → data als Query-String anhängen (kein Body!) + if ((method === "GET" || method === "HEAD") && data && typeof data === "object") { + const params = new URLSearchParams(); + for (const [k, v] of Object.entries(data)) { + if (v !== undefined && v !== null) params.append(k, String(v)); + } + const qs = params.toString(); + if (qs) url += `&${qs}`; + } else if (data != null) { + init.headers["Content-Type"] = "application/json"; + init.body = JSON.stringify(data); + } + + const res = await apiFetch(url, init); + return await parseJsonSafe(res); +} + +// ... Rest (apiList, apiCreate, apiUpdate, apiDelete, toast) unverändert ... + +/** + * Listen-Helper für Ressourcen – ruft `${res}.list` auf. + * Optional kannst du query-Objekte mitgeben, z.B. { template_id: 123 } für sections. + */ +export async function apiList(res, query = {}) { + const q = new URLSearchParams(query); + const qs = q.toString() ? `&${q.toString()}` : ""; + const r = await apiAction(`${res}.list`, { method: "GET" }); + // Falls du query serverseitig brauchst (z.B. template_id), nutze eine Action-Variante: + // return await apiAction(`${res}.list`, { method:"GET", data: query }); + return r?.items ?? []; +} + +/** GET by id: nur nutzen, wenn du eine `${res}.get`-Action hast */ +export async function apiGet(res, id) { + return await apiAction(`${res}.get`, { method: "GET", data: { id } }); +} + +/** CREATE / UPDATE / DELETE – sprechen `${res}.create|update|delete` an */ +export async function apiCreate(res, payload) { + return await apiAction(`${res}.create`, { method: "POST", data: payload }); +} + +export async function apiUpdate(res, id, payload) { + return await apiAction(`${res}.update`, { method: "POST", data: { id, ...payload } }); +} + +export async function apiDelete(res, id) { + return await apiAction(`${res}.delete`, { method: "POST", data: { id } }); +} + +/** optionaler Toast-Fallback (keine harte Abhängigkeit) */ +export function toast(msg, ok = true, opts = {}) { + if (window.Toast?.show) { + window.Toast.show(msg, { type: ok ? "success" : "error", duration: 2200, ...opts }); + } else { + (ok ? console.log : console.error)(msg); + } +} + diff --git a/public/assets/js/app.js b/public/assets/js/app.js new file mode 100644 index 0000000..4caf1ac --- /dev/null +++ b/public/assets/js/app.js @@ -0,0 +1,84 @@ +// assets/js/app.js +import { initTabs } from './ui-tabs.js'; +import { initLists } from './ui-list.js'; +import { initCreate } from './ui-create.js'; +import { initEditor } from './ui-editor.js'; +import { mountLogoutButton, ensureFloatingLogout } from './ui-auth.js'; +import { apiAction } from './api.js'; + + +/** + * Zeigt die App erst, wenn Auth validiert ist. + * Wichtig: KEIN finally → nur im Erfolgsfall UI freigeben (verhindert Flashing für Gäste). + */ +async function ensureAuthenticated() { + try { + const me = await apiAction('auth.me', { method: 'GET' }); + if (!me?.ok || !me?.user) { + window.location.href = '/login.php'; + return false; + } + // ✅ nur für eingeloggte Nutzer: UI freigeben + document.documentElement.classList.remove('auth-pending'); + const appRoot = document.getElementById('app'); + if (appRoot && appRoot.hasAttribute('hidden')) appRoot.removeAttribute('hidden'); + return true; + } catch { + // apiAction leitet bei 401 ohnehin um + return false; + } +} + +function initAppFeatures() { + initTabs(); + initLists(); + initCreate(); + initEditor(); + + // Logout-Buttons + mountLogoutButton('#btn-logout', { redirect: '/login.php' }); + ensureFloatingLogout({ redirect: '/login.php' }); +} + +// Sync-Nachrichten aus dem Editor-Iframe (unverändert, aber mit credentials) +async function handleEditorMessages(ev) { + const msg = ev.data || {}; + if (msg.source !== 'email-editor' || msg.type !== 'save') return; + + try { + const ctx = window.__currentEditorCtx || {}; + const id = ctx.id; + const mode = (ctx.mode || msg.mode || '').toLowerCase(); + const refs = Array.isArray(msg.refs) ? msg.refs : []; + if (!id || !mode) return; + + if (mode === 'templates') { + await fetch('./api.php?resource=template_items&action=sync', { + method: 'POST', + credentials: 'include', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ template_id: id, items: refs }) + }); + } else if (mode === 'sections') { + await fetch('./api.php?resource=section_items&action=sync', { + method: 'POST', + credentials: 'include', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ section_id: id, items: refs.filter(r => r.ref_type === 'block') }) + }); + } + } catch (e) { + console.error('refs sync failed', e); + } +} + + + +document.addEventListener('DOMContentLoaded', async () => { + const ok = await ensureAuthenticated(); + if (!ok) return; // Gast → Redirect, UI bleibt verborgen + initAppFeatures(); // Eingeloggt → App initialisieren +}); + +window.addEventListener('message', handleEditorMessages); + diff --git a/public/assets/js/bridge/blocks-api (Kopie).js b/public/assets/js/bridge/blocks-api (Kopie).js new file mode 100644 index 0000000..a7e59f0 --- /dev/null +++ b/public/assets/js/bridge/blocks-api (Kopie).js @@ -0,0 +1,207 @@ +/* /assets/js/bridge/blocks-api.js (SCHRITT 16: Finaler Stabilitäts-Fix) */ +(function (B) { + + // 🛑 KRITISCHER FIX: Nur minimale Prüfung, um synchrone Initialisierung zu garantieren + if (!B || typeof grapesjs === 'undefined') { + console.warn("[BRIDGE-API] blocks-api.js: BridgeParts (B) oder GrapesJS fehlt. Exit."); + return; + } + + const PluginName = 'bridge-blocks-api'; + const qs = new URLSearchParams(location.search); + B.EDITOR_MODE = (qs.get('mode') || 'templates').toUpperCase(); + console.log(`%c[${PluginName} - INIT] Editor Modus: ${B.EDITOR_MODE} (SCHRITT 16 - FINAL STABLE)`, 'color: #1E90FF; font-weight: bold;'); + + const TARGET_CAT_ID = 'custom'; + const PLACEHOLDER_ID = 'api-placeholder-loading'; + const REFERENCE_COMPONENT_TYPE = 'library-reference'; + +// -------------------------------------------------------- +// (1) Kern-Logik: Platzhalter und Kategorien registrieren (SYNCHRON) +// -------------------------------------------------------- + const preRegisterCategoriesAndPlaceholders = (editor) => { + const bm = editor.BlockManager; + + bm.add(PLACEHOLDER_ID, { + label: 'Lade Custom-Blöcke...', + category: TARGET_CAT_ID, + content: '
⚙️ Custom-Blöcke werden geladen...
', + attributes: { class: 'gjs-block__api-placeholder' }, + }); + + const cat = bm.getCategories().get(TARGET_CAT_ID); + if (!cat) { + bm.addCategory(TARGET_CAT_ID, { label: 'Custom', open: true, order: 1 }); + } + console.log(`%c[${PluginName}] Platzhalter und Kategorie registriert.`, 'color: #008000;'); + }; + +// -------------------------------------------------------- +// (2) Komponenten-Logik (ASYNCHRONER WORKAROUND & FIX) +// -------------------------------------------------------- + const registerReferenceComponent = (editor) => { + const domc = editor.DomComponents; + const defaultType = domc.getType('default'); + + if (!defaultType) return; + + // KRITISCHER WORKAROUND: Registrierung wird minimal verzögert + setTimeout(() => { + domc.addType(REFERENCE_COMPONENT_TYPE, { + model: defaultType.model.extend({ + + init() { + // Setze die Attribute sicher im init() (Fix für "defaults" TypeError) + if (this.get('type') !== REFERENCE_COMPONENT_TYPE) { + this.set('type', REFERENCE_COMPONENT_TYPE); + this.set('tagName', 'div'); + this.set('lib-kind', ''); + this.set('lib-id', ''); + } + + this.on('change:lib-kind change:lib-id', this.reloadComponentContent); + const editorInstance = this.em.get('Editor'); + if (editorInstance && this.get('lib-id')) { + // Prüft hier nur auf getApiItem, da es für die Referenz-Komponente essenziell ist + if(B.getApiItem) { + editorInstance.on('load', this.reloadComponentContent.bind(this), { once: true }); + } else { + console.warn(`[${PluginName}] B.getApiItem fehlt. Inhalte für 'library-reference' können nicht geladen werden.`); + } + } + }, + + reloadComponentContent(opts = {}) { + const kind = this.get('lib-kind'); + const id = this.get('lib-id'); + + if (!kind || !id) { + this.set('content', '
🛑 Fehler: API-Referenz unvollständig.
'); + return; + } + + if (!B.getApiItem) { + this.set('content', '
🛑 Fehler: API-Kernfunktion getApiItem fehlt.
'); + return; + } + + B.getApiItem(kind, id) + .then(item => { + if (item && item.html) { + this.set('content', item.html); + console.log(`[${PluginName}] Geladenen Inhalt für ${kind}/${id} gesetzt.`); + } else { + this.set('content', `
🛑 Fehler: Inhalt für ${kind}/${id} nicht gefunden.
`); + } + }) + .catch(error => { + console.error(`[${PluginName}] Fehler beim Abruf von ${kind}/${id}:`, error); + this.set('content', `
🛑 Fehler beim Laden von ${kind}/${id}.
`); + }); + }, + }, {}), + view: defaultType.view, + }); + + console.log(`%c[${PluginName}] Komponententyp '${REFERENCE_COMPONENT_TYPE}' ASYNCHRON registriert.`, 'color: #008000;'); + + }, 0); + }; + +// -------------------------------------------------------- +// (3) Asynchrone Logik: API-Blöcke registrieren (FINAL CLEAN) +// -------------------------------------------------------- + const loadAndRegisterApiBlocks = (editor) => { + const bm = editor.BlockManager; + const targetCatId = TARGET_CAT_ID; + + // KRITISCHER FIX: Stelle sicher, dass der Platzhalter existiert. + if (!bm.get(PLACEHOLDER_ID)) { + bm.add(PLACEHOLDER_ID, { + label: 'Lade Custom-Blöcke...', + category: targetCatId, + content: '
⚙️ Custom-Blöcke werden geladen...
', + attributes: { class: 'gjs-block__api-placeholder' }, + }); + console.log(`%c[${PluginName}] Platzhalter erneut hinzugefügt (Überlebens-Check).`, 'color: orange;'); + } + + // 🛑 NEUER CHECK: Prüfe die fetch*-Funktionen erst HIER. + if (!B.fetchSections || !B.fetchBlocks || !B.fetchSnippets) { + console.error(`%c[${PluginName}] FEHLER: Eine der API-Ladefunktionen (fetchSections/Blocks/Snippets) fehlt.`, 'color: #dc3545; font-weight: bold;'); + // Platzhalter bleibt, da die Kategorie sonst verschwindet. + return; + } + + + // Explizite Promise.all mit allen fetch*-Funktionen + Promise.all([ + B.fetchSections().then(items => items.map(i => ({ ...i, kind: 'sections' }))), + B.fetchBlocks().then(items => items.map(i => ({ ...i, kind: 'blocks' }))), + B.fetchSnippets().then(items => items.map(i => ({ ...i, kind: 'snippets' }))) + ]) + .then(results => { + // Führe alle Ergebnisse zu einem flachen Array zusammen + const apiItems = results.flat().filter(item => item && item.id); + + // Array-Ausgabe zur Bestätigung der Daten + console.log(`%c[${PluginName}] API-Daten Array:`, 'color: #9400D3; font-weight: bold;', apiItems); + + console.log(`%c[${PluginName}] API-Daten geladen: ${apiItems.length} Blöcke/Sektionen gefunden.`, 'color: #1E90FF; font-weight: bold;'); + + if (apiItems.length === 0) { + // Platzhalter bleibt, um die leere Kategorie sichtbar zu halten. + console.warn(`[${PluginName}] Keine API-Daten gefunden, Platzhalter bleibt (leer) erhalten.`); + } else { + apiItems.forEach(item => { + const blockId = `lib-${item.kind}-${item.id}`; + const label = item.name || item.label || 'Unbenannter Block'; + const itemKindUpper = item.kind.toUpperCase(); + + const blockDefinition = { + label: label, + category: targetCatId, + content: { + type: REFERENCE_COMPONENT_TYPE, + attributes: { 'lib-kind': item.kind, 'lib-id': item.id }, + }, + attributes: { 'title': itemKindUpper }, + media: item.preview_url ? `` : '', + }; + bm.add(blockId, blockDefinition); + }); + + // Platzhalter entfernen, da Blöcke erfolgreich geladen wurden + bm.remove(PLACEHOLDER_ID); + console.log(`%c[${PluginName}] ${apiItems.length} API-Blöcke registriert. Platzhalter entfernt.`, 'color: #008000; font-weight: bold;'); + } + }) + .catch(error => { + console.error(`%c[${PluginName}] FEHLER beim Laden der API-Blöcke:`, 'color: #dc3545; font-weight: bold;', error); + // Platzhalter entfernen, um nicht im ewigen Ladezustand zu bleiben. + bm.remove(PLACEHOLDER_ID); + }); + }; + + +// -------------------------------------------------------- +// (4) Plugin-Funktion +// -------------------------------------------------------- + const plugin = (editor) => { + preRegisterCategoriesAndPlaceholders(editor); + registerReferenceComponent(editor); + + editor.on('load', () => { + console.log(`%c[${PluginName}] GrapesJS 'load' Event: Starte asynchrones Laden der API-Blöcke.`, 'color: #1E90FF; font-weight: bold;'); + loadAndRegisterApiBlocks(editor); + }); + }; + +// -------------------------------------------------------- +// (5) Export an Bridge Core +// -------------------------------------------------------- + if (B.registerGrapesJSPlugin) { + B.registerGrapesJSPlugin(PluginName, plugin); + } + +})(window.BridgeParts || (window.BridgeParts = {})); diff --git a/public/assets/js/bridge/blocks-api.js b/public/assets/js/bridge/blocks-api.js new file mode 100644 index 0000000..4ba3c2d --- /dev/null +++ b/public/assets/js/bridge/blocks-api.js @@ -0,0 +1,270 @@ +/* /assets/js/bridge/blocks-api.js (UI-KERN UND KOMPONENTEN-SCHICHT) */ + +(function (B) { + + const PluginName = 'bridge-blocks-api'; + + if (!B || typeof grapesjs === 'undefined') { + console.warn(`%c[${PluginName}] %cBridgeParts (B) oder GrapesJS fehlt. Exit.`, 'color:orange; font-weight:bold;', 'color:inherit;'); + return; + } + + B.LOG_CONFIG = B.LOG_CONFIG || { PLUGINS: {} }; + B.LOG_CONFIG.PLUGINS[PluginName] = true; + + const log = (message, color = '#1E90FF', type = 'info', force = false) => B.log(PluginName, message, color, type, force); + + const qs = new URLSearchParams(location.search); + B.EDITOR_MODE = (qs.get('mode') || 'templates').toUpperCase(); + log(`START: SKRIPT-AUSFÜHRUNG GESTARTET. Editor Modus: ${B.EDITOR_MODE}.`, '#DC143C'); + + const TARGET_CAT_ID = 'custom'; + const PLACEHOLDER_ID = 'api-placeholder-loading'; + const REFERENCE_COMPONENT_TYPE = 'library-reference'; + + // --- NEUE KONSTANTEN FÜR SPEICHERN-LOGIK --- + // Annahme: ID der aktuellen Seite/Template ist global in B verfügbar + const CURRENT_ENTITY_ID = B.CURRENT_ENTITY_ID || qs.get('id') || 0;  + // Annahme: Basis-URL der API ist in B verfügbar + const API_KERNEL_URL = B.API_KERNEL_URL || '/api/ApiKernel.php';  + // ------------------------------------------- + +// -------------------------------------------------------- +// (1) Kern-Logik: Platzhalter und Kategorien registrieren (SYNCHRON) +// -------------------------------------------------------- + const preRegisterCategoriesAndPlaceholders = (editor) => { + const bm = editor.BlockManager; + + bm.add(PLACEHOLDER_ID, { + label: 'Lade Custom-Blöcke...', + category: TARGET_CAT_ID, + content: '
⚙️ Custom-Blöcke werden geladen...
', + attributes: { class: 'gjs-block__api-placeholder' }, + }); + + const cat = bm.getCategories().get(TARGET_CAT_ID); + if (!cat) { + bm.addCategory(TARGET_CAT_ID, { label: 'Custom', open: true, order: 1 }); + } + log('Platzhalter und Kategorie registriert.', '#008000'); + }; + +// -------------------------------------------------------- +// (2) Komponenten-Logik (ASYNCHRONER WORKAROUND & FIX) +// -------------------------------------------------------- + const registerReferenceComponent = (editor) => { + const domc = editor.DomComponents; + const defaultType = domc.getType('default'); + + if (!defaultType) return; + + log(`Starte Registrierung des Komponententyps '${REFERENCE_COMPONENT_TYPE}'.`, '#1E90FF'); + + setTimeout(() => { + domc.addType(REFERENCE_COMPONENT_TYPE, { + model: defaultType.model.extend({ + + getCachedApiItem(kind, id) { + const key = `${kind}-${id}`; + const item = B.ApiItemCache?.[key];  + return item; + }, + + init() { + const id = this.get('lib-id'); + const kind = this.get('lib-kind'); + const startContent = this.get('startContent'); + + log(`INIT LÄUFT. lib-kind: ${kind}, lib-id: ${id}. (Bestätigung des Element-Drops/Load)`, '#8A2BE2'); + + if (startContent) { + // 💡 NEUER FIX: Beim Drop nur die 'content'-Eigenschaft setzen, NICHT als Unterkomponenten parsen + this.set('content', startContent);   + this.unset('startContent'); + log(`INHALT erfolgreich als REINES HTML aus 'startContent' gesetzt: ${kind}/${id}`, '#008000'); + } + + this.on('change:lib-kind change:lib-id', this.reloadComponentContent); + + if (!startContent && kind && id) { + this.reloadComponentContent({ forced: true, reason: 'INIT_LOAD_FROM_CACHE' }); + } + }, + + reloadComponentContent(opts = {}) { + const kind = this.get('lib-kind'); + const id = this.get('lib-id'); + const reason = opts.reason || (opts.forced ? 'FORCED_INTERNAL' : 'EVENT_CHANGE'); + log(`RELOAD START (${reason}). Kind: ${kind}, ID: ${id}.`, '#8A2BE2'); + + if (!kind || !id) { + log('RELOAD FEHLER: lib-kind oder lib-id fehlt. Setze Fehler-Placeholder.', '#dc3545', 'error', true); + // 💡 FIX: Setze reinen HTML-String als content + this.set('content', '
🛑 Fehler: API-Referenz unvollständig.
'); + return; + } + + const item = this.getCachedApiItem(kind, id); + + if (item && (item.html || item.content)) { + const content = item.html || item.content; + // 💡 FIX: Verwende set('content', ...) statt components(...) + // Dadurch wird der Inhalt als reiner HTML-String in die Komponente gesetzt + // und nicht als neue, bearbeitbare GrapesJS-Komponenten geparst. + this.set('content', content); + log(`INHALT erfolgreich für ${kind}/${id} geladen und als REINER HTML-STRING gesetzt.`, '#008000'); + } else { + log(`RELOAD FEHLER: Inhalt für ${kind}/${id} NICHT im Cache gefunden.`, '#dc3545', 'error', true); + // 💡 FIX: Setze reinen HTML-HTML-String als content + this.set('content', `
🛑 Fehler: Inhalt für ${kind}/${id} nicht im Cache gefunden.
`); + } + }, + }, { + isComponent: el => el && el.nodeType === 1 && el.hasAttribute('lib-id'), + extend: 'default', + model: { + defaults: { + ...defaultType.model.prototype.defaults, + // 🛑 KRITISCHE FIXES FÜR REFERENZEN + components: '', // Darf keine Unterkomponenten haben, die geparst werden + editable: false, // ❌ Nicht bearbeitbar (Inline-Editierung verhindern) + removable: true, + draggable: true, + copyable: true, + droppable: false, // ❌ Darf keine anderen Komponenten aufnehmen + // --------------------------------- + traits: [ + { type: 'text', name: 'lib-id', label: 'Library ID', changeProp: true }, + { type: 'text', name: 'lib-kind', label: 'Library Kind', changeProp: true }, + ], + 'lib-id': '', + 'lib-kind': '', + startContent: '', + content: '', // Inhalt, der das gerenderte HTML hält + } + } + }), + // 💡 WICHTIG: Die View muss den Content als reinen HTML-Inhalt rendern (defaultType macht das). + view: defaultType.view,  + }); + + log(`Komponententyp '${REFERENCE_COMPONENT_TYPE}' ASYNCHRON registriert.`, '#008000'); + }, 0); + }; + +// -------------------------------------------------------- +// (3) HINZUGEFÜGT: Speichern-Befehl (Command) +// -------------------------------------------------------- + const registerSaveCommand = (editor) => { + + editor.Commands.add('save-data', { + run: function(editor, sender) { + // 💡 FIX: Sicherstellen, dass sender existiert und die 'set'-Methode hat (nur bei Buttons) + if (sender && typeof sender.set === 'function') { + sender.set('active', 0); // Schaltet den Button nach dem Klick ab + } + + if (!CURRENT_ENTITY_ID) { + log('SAVE ABORT', 'Speichern abgebrochen: Keine Entity ID verfügbar (B.CURRENT_ENTITY_ID fehlt oder ist 0).', 'red', 'error', true); + alert('Speichern fehlgeschlagen: Die ID des aktuellen Elements fehlt.'); + return; + } + + // 1. Daten extrahieren + const htmlContent = editor.getHtml() + ''; + // 2. KRITISCH: Holt die JSON-Repräsentation des Editors + const jsonProjectData = editor.getProjectData();  + + log('SAVE START', 'Starte Speichern des Inhalts an die API...', '#FF4500'); + + // 3. Daten für den POST-Request vorbereiten + const dataToSend = { + action: 'blocks.update', // Oder 'templates.update', je nach Entity + id: CURRENT_ENTITY_ID,  + html: htmlContent, + // 🚨 KRITISCH: Korrigiert auf 'json_content' für das PHP-Backend + json_content: jsonProjectData,  + name: B.CURRENT_ENTITY_NAME || 'Unbenannt', // Optional + }; + + // 4. API-Aufruf (fetch) + fetch(API_KERNEL_URL, { + method: 'POST', + headers: { + // Wichtig: JSON-Daten senden + 'Content-Type': 'application/json',  + }, + body: JSON.stringify(dataToSend), + }) + .then(response => { + if (!response.ok) { + log('SAVE FAILED (HTTP)', `Speichern fehlgeschlagen: HTTP-Status ${response.status}.`, 'red', 'error', true); + throw new Error(`HTTP Error: ${response.status}`); + } + return response.json(); + }) + .then(data => { + if (data.ok === false) { + log('SAVE FAILED (API)', `Speichern fehlgeschlagen: API-Fehler: ${data.error || 'Unbekannt'}`, 'red', 'error', true); + alert(`Speichern fehlgeschlagen: ${data.error || 'API-Fehler'}`); + } else { + log('SAVE SUCCESS', 'Speichern erfolgreich. JSON-Daten wurden gesendet.', '#008000', 'info', true); + // 💡 HINZUGEFÜGT: Bestätigung an das Elternfenster senden + window.parent.postMessage({ source: 'editor', type: 'save:success' }, '*'); + editor.refresh(); // Optional: Editor-Ansicht aktualisieren + } + }) + .catch(error => { + log('SAVE FAILED (FETCH)', `FEHLER beim Speichern: ${error.message}`, 'red', 'error', true); + alert('Speichern fehlgeschlagen. Netzwerk- oder JSON-Parse-Fehler.'); + }); + } + }); + + // Eventuell den Button in der Toolbar registrieren (falls noch nicht geschehen) + editor.Panels.addButton('options', { + id: 'save-data', + className: 'fa fa-floppy-o', + command: 'save-data',  + attributes: { title: 'Speichern (Strg/Cmd + S)' } + }); + + // Tastenkürzel für Speichern hinzufügen + editor.Keymaps.add('ctrl-s', 'save-data', 'ctrl+s'); + editor.Keymaps.add('cmd-s', 'save-data', 'cmd+s'); + + log('Speichern-Command und Button/Keymap registriert.', '#FF4500'); + }; + +// -------------------------------------------------------- +// (4) Plugin-Funktion (AKTUALISIERT) +// -------------------------------------------------------- + const plugin = (editor) => { + preRegisterCategoriesAndPlaceholders(editor); + registerReferenceComponent(editor); + registerSaveCommand(editor); // HINZUGEFÜGT: Speichern-Logik + + editor.on('load', () => { + log("GrapesJS 'load' Event: Delegiere asynchrones Laden der API-Blöcke an library-api.", '#1E90FF'); + if (B.loadAndRegisterApiBlocks) {  + setTimeout(() => { + B.loadAndRegisterApiBlocks(editor); + }, 500); + } else { + log(`FEHLER: B.loadAndRegisterApiBlocks ist nicht definiert. library-api.js wurde nicht geladen oder nicht richtig initialisiert.`, 'red', 'error', true); + editor.BlockManager.remove(PLACEHOLDER_ID); + } + }); + }; + +// -------------------------------------------------------- +// (5) Export an Bridge Core (unverändert) +// -------------------------------------------------------- + if (B.registerGrapesJSPlugin) { + B.registerGrapesJSPlugin(PluginName, plugin); + log(`PLUGIN REGISTER: '${PluginName}' zur Bridge Plugin Registry hinzugefügt.`, '#008000'); + } else { + log(`FEHLER: B.registerGrapesJSPlugin fehlt. Plugin-Registrierung gescheitert.`, 'red', 'error', true); + } + +})(window.BridgeParts || (window.BridgeParts = {})); diff --git a/public/assets/js/bridge/blocks-custom.js b/public/assets/js/bridge/blocks-custom.js new file mode 100644 index 0000000..ea39d67 --- /dev/null +++ b/public/assets/js/bridge/blocks-custom.js @@ -0,0 +1,131 @@ +/* /assets/js/bridge/blocks-custom.js (FINAL & LOG-KONTROLLIERT) */ +(function () { + + const PluginName = 'blocks-custom'; + const B = window.BridgeParts || (window.BridgeParts = {}); + + // ---------------------------------------------------------------------- + // 🎯 NEU: LOKALE LOG-KONFIGURATION UND WRAPPER + // ---------------------------------------------------------------------- + // Setzen Sie dies auf 'false' in der config.js oder hier, um alle Logs NUR für dieses Plugin zu deaktivieren. + if (B.LOG_CONFIG && B.LOG_CONFIG.PLUGINS) { + B.LOG_CONFIG.PLUGINS[PluginName] = false; // <-- HIER IST IHR SCHALTER + } + + // NEUER LOKALER WRAPPER, der die zentrale B.log Funktion verwendet: + const log = (type, message, color = '#FFD700', logType = 'info', force = false) => { + if (typeof B.log === 'function') { + B.log(PluginName, `[${type}] ${message}`, color, logType, force); + } else if (logType === 'error') { + // Fallback für kritische Fehler, wenn B.log fehlt + console.error(`%c[${PluginName} - ${type}] %c${message}`, `color:red; font-weight:bold;`, 'color:inherit;'); + } + }; + // ---------------------------------------------------------------------- + + log('FILE CHECK', 'Datei-IIFE startet.'); // NEU: Kontrollierbarer Start-Log + + if (window.__CUSTOM_BLOCKS_LOADED) return; + window.__CUSTOM_BLOCKS_LOADED = true; + + const TARGET_CAT_ID = 'bausteine'; + const ALL_CUSTOM_BLOCK_IDS = []; + + function addOnce(bm, id, def) { + // Hinzufügen des Blocks und Sicherstellen der Kategorie-Zuweisung + try { + bm.add(id, { ...def, category: TARGET_CAT_ID }); + ALL_CUSTOM_BLOCK_IDS.push(id); + log('BLOCK ADD', `Block '${id}' erfolgreich hinzugefügt.`, '#B8860B'); + } catch (e) { + log('BLOCK ERROR', `Fehler beim Hinzufügen von Block '${id}': ${e.message}`, 'red', 'error'); + } + } + + const css = o => Object.entries(o).map(([k,v]) => `${k}:${v}`).join(';'); + + function register(editor) { + log('EXECUTION', `Starte Block-Registrierung für ${TARGET_CAT_ID}.`, '#DAA520'); + + const bm = editor.BlockManager; + + // --- Custom-Blöcke DEFINIEREN --- + + // TEXT + addOnce(bm, 'cust-text', { id:'cust-text', label:'📝 Text', + content:`
+

Dies ist ein Absatz. Doppelklick zum Bearbeiten.

` }); + + // IMAGE + addOnce(bm, 'cust-image', { id:'cust-image', label:'🖼️ Bild', + content:`
+ Bild
` }); + + // BUTTON + addOnce(bm, 'cust-button', { id:'cust-button', label:'🔘 Button', + content:`
+ Call To Action
` }); + + // DIVIDER + addOnce(bm, 'cust-divider',{ id:'cust-divider',label:'⎯ Divider', + content:`
` }); + + // SPACER + addOnce(bm, 'cust-spacer', { id:'cust-spacer', label:'↕ Spacer', + content:`
` }); + + // 2 COL + addOnce(bm, 'cust-2col', { id:'cust-2col', label:'🧩 2 Spalten', + content:` +
+

Linke Spalte – Inhalt hier.

+
+

Rechte Spalte – Inhalt hier.

+
` }); + + // MEDIA LEFT + addOnce(bm, 'cust-media-left', { id:'cust-media-left', label:'🖼️◀ Text', + content:` +
+ Bild + +

Überschrift

+

Beschreibungstext …

+ Mehr erfahren +
` }); + + // HERO + addOnce(bm, 'cust-hero', { id:'cust-hero', label:'🌄 Hero', + content:`
+ Hero +

Titel des Newsletters

+

Kurzer Untertitel oder Einleitung.

+
` }); + + // FOOTER + addOnce(bm, 'cust-footer', { id:'cust-footer', label:'⚓ Footer', + content:`
+

Dein Unternehmen GmbH • Musterstraße 1 • 12345 Berlin

+

Abmelden · + Impressum · + Datenschutz

+
` }); + + log('SUCCESS', `Registrierung abgeschlossen. ${ALL_CUSTOM_BLOCK_IDS.length} Blöcke erstellt.`, '#008000', 'info', true); + } + + // 🛑 KRITISCHE EXPORT-KORREKTUR: Exportiere 'register', um den Fehler in bridge-core.js zu beheben + window.BridgeBlocksCustom = { + IDS: ALL_CUSTOM_BLOCK_IDS, + register: register // <--- NEU: Exportiert die Register-Funktion + }; + + // Registriere das Modul als GrapesJS Plugin + if (B && B.registerGrapesJSPlugin && typeof register === 'function') { + B.registerGrapesJSPlugin('bridge-blocks-custom', register); + log('PLUGIN REGISTER', `'bridge-blocks-custom' erfolgreich zur Bridge Plugin Registry hinzugefügt.`, '#008000'); + } else { + log('CRITICAL ERROR', `BridgeParts oder registerGrapesJSPlugin fehlt! Plugin-Registrierung gescheitert.`, 'red', 'error'); + } + +})(); diff --git a/public/assets/js/bridge/blocks-standard.js b/public/assets/js/bridge/blocks-standard.js new file mode 100644 index 0000000..6dad268 --- /dev/null +++ b/public/assets/js/bridge/blocks-standard.js @@ -0,0 +1,139 @@ +/* /assets/js/bridge/blocks-standard.js (FINAL & LOG-KONTROLLIERT) */ +(function () { + + const PluginName = 'blocks-standard'; + const B = window.BridgeParts || (window.BridgeParts = {}); + + // ---------------------------------------------------------------------- + // 🎯 NEU: LOKALE LOG-KONFIGURATION UND WRAPPER + // ---------------------------------------------------------------------- + // Setzen Sie dies auf 'false' in der config.js oder hier, um alle Logs NUR für dieses Plugin zu deaktivieren. + if (B.LOG_CONFIG && B.LOG_CONFIG.PLUGINS) { + B.LOG_CONFIG.PLUGINS[PluginName] = false; // <-- HIER IST IHR SCHALTER + } + + // NEUER LOKALER WRAPPER, der die zentrale B.log Funktion verwendet: + const log = (type, message, color = '#0000FF', logType = 'info', force = false) => { + if (typeof B.log === 'function') { + B.log(PluginName, `[${type}] ${message}`, color, logType, force); + } else if (logType === 'error') { + // Fallback für kritische Fehler, wenn B.log fehlt + console.error(`%c[${PluginName} - ${type}] %c${message}`, `color:red; font-weight:bold;`, 'color:inherit;'); + } else { + // Fallback für sonstige Logs + console.log(`%c[${PluginName} - ${type}] %c${message}`, `color:${color}; font-weight:bold;`, 'color:inherit;'); + } + }; + // ---------------------------------------------------------------------- + + log('FILE CHECK', 'Datei-IIFE startet.'); + + // Kritische Prüfung, um doppelte Ausführung zu verhindern + if (window.__STANDARD_BLOCKS_LOADED) return; + window.__STANDARD_BLOCKS_LOADED = true; + + const TARGET_CAT_ID = 'mysnips'; + const TARGET_CAT_LABEL = 'Bibliothek'; + const ALL_STANDARD_BLOCK_IDS = []; + const css = o => Object.entries(o).map(([k,v]) => `${k}:${v}`).join(';'); + + /** + * Fügt einen Block hinzu oder aktualisiert ihn SICHER + */ + function addOrUpdate(bm, id, def) { + if (bm.get(id)) { + bm.remove(id); + log('UPDATE', `Entferne alte Block-Definition: ${id}`, 'gray'); + } + + const finalDef = { + ...def, + category: TARGET_CAT_ID, + force: true + }; + + try { + bm.add(id, finalDef); + } catch (e) { + log('CRITICAL ERROR', `KRITISCHER FEHLER beim Hinzufügen von '${id}': ${e.message}`, 'red', 'error'); + return; + } + + ALL_STANDARD_BLOCK_IDS.push(id); + } + + /** + * Die eigentliche Plugin-Funktion, die von GrapesJS/Bridge aufgerufen wird. + */ + const pluginFunction = (editor) => { + // Aggressiver Log zur Prüfung der Ausführung + log('EXECUTION CHECK', `Starte Block-Registrierung für ${TARGET_CAT_ID}.`, '#993300'); + + if (!editor || !editor.BlockManager) { + log('EXECUTION CHECK', 'Fehler: GrapesJS Editor Instanz ist ungültig.', 'red', 'error'); + return; + } + + const bm = editor.BlockManager; + + // ======================================================= + // I. GRAPESJS DEFAULT BLÖCKE (ALLE STANDARD ELEMENTE) + // ======================================================= + + // TEXT (Registriert als 'std-text') + addOrUpdate(bm, 'std-text', { label:'Text (Basis)', + content:`
Absatztext.
` }); + + // IMAGE (Registriert als 'std-image') + addOrUpdate(bm, 'std-image', { label:'Bild (Basis)', + content:`Bild` }); + + // LINK (Registriert als 'std-link') + addOrUpdate(bm, 'std-link', { label:'Link (Basis)', + content:`Hyperlink` }); + + // SECTION (Registriert als 'std-section') + addOrUpdate(bm, 'std-section', { label:'Sektion', + content:`
+
Inhalt der Sektion.
+
` }); + + // COLUMN (Registriert als 'std-column') + addOrUpdate(bm, 'std-column', { label:'Spalte', + content:`
+
Spalteninhalt
+
` }); + + // BUTTON (Registriert als 'std-button') + addOrUpdate(bm, 'std-button', { label:'Button (Basis)', + content:`Button` }); + + // DIVIDER (Registriert als 'std-divider') + addOrUpdate(bm, 'std-divider',{ label:'Trenner (Basis)', + content:`
` }); + + // MAP (Registriert als 'std-map') + addOrUpdate(bm, 'std-map', { label:'Karte', + content:`` }); + + // Löst die notwendigen Events für den Bridge Core / Cleanup aus. + editor.trigger('block:add'); + + log('SUCCESS', `Erfolgreich ${ALL_STANDARD_BLOCK_IDS.length} Standardblöcke in Kategorie '${TARGET_CAT_LABEL}' registriert.`, '#008000', 'info', true); + }; + + // Exportiere für den manuellen Aufruf in bridge-core.js + window.BridgeBlocksStandard = { + IDS: ALL_STANDARD_BLOCK_IDS, + register: pluginFunction, + }; + + // Registriere das Modul als GrapesJS Plugin (für den Fall, dass es doch anderswo benötigt wird) + if (B && B.registerGrapesJSPlugin) { + B.registerGrapesJSPlugin('bridge-blocks-standard', window.BridgeBlocksStandard.register); + log('PLUGIN REGISTER', `'bridge-blocks-standard' erfolgreich zur Bridge Plugin Registry hinzugefügt.`, '#008000'); + } else { + log('CRITICAL ERROR', `BridgeParts oder registerGrapesJSPlugin fehlt! Plugin-Registrierung gescheitert.`, 'red', 'error'); + } + +})(); diff --git a/public/assets/js/bridge/categorization-cleanup.js b/public/assets/js/bridge/categorization-cleanup.js new file mode 100644 index 0000000..c369709 --- /dev/null +++ b/public/assets/js/bridge/categorization-cleanup.js @@ -0,0 +1,265 @@ +/* /assets/js/bridge/categorization-cleanup.js (FINAL & LOG-KONTROLLIERT) */ +(function(B){ + + if (!B || typeof grapesjs === 'undefined') return; + + // 🛑 NEUER NAME: Dies wird das Plugin in GrapesJS registrieren + const PluginName = 'bridge-categorization-cleanup'; + + // ---------------------------------------------------------------------- + // 🎯 NEU: LOKALE LOG-KONFIGURATION UND WRAPPER + // ---------------------------------------------------------------------- + // Setzen Sie dies auf 'false' in der config.js oder hier, um alle Logs NUR für dieses Plugin zu deaktivieren. + if (B.LOG_CONFIG && B.LOG_CONFIG.PLUGINS) { + B.LOG_CONFIG.PLUGINS[PluginName] = false; // <-- HIER IST IHR SCHALTER + } + + // NEUER LOKALER WRAPPER, der die zentrale B.log Funktion verwendet: + const log = (type, message, color = '#228B22', logType = 'info', force = false) => { + // Wir verwenden B.log, das die B.LOG_CONFIG.PLUGINS[PluginName] prüft + if (typeof B.log === 'function') { + B.log(PluginName, `[${type}] ${message}`, color, logType, force); + } else if (logType === 'error') { + // Fallback für kritische Fehler, wenn B.log fehlt (sollte nicht passieren) + console.error(`%c[${PluginName} - ${type}] %c${message}`, `color:red; font-weight:bold;`, 'color:inherit;'); + } + }; + // ---------------------------------------------------------------------- + + // 🛑 WICHTIG: Liste aller unerwünschten IDs/Labels + const UNWANTED_UNCATEGORIZED_ID = 'Uncategorized'; + // Fügen Sie die gängigen IDs des gjs-preset-newsletter hinzu + const PRESET_UNWANTED_IDS = ['Basic', 'Layout', 'Extra', 'Components', 'Forms']; + + // Alle IDs, die gelöscht werden müssen. Enthält NICHT mehr 'Bibliothek'. + const ALL_FORBIDDEN_CAT_IDS = [UNWANTED_UNCATEGORIZED_ID, ...PRESET_UNWANTED_IDS]; + + const UNWANTED_BLOCK_ID = 'gjs-lbr-block-disabled'; + const UNWANTED_BLOCK_LABEL = 'Bibliothek-disabled'; + + const FALLBACK_CATEGORY_ID = 'mysnips'; + + const CUSTOM_BLOCK_IDS = (window.BridgeBlocksCustom && window.BridgeBlocksCustom.IDS) || []; + + let normalizationRunCount = 0; + let normalizationIsRunning = false; + let maxNormalizationRuns = 5; + + + // ---------------------------------------------------------------------- + // HILFSFUNKTION: Entfernt hartnäckige Kategorie-DOM-Elemente + // ---------------------------------------------------------------------- + const zapUnwantedCategoryDom = (editor) => { + const blocksPanelEl = editor.BlockManager.getContainer(); + if (blocksPanelEl) { + let removedCount = 0; + blocksPanelEl.querySelectorAll('.gjs-block-cat').forEach(catEl => { + const catTitleEl = catEl.querySelector('.gjs-title'); + + if (catTitleEl) { + const catTitle = catTitleEl.textContent.trim(); + // Prüft, ob der Titel eine der unerwünschten IDs ist (z.B. 'Basic') + if (ALL_FORBIDDEN_CAT_IDS.includes(catTitle)) { + catEl.remove(); + removedCount++; + } + } + }); + if (removedCount > 0) { + log('DOM FIX', `${removedCount} unerwünschte Kategorie-DOM-Elemente entfernt.`, 'orange', 'warn'); + } + } + }; + + + // ---------------------------------------------------------------------- + // Hilfsfunktion: Erzwingt das Neu-Rendern der Block-View + // ---------------------------------------------------------------------- + const renderBlocks = (editor) => { + zapUnwantedCategoryDom(editor); + log('RENDER', 'DOM-Cleanup ausgeführt.', 'green'); + }; + + + // ---------------------------------------------------------------------- + // 1. Funktion zum Ausblenden/Normalisieren der Kategorien (Kernlogik) + // ---------------------------------------------------------------------- + const normalizeCategories = (editor) => { + if (normalizationIsRunning || normalizationRunCount >= maxNormalizationRuns) { + if (normalizationRunCount >= maxNormalizationRuns) { + log('SKIP', `normalizeCategories übersprungen: Maximale Läufe (${maxNormalizationRuns}) erreicht.`, 'red', 'warn'); + } else { + log('SKIP', 'normalizeCategories übersprungen: Läuft bereits.', 'red', 'warn'); + } + return; + } + + normalizationIsRunning = true; + normalizationRunCount++; + // Nur das Start-Log kann eine Gruppen-Markierung sein + log('START', `Starte normalizeCategories Run #${normalizationRunCount}`, '#191970'); + + const bm = editor.BlockManager; + const config = B.CATEGORY_CONFIG || {}; + const configuredCategoryIds = Object.keys(config); + + log('CONFIG', `Konfigurierte Kategorie-IDs: ${configuredCategoryIds.join(', ')}`, '#555555'); + + // --- A. Explizites Erstellen der Kategorien (Sicherheits-Fallback) --- + const catsToEnsure = new Set(configuredCategoryIds); + + catsToEnsure.forEach(catId => { + const catConf = config[catId]; + if (!catConf) return; + + if (!bm.getCategories().get(catId)) { + bm.getCategories().add({ + id: catId, + label: catConf.label, + open: catConf.open !== false, + order: catConf.ord || 999 + }); + log('CAT FALLBACK', `Kategorie '${catId}' fehlte und wurde JETZT erstellt!`, 'red', 'error'); + } + }); + + + // --- B. Zwangszuweisung der Blöcke und Bereinigung von Blöcken --- + bm.getAll().each(block => { + const id = block.get('id'); + const label = block.get('label'); + let catId = block.get('category'); + + if (typeof catId === 'object' && catId.id) { + catId = catId.id; + } + + // 1. Lösche unerwünschten hartnäckigen Block (DEAKTIVIERT) + if (id === UNWANTED_BLOCK_ID || label === UNWANTED_BLOCK_LABEL) { + // ... (Block removal logic commented out) + // log('BLOCK REMOVE', `Lösche unerwünschten Block: ${id}`, 'red', 'warn'); + // bm.remove(id); + } + + // 2. Setze Blöcke ohne oder mit unerwünschter/unbekannter Kategorie auf den Fallback (mysnips) + const isUnconfiguredOrForbidden = !catId || !configuredCategoryIds.includes(catId) || ALL_FORBIDDEN_CAT_IDS.includes(catId); + + if (isUnconfiguredOrForbidden) { + if (id) { + log('BLOCK FIX', `Block '${id}' ('${label}') verschoben nach '${FALLBACK_CATEGORY_ID}' (Ursprüngliche Kat ID: ${catId || 'keine/leer'}).`, 'orange', 'warn'); + block.set('category', FALLBACK_CATEGORY_ID); + } + } else { + log('BLOCK OK', `Block '${id}' ('${label}') bleibt in Kategorie '${catId}'.`, 'green'); + } + + // 3. Custom Blocks schützen + if (CUSTOM_BLOCK_IDS.includes(id) && catId !== 'bausteine') { + log('BLOCK FIX', `Custom Block '${id}' auf 'bausteine' korrigiert.`, 'orange', 'warn'); + block.set('category', 'bausteine'); + } + }); + + + // --- C. Kategorien erzwingen, Label korrigieren und Löschen von Modellen --- + const categories = bm.getCategories().models || bm.getCategories(); + let visibleCategories = []; + + categories.forEach(catModel => { + const catId = catModel.get('id'); + const catConf = config[catId]; + + // 1. Aggressives Löschen von unerwünschten Preset-Kategorien + if (ALL_FORBIDDEN_CAT_IDS.includes(catId)) { + log('CAT REMOVE', `Lösche unerwünschtes Category Model: ${catId} (Da in ALL_FORBIDDEN_CAT_IDS).`, 'red', 'error'); + bm.getCategories().remove(catModel); + return; + } + + const activeConf = catConf; + + // 2. Finde eine existierende, aber nicht konfigurierte Kategorie, und blende sie aus + if (!activeConf && catId) { + log('CAT HIDE', `Kategorie '${catId}' existiert, ist aber nicht in CATEGORY_CONFIG. Wird ausgeblendet.`, 'orange', 'warn'); + catModel.set('visible', false); + catModel.set('open', false); + return; + } + + // 3. Korrigiere Label, Sortierung und Sichtbarkeit (Konfigurierte Kategorien) + if (activeConf) { + const oldLabel = catModel.get('label'); + const newLabel = activeConf.label; + const visibility = true; + + if (oldLabel !== newLabel) { + log('CAT UPDATE', `Korrigiere Label von '${catId}' von '${oldLabel}' auf '${newLabel}'.`, '#00BFFF'); + catModel.set('label', newLabel, { silent: true }); + } + + catModel.set('visible', visibility); + catModel.set('open', activeConf.open !== false); + catModel.set('order', activeConf.ord || 999); + visibleCategories.push(catId); + + log('CAT FINAL', `Kategorie '${catId}' auf Visible: ${visibility}, Order: ${catModel.get('order')}.`, 'green'); + } + }); + + // --- D. Cleanup und Neu-Sortierung erzwingen --- + categories.sort((a, b) => (a.get('order') || 999) - (b.get('order') || 999)); + + B.sortBlocksByPrefixAndLabel && B.sortBlocksByPrefixAndLabel(bm.getAll().models); + + // DOM Cleanup wird über renderBlocks aufgerufen + renderBlocks(editor); + + log('END', `Kategorisierung abgeschlossen. Sichtbare Kategorien (Modelle): ${visibleCategories.sort().join(', ')}.`, 'green', 'info', true); // FINAL Log ist forced=true für Abschlussmeldung + + normalizationIsRunning = false; + }; + + + // ---------------------------------------------------------------------- + // GrapesJS Plugin Registrierung + // ---------------------------------------------------------------------- + grapesjs.plugins.add(PluginName, (editor, opts = {}) => { + const bm = editor.BlockManager; + + // 1. Initialer, verspäteter Lauf bei Ladevorgang + editor.on('load', () => { + setTimeout(() => { + log('FINAL RUN', `Starte finalen Normalisierungslauf nach 2500ms.`, 'orange', 'warn'); + normalizeCategories(editor); + }, 2500); + }); + + // 2. WATCHDOG gegen Label-Überschreibung oder unerwünschte Adds + bm.getCategories().on('add change:label', (categoryModel) => { + const catId = categoryModel.get('id'); + const newLabel = categoryModel.get('label'); + const expectedLabel = B.CATEGORY_CONFIG?.[catId]?.label; + + // WATCHDOG-ADD + if (ALL_FORBIDDEN_CAT_IDS.includes(catId)) { + log('WATCHDOG-ADD', `Unerwünschte Kategorie '${catId}' wurde hinzugefügt! Starte Sofort-Korrektur.`, 'red', 'error'); + bm.getCategories().remove(categoryModel); + setTimeout(() => normalizeCategories(editor), 1); + } + + // WATCHDOG-LABEL + if (expectedLabel && newLabel !== expectedLabel) { + log('WATCHDOG-CHANGE', `Externe Label-Manipulation von '${catId}' erkannt: Korrigiere von '${newLabel}' auf '${expectedLabel}'.`, 'orange', 'warn'); + categoryModel.set('label', expectedLabel, { silent: true }); + setTimeout(() => normalizeCategories(editor), 1); + } + }); + + // Exporte beibehalten, falls sie in bridge-core.js verwendet werden + B.normalizeCategories = normalizeCategories; + B.renderBlocks = renderBlocks; + + log('INIT', 'Master-Koordinator registriert.', '#008080'); + }); + +})(window.BridgeParts || (window.BridgeParts = {})); diff --git a/public/assets/js/bridge/categorization-master (Version before split).js b/public/assets/js/bridge/categorization-master (Version before split).js new file mode 100644 index 0000000..7059b64 --- /dev/null +++ b/public/assets/js/bridge/categorization-master (Version before split).js @@ -0,0 +1,239 @@ +/* /assets/js/bridge/categorization-master.js (FINALE KORREKTUR V3: Entfernt aggressives bm.render()) */ +(function(B){ + + if (!B || typeof grapesjs === 'undefined') return; + + const PluginName = 'bridge-categorization-master'; + + // 🛑 WICHTIG: Liste aller unerwünschten IDs/Labels + const UNWANTED_CATEGORY_ID = 'Bibliothek'; + const UNWANTED_UNCATEGORIZED_ID = 'Uncategorized'; + // Fügen Sie die gängigen IDs des gjs-preset-newsletter hinzu + const PRESET_UNWANTED_IDS = ['Basic', 'Layout', 'Extra', 'Components', 'Forms']; + + // Alle IDs, die gelöscht werden müssen + const ALL_FORBIDDEN_CAT_IDS = [UNWANTED_CATEGORY_ID, UNWANTED_UNCATEGORIZED_ID, ...PRESET_UNWANTED_IDS]; + + const UNWANTED_BLOCK_ID = 'gjs-lbr-block'; + const UNWANTED_BLOCK_LABEL = 'Bibliothek'; + + const FALLBACK_CATEGORY_ID = 'mysnips'; + + const CUSTOM_BLOCK_IDS = (window.BridgeBlocksCustom && window.BridgeBlocksCustom.IDS) || []; + + let normalizationRunCount = 0; + let normalizationIsRunning = false; + let maxNormalizationRuns = 5; + + + // ---------------------------------------------------------------------- + // HILFSFUNKTION: Entfernt hartnäckige Kategorie-DOM-Elemente + // ---------------------------------------------------------------------- + const zapUnwantedCategoryDom = (editor) => { + const blocksPanelEl = editor.Panels.getPanel('blocks')?.get('el'); + if (blocksPanelEl) { + let removedCount = 0; + blocksPanelEl.querySelectorAll('.gjs-block-cat').forEach(catEl => { + const catTitleEl = catEl.querySelector('.gjs-title'); + + if (catTitleEl) { + const catTitle = catTitleEl.textContent.trim(); + // Prüfe auf unerwünschte Titel (sowohl Standard als auch Presets) + if (ALL_FORBIDDEN_CAT_IDS.includes(catTitle) || catTitle === UNWANTED_UNCATEGORIZED_ID || catTitle === UNWANTED_CATEGORY_ID) { + catEl.remove(); + removedCount++; + } + } + }); + if (removedCount > 0) { + console.warn(`[${PluginName}][DOM Fix] ${removedCount} unerwünschte Kategorie-DOM-Elemente entfernt.`); + } + } + }; + + + // ---------------------------------------------------------------------- + // Hilfsfunktion: Erzwingt das Neu-Rendern der Block-View (NUR DOM-CLEANUP) + // ---------------------------------------------------------------------- + const renderBlocks = (editor) => { + // 🛑 KRITISCHE KORREKTUR: Entferne bm.render() – nur DOM-Cleanup ist hier nötig, + // da das Setzen der Model-Eigenschaften (label, visible) das Rendering übernehmen sollte. + zapUnwantedCategoryDom(editor); + console.log(`[${PluginName}][Render] DOM-Cleanup ausgeführt.`); + }; + + + // ---------------------------------------------------------------------- + // 1. Funktion zum Ausblenden/Normalisieren der Kategorien (Kernlogik) + // ---------------------------------------------------------------------- + const normalizeCategories = (editor) => { + if (normalizationIsRunning || normalizationRunCount >= maxNormalizationRuns) { + if (normalizationRunCount >= maxNormalizationRuns) { + console.warn(`[${PluginName}] normalizeCategories übersprungen: Maximale Läufe (${maxNormalizationRuns}) erreicht.`); + } else { + console.warn(`[${PluginName}] normalizeCategories übersprungen: Läuft bereits.`); + } + return; + } + + normalizationIsRunning = true; + normalizationRunCount++; + console.group(`[${PluginName}] normalizeCategories Run #${normalizationRunCount}`); + + const bm = editor.BlockManager; + const config = B.CATEGORY_CONFIG || {}; + const configuredCategoryIds = Object.keys(config); + + + // 🛑 NEUER FALLBACK-FIX: Stellen Sie sicher, dass alle konfigurierten Kategorien existieren, + // bevor Blöcke zugewiesen werden. + configuredCategoryIds.forEach(catId => { + const catConf = config[catId]; + if (!bm.getCategories().get(catId)) { + bm.getCategories().add({ + id: catId, + label: catConf.label, + open: catConf.open !== false, + order: catConf.ord || 999 + }); + // Nur als Warnung, da dies bei 'mysnips' oft passiert, wenn es leer ist. + console.warn(`[${PluginName}][Cat Fallback] Kategorie '${catId}' wurde nachträglich erstellt.`); + } + }); + + + // --- A. Zwangszuweisung der Blöcke und Bereinigung von Blöcken --- + bm.getAll().each(block => { + const id = block.get('id'); + const label = block.get('label'); + let catId = block.get('category'); + + if (typeof catId === 'object' && catId.id) { + catId = catId.id; // Behandle Category-Objekte + } + + // 1. Lösche unerwünschten hartnäckigen Block (z.B. gjs-lbr-block) + if (id === UNWANTED_BLOCK_ID || label === UNWANTED_BLOCK_LABEL) { + console.log(`[${PluginName}][Block Fix] Unerwünschter Block '${id}' ('${label}') entfernt.`); + bm.remove(id); + return; + } + + // 2. Setze Blöcke ohne oder mit unerwünschter/unbekannter Kategorie auf den Fallback (mysnips) + // HINWEIS: 'custom' ist in configuredCategoryIds, falls es noch keine Blöcke von der API hat. + if (!catId || !configuredCategoryIds.includes(catId) || ALL_FORBIDDEN_CAT_IDS.includes(catId)) { + // Nur wenn der Block nicht leer ist + if (id) { + console.log(`[${PluginName}][Block Fix] Block '${id}' ('${label}') verschoben nach '${FALLBACK_CATEGORY_ID}' (von Kat: ${catId || 'keine'}).`); + block.set('category', FALLBACK_CATEGORY_ID); + } + } + + // 3. Custom Blocks schützen + if (CUSTOM_BLOCK_IDS.includes(id) && catId !== 'bausteine') { + block.set('category', 'bausteine'); + } + }); + + + // --- B. Kategorien erzwingen, Label korrigieren und Löschen von Modellen --- + const categories = bm.getCategories().models || bm.getCategories(); + let visibleCategories = []; + + // Gehe alle Category Models durch + categories.forEach(catModel => { + const catId = catModel.get('id'); + const catConf = config[catId]; + + // Aggressives Löschen von unerwünschten Preset-Kategorien + if (ALL_FORBIDDEN_CAT_IDS.includes(catId)) { + console.warn(`[${PluginName}][Cat Fix] Lösche unerwünschtes Category Model: ${catId}`); + bm.getCategories().remove(catModel); + return; + } + + // Finde eine existierende, aber nicht konfigurierte Kategorie, und blende sie aus + // WICHTIG: mysnips ist der FALLBACK_CATEGORY_ID, hier darf es NICHT ausgeblendet werden. + if (!catConf && catId && catId !== FALLBACK_CATEGORY_ID) { + catModel.set('visible', false); + catModel.set('open', false); + return; + } + + // Korrigiere Label, Sortierung und Sichtbarkeit der konfigurierten Kategorien + if (catConf) { + // 🛑 KRITISCHER FIX: Garantiertes Setzen des korrekten Labels (LÖST KLEINSCHREIBUNGS-PROBLEM) + if (catModel.get('label') !== catConf.label) { + console.log(`[${PluginName}][Cat Fix] Korrigiere Label von '${catId}' auf '${catConf.label}'.`); + catModel.set('label', catConf.label); + } + + // ** Das Setzen von 'visible' und 'open' sollte die UI-Aktualisierung (Kategorie anzeigen) auslösen. ** + catModel.set('visible', true); + catModel.set('open', catConf.open !== false); + catModel.set('order', catConf.ord || 999); + visibleCategories.push(catId); + } + }); + + // --- C. Cleanup und Neu-Rendern erzwingen --- + categories.sort((a, b) => (a.get('order') || 999) - (b.get('order') || 999)); + + B.sortBlocksByPrefixAndLabel && B.sortBlocksByPrefixAndLabel(bm.getAll().models); + + // 🛑 KRITISCH: Rendering WIRD NICHT mehr erzwungen – nur DOM Cleanup. + renderBlocks(editor); + + console.log(`Kategorisierung abgeschlossen. Sichtbare Kategorien: ${visibleCategories.sort().join(', ')}.`); + console.groupEnd(); + normalizationIsRunning = false; + }; + + + // ---------------------------------------------------------------------- + // GrapesJS Plugin Registrierung + // ---------------------------------------------------------------------- + grapesjs.plugins.add(PluginName, (editor, opts = {}) => { + const bm = editor.BlockManager; + + // 1. Initialer, verspäteter Lauf bei Ladevorgang + editor.on('load', () => { + // FINALER LAUF: Läuft, wenn ALLE Standard-Plugins fertig sind + setTimeout(() => { + console.warn(`[${PluginName}][FINAL RUN] Starte finalen Normalisierungslauf nach 2500ms.`); + normalizeCategories(editor); + }, 2500); + }); + + // 2. WATCHDOG gegen Label-Überschreibung oder unerwünschte Adds + bm.getCategories().on('add change:label', (categoryModel) => { + const catId = categoryModel.get('id'); + const newLabel = categoryModel.get('label'); + const expectedLabel = B.CATEGORY_CONFIG?.[catId]?.label; + + // WATCHDOG-ADD: Entfernt unerwünschte Kategorien sofort, falls sie erstellt werden + if (ALL_FORBIDDEN_CAT_IDS.includes(catId)) { + console.error(`[${PluginName}][WATCHDOG-ADD] Unerwünschte Kategorie '${catId}' wurde hinzugefügt! Starte Sofort-Korrektur.`); + bm.getCategories().remove(categoryModel); + setTimeout(() => normalizeCategories(editor), 1); + } + + // WATCHDOG-LABEL: Korrigiert falsche Labels (z.B. "bausteine" -> "🧱 Bausteine") + if (expectedLabel && newLabel !== expectedLabel) { + console.warn(`[${PluginName}][WATCHDOG-CHANGE] Externe Label-Manipulation von '${catId}' erkannt: Korrigiere von '${newLabel}' auf '${expectedLabel}'.`); + + // Sofortiges Zurücksetzen des Labels auf den korrekten Wert + categoryModel.set('label', expectedLabel, { silent: true }); + + // Triggere einen Normalize-Lauf, damit die UI die Korrektur sieht und die Sortierung passt. + setTimeout(() => normalizeCategories(editor), 1); + } + }); + + B.normalizeCategories = normalizeCategories; + B.renderBlocks = renderBlocks; + + console.log(`[${PluginName}] Master-Koordinator registriert.`); + }); + +})(window.BridgeParts || (window.BridgeParts = {})); diff --git a/public/assets/js/bridge/categorization-master.js b/public/assets/js/bridge/categorization-master.js new file mode 100644 index 0000000..d544c7f --- /dev/null +++ b/public/assets/js/bridge/categorization-master.js @@ -0,0 +1,14 @@ +/* /assets/js/bridge/categorization-master.js (PLATZHALTER - LOGIK IN CLEANUP.JS VERSCHOBEN) */ +(function(B){ + + if (!B || typeof grapesjs === 'undefined') return; + + const PluginName = 'bridge-categorization-master'; + + // Dies ist nun ein leeres Plugin. Die Logik wurde nach categorization-cleanup.js verschoben. + grapesjs.plugins.add(PluginName, (editor, opts = {}) => { + // Leere Plugin-Funktion. Führt keine Aufräumarbeiten, Normalisierung oder Exporte durch. + console.log(`[${PluginName}] Plugin existiert (Logik nach cleanup.js verschoben).`); + }); + +})(window.BridgeParts || (window.BridgeParts = {})); diff --git a/public/assets/js/bridge/category-config.js b/public/assets/js/bridge/category-config.js new file mode 100644 index 0000000..165ee8e --- /dev/null +++ b/public/assets/js/bridge/category-config.js @@ -0,0 +1,55 @@ +/* /assets/js/bridge/category-config.js (FINALE KORREKTUR DER BLAUPASE) */ +(function(B) { +    if (!B) return; + + // NEU: Map, die Ressourcentyp ('kind') zu API-Basis-URL zuordnet. Wird von library-api.js gelesen. + B.RESOURCE_API_BASES = B.RESOURCE_API_BASES || {}; + const API_BASE_DEFAULT = (B.API_BASE || '/api/editor'); + +    // DEFINITION DER ZIEL-KATEGORIEN +    B.CATEGORY_CONFIG = { +        // --- 1. BIBLIOTHEK (mysnips) --- +        mysnips: { +            // ... (Bleibt unverändert, da es kein API-Async-Laden nutzt) +            ord: 20,  +            open: false, +            label: '📚 Bibliothek', +            files: ['blocks-standard.js'], + registration_mode: 'sync', +        }, +        // --- 2. BAUSTEINE (bausteine) --- +        bausteine: { +            // ... (Bleibt unverändert, da es kein API-Async-Laden nutzt) +            ord: 10, +            open: true, +            label: '🧱 Bausteine', +            files: ['blocks-custom.js'], +            registration_mode: 'sync', +        }, +        // --- 3. API Custom-Blocks (Standard-API) ---- +        custom: { +            ord: 1, +            label: 'Custom', +            open: true, +            files: ['library-api.js','blocks-api.js'], +            registration_mode: 'async', + // NEU: API-Konfiguration für diese Kategorie + api_config: { + base_url: '/api/editor', // Nutzt die Standard-API + resources: ['templates','sections', 'blocks', 'snippets'] // Ressourcen, die von dort geladen werden + } +        } +    }; + + // --- Initialisierung der zentralen RESOURCE_API_BASES Map --- + // Diese Logik stellt sicher, dass library-api.js weiß, welchen Endpunkt es für welchen "kind" nutzen muss. + Object.values(B.CATEGORY_CONFIG).forEach(config => { + if (config.api_config && Array.isArray(config.api_config.resources)) { + const baseUrl = config.api_config.base_url || API_BASE_DEFAULT; + config.api_config.resources.forEach(resourceKind => { + B.RESOURCE_API_BASES[resourceKind] = baseUrl; + }); + } + }); +     +})(window.BridgeParts || (window.BridgeParts = {})); diff --git a/public/assets/js/bridge/category-config.js WORKED b/public/assets/js/bridge/category-config.js WORKED new file mode 100644 index 0000000..4ac3ff8 --- /dev/null +++ b/public/assets/js/bridge/category-config.js WORKED @@ -0,0 +1,28 @@ +/* /assets/js/bridge/category-config.js (FINAL: Zentrale Konfiguration) */ +(function(w){ + var B = w.BridgeParts = w.BridgeParts || {}; + + /** + * Zentrale Konfiguration für Block-Kategorien und deren Sortierprioritäten. + */ + B.CATEGORY_CONFIG = { + // Prio 1 + 'lib-templates':   { label:'Bibliothek: Templates (Ref)', ord: 1, open: true }, + + // Prio 2 (Custom)A + 'custom':           { label:'Custom',                     ord: 2, open: true }, + 'custom-fix':       { label:'Custom',                     ord: 2, open: true }, + 'custom-flex':      { label:'Custom',                     ord: 2, open: true }, + + // Prio 3 (Bausteine) + 'bausteine':       { label:'Bausteine',                   ord: 3, open: true }, + + // Prio 4 (Bibliothek) + 'mysnips':         { label:'Bibliothek',                  ord: 4, open: true }, + + // INTERNE (Werden später im Plugin auf Prio 2 umgeleitet und sortiert) + 'lib-sections':    { label:'Bibliothek: Sections',       ord: 99, open: true }, + 'lib-blocks':      { label:'Bibliothek: Blöcke',         ord: 99, open: true }, + }; + +})(window); diff --git a/public/assets/js/bridge/custom-blocks-plugin.js b/public/assets/js/bridge/custom-blocks-plugin.js new file mode 100644 index 0000000..db74312 --- /dev/null +++ b/public/assets/js/bridge/custom-blocks-plugin.js @@ -0,0 +1,143 @@ +/* /assets/js/bridge/custom-blocks-plugin.js (FINALE VERSION 2.0: Erzwungene Sortierung) */ +(function(gjs, B){ + if (!gjs || !B || !B.CATEGORY_CONFIG) return; + + // --- 1. Block-Sortierlogik (Wieder logische Gewichte: 1 < 2 < 3) ----------------------- + const getSortWeight = (id) => { + // Logisch: Section (1) < Block (2) < Snippet (3) + if (id.startsWith('custom-section-') || id.startsWith('lib-sec-')) return 1; + if (id.startsWith('custom-block-') || id.startsWith('lib-blk-')) return 2; + if (id.startsWith('custom-snippet-') || id.startsWith('snip-')) return 3; + return 99; + }; + + const sortBlocksByPrefixAndLabel = (blocks) => { + blocks.sort((a, b) => { + const aId = String((a.get ? a.get('id') : a.id) || ''); + const bId = String((b.get ? b.get('id') : b.id) || ''); + // Hier nutzen wir die Rohdaten (aSnippet, bSnippet) + const aLabel = String((a.get ? a.get('label') : a.label) || '').toLowerCase(); + const bLabel = String((b.get ? b.get('label') : b.label) || '').toLowerCase(); + + const aWeight = getSortWeight(aId); + const bWeight = getSortWeight(bId); + + // 1. Sortierung nach Gewicht (1, 2, 3) + if (aWeight !== bWeight) return aWeight - bWeight; + + // 2. Sortierung alphabetisch (a vor b) + if (aLabel < bLabel) return -1; + if (aLabel > bLabel) return 1; + return 0; + }); + }; + // ----------------------------------------------------------------------------------------- + + + gjs.plugins.add('bridge-custom-blocks', (editor, opts = {}) => { + const config = B.CATEGORY_CONFIG; + const validCatIds = Object.keys(config); + + // IDs zur internen Zuweisung + const CAT_CUSTOM_MAIN_ID = 'custom'; + const CAT_BAUSTEINE_ID = 'bausteine'; + const CAT_BIBLIOTHEK_ID = 'mysnips'; + const CAT_LIB_TEMPLATES_ID = 'lib-templates'; + + + const normalizeAndSort = (ed) => { + try { + const bm = ed.BlockManager; + const categories = bm.getCategories ? bm.getCategories() : null; + + let allBlocks = bm.getAll().models || bm.getAll(); + let customBlocksArray = []; + let otherBlocksArray = []; + + // 1. Blöcke neu kategorisieren & trennen + (allBlocks || []).forEach(b => { + const id = String((b.get ? b.get('id') : b.id) || ''); + let targetCatId = null; + + if (id.startsWith('lib-tpl-ref-')) { + targetCatId = CAT_LIB_TEMPLATES_ID; + } else if (id.startsWith('custom-') || id.startsWith('lib-sec-') || id.startsWith('lib-blk-') || id.startsWith('snip-')) { + targetCatId = CAT_CUSTOM_MAIN_ID; + } else if (id.startsWith('blk-') || id.startsWith('std-')) { + targetCatId = CAT_BAUSTEINE_ID; + } else if (!b.get('category')) { + targetCatId = CAT_BIBLIOTHEK_ID; + } + + if (targetCatId) { + b.set('category', targetCatId); + if (targetCatId === CAT_CUSTOM_MAIN_ID) { + customBlocksArray.push(b); + } else { + otherBlocksArray.push(b); + } + } else { + // Blöcke, die nicht zugewiesen wurden (z.B. basic/extra), behalten + otherBlocksArray.push(b); + } + }); + + // 2. Block-Sortierung INNERHALB der "custom" Kategorie + if (customBlocksArray.length > 0) { + sortBlocksByPrefixAndLabel(customBlocksArray); + console.log('[DEBUG PLUGIN] Custom Blocks intern sortiert.'); + } + + // NEU: Gesamte BlockManager-Kollektion mit sortierten Custom-Blöcken überschreiben + // Wir nehmen alle sortierten Custom-Blöcke und fügen die anderen Blöcke danach an. + const newBlockOrder = customBlocksArray.concat(otherBlocksArray); + + // Dieser Hack sollte die Reihenfolge in der Seitenleiste erzwingen. + if (bm.getAll().reset) { + bm.getAll().reset(newBlockOrder); + console.log('[DEBUG PLUGIN] Gesamte Block-Kollektion mit neuer Sortierung überschrieben.'); + } + + // 3. Kategorien Aufräumen & Sortieren (wie zuvor) + if (categories && categories.models) { + // Aufräumen + categories.models.slice().forEach(cat => { + const catId = (cat.get('id') || cat.id || '').toLowerCase(); + if (!validCatIds.includes(catId) && catId !== 'basic' && catId !== 'extra') { + categories.remove(cat); + } + }); + + // Labels korrigieren und Kategorie-Sortierung erzwingen + categories.models.forEach(cat => { + const catId = (cat.get('id') || cat.id || '').toLowerCase(); + if (config[catId]) { + cat.set('label', config[catId].label); + cat.set('open', config[catId].open ?? true); + } + }); + + const catOrder = (m) => config[String((m.get('id') || m.id)).toLowerCase()]?.ord || 99; + const arr = categories.models.slice().sort((a,b) => catOrder(a) - catOrder(b)); + categories.reset(arr); + } + + // 4. Finaler DOM-Sweep + B.enforceCategoryOrder && B.enforceCategoryOrder(ed); + B.renderBlocks && B.renderBlocks(ed); + + } catch(e) { + console.error('[CustomPlugin] Error during normalize:', e); + } + }; + + // 5. Listener + editor.on('block:add block:remove block:reset', () => normalizeAndSort(editor)); + editor.on('load', () => { + normalizeAndSort(editor); + setTimeout(() => normalizeAndSort(editor), 100); + setTimeout(() => normalizeAndSort(editor), 800); + setTimeout(() => normalizeAndSort(editor), 1500); + }); + }); +})(window.grapesjs, window.BridgeParts); diff --git a/public/assets/js/bridge/custom-blocks-plugin.js WORKED b/public/assets/js/bridge/custom-blocks-plugin.js WORKED new file mode 100644 index 0000000..db74312 --- /dev/null +++ b/public/assets/js/bridge/custom-blocks-plugin.js WORKED @@ -0,0 +1,143 @@ +/* /assets/js/bridge/custom-blocks-plugin.js (FINALE VERSION 2.0: Erzwungene Sortierung) */ +(function(gjs, B){ + if (!gjs || !B || !B.CATEGORY_CONFIG) return; + + // --- 1. Block-Sortierlogik (Wieder logische Gewichte: 1 < 2 < 3) ----------------------- + const getSortWeight = (id) => { + // Logisch: Section (1) < Block (2) < Snippet (3) + if (id.startsWith('custom-section-') || id.startsWith('lib-sec-')) return 1; + if (id.startsWith('custom-block-') || id.startsWith('lib-blk-')) return 2; + if (id.startsWith('custom-snippet-') || id.startsWith('snip-')) return 3; + return 99; + }; + + const sortBlocksByPrefixAndLabel = (blocks) => { + blocks.sort((a, b) => { + const aId = String((a.get ? a.get('id') : a.id) || ''); + const bId = String((b.get ? b.get('id') : b.id) || ''); + // Hier nutzen wir die Rohdaten (aSnippet, bSnippet) + const aLabel = String((a.get ? a.get('label') : a.label) || '').toLowerCase(); + const bLabel = String((b.get ? b.get('label') : b.label) || '').toLowerCase(); + + const aWeight = getSortWeight(aId); + const bWeight = getSortWeight(bId); + + // 1. Sortierung nach Gewicht (1, 2, 3) + if (aWeight !== bWeight) return aWeight - bWeight; + + // 2. Sortierung alphabetisch (a vor b) + if (aLabel < bLabel) return -1; + if (aLabel > bLabel) return 1; + return 0; + }); + }; + // ----------------------------------------------------------------------------------------- + + + gjs.plugins.add('bridge-custom-blocks', (editor, opts = {}) => { + const config = B.CATEGORY_CONFIG; + const validCatIds = Object.keys(config); + + // IDs zur internen Zuweisung + const CAT_CUSTOM_MAIN_ID = 'custom'; + const CAT_BAUSTEINE_ID = 'bausteine'; + const CAT_BIBLIOTHEK_ID = 'mysnips'; + const CAT_LIB_TEMPLATES_ID = 'lib-templates'; + + + const normalizeAndSort = (ed) => { + try { + const bm = ed.BlockManager; + const categories = bm.getCategories ? bm.getCategories() : null; + + let allBlocks = bm.getAll().models || bm.getAll(); + let customBlocksArray = []; + let otherBlocksArray = []; + + // 1. Blöcke neu kategorisieren & trennen + (allBlocks || []).forEach(b => { + const id = String((b.get ? b.get('id') : b.id) || ''); + let targetCatId = null; + + if (id.startsWith('lib-tpl-ref-')) { + targetCatId = CAT_LIB_TEMPLATES_ID; + } else if (id.startsWith('custom-') || id.startsWith('lib-sec-') || id.startsWith('lib-blk-') || id.startsWith('snip-')) { + targetCatId = CAT_CUSTOM_MAIN_ID; + } else if (id.startsWith('blk-') || id.startsWith('std-')) { + targetCatId = CAT_BAUSTEINE_ID; + } else if (!b.get('category')) { + targetCatId = CAT_BIBLIOTHEK_ID; + } + + if (targetCatId) { + b.set('category', targetCatId); + if (targetCatId === CAT_CUSTOM_MAIN_ID) { + customBlocksArray.push(b); + } else { + otherBlocksArray.push(b); + } + } else { + // Blöcke, die nicht zugewiesen wurden (z.B. basic/extra), behalten + otherBlocksArray.push(b); + } + }); + + // 2. Block-Sortierung INNERHALB der "custom" Kategorie + if (customBlocksArray.length > 0) { + sortBlocksByPrefixAndLabel(customBlocksArray); + console.log('[DEBUG PLUGIN] Custom Blocks intern sortiert.'); + } + + // NEU: Gesamte BlockManager-Kollektion mit sortierten Custom-Blöcken überschreiben + // Wir nehmen alle sortierten Custom-Blöcke und fügen die anderen Blöcke danach an. + const newBlockOrder = customBlocksArray.concat(otherBlocksArray); + + // Dieser Hack sollte die Reihenfolge in der Seitenleiste erzwingen. + if (bm.getAll().reset) { + bm.getAll().reset(newBlockOrder); + console.log('[DEBUG PLUGIN] Gesamte Block-Kollektion mit neuer Sortierung überschrieben.'); + } + + // 3. Kategorien Aufräumen & Sortieren (wie zuvor) + if (categories && categories.models) { + // Aufräumen + categories.models.slice().forEach(cat => { + const catId = (cat.get('id') || cat.id || '').toLowerCase(); + if (!validCatIds.includes(catId) && catId !== 'basic' && catId !== 'extra') { + categories.remove(cat); + } + }); + + // Labels korrigieren und Kategorie-Sortierung erzwingen + categories.models.forEach(cat => { + const catId = (cat.get('id') || cat.id || '').toLowerCase(); + if (config[catId]) { + cat.set('label', config[catId].label); + cat.set('open', config[catId].open ?? true); + } + }); + + const catOrder = (m) => config[String((m.get('id') || m.id)).toLowerCase()]?.ord || 99; + const arr = categories.models.slice().sort((a,b) => catOrder(a) - catOrder(b)); + categories.reset(arr); + } + + // 4. Finaler DOM-Sweep + B.enforceCategoryOrder && B.enforceCategoryOrder(ed); + B.renderBlocks && B.renderBlocks(ed); + + } catch(e) { + console.error('[CustomPlugin] Error during normalize:', e); + } + }; + + // 5. Listener + editor.on('block:add block:remove block:reset', () => normalizeAndSort(editor)); + editor.on('load', () => { + normalizeAndSort(editor); + setTimeout(() => normalizeAndSort(editor), 100); + setTimeout(() => normalizeAndSort(editor), 800); + setTimeout(() => normalizeAndSort(editor), 1500); + }); + }); +})(window.grapesjs, window.BridgeParts); diff --git a/public/assets/js/bridge/custom-plugin.js b/public/assets/js/bridge/custom-plugin.js new file mode 100644 index 0000000..a4dd421 --- /dev/null +++ b/public/assets/js/bridge/custom-plugin.js @@ -0,0 +1,6 @@ +/* /assets/js/bridge/custom-plugin.js (FINALE VERSION: API-Logik Hülle) */ +(function(B){ + if (!B || typeof grapesjs === 'undefined') return; + + +})(window.BridgeParts || (window.BridgeParts = {})); diff --git a/public/assets/js/bridge/general-functions.js b/public/assets/js/bridge/general-functions.js new file mode 100644 index 0000000..0327082 --- /dev/null +++ b/public/assets/js/bridge/general-functions.js @@ -0,0 +1,118 @@ +/* /assets/js/bridge/general-functions.js (LOGIK-FIX: GLOBAL_DEBUG prüft als erstes) */ +(function(B){ + if (!B) return; + + // --- 🎯 1. ZENTRALE LOG-KONTROLLE (Konfiguration & Defaults) --- + B.LOG_CONFIG = B.LOG_CONFIG || {}; + + // Globale Steuerung: Deaktiviert ALLE Logs (außer force=true) + // 🛑 KRITISCHE KORREKTUR: Wir setzen den Wert nur, wenn er noch nicht gesetzt wurde (z.B. durch bridge-core.js) + B.LOG_CONFIG.GLOBAL_DEBUG = B.LOG_CONFIG.GLOBAL_DEBUG !== undefined ? B.LOG_CONFIG.GLOBAL_DEBUG : true; + + // Steuerung nach Log-Ebenen (wirken nur, wenn GLOBAL_DEBUG = true) + B.LOG_CONFIG.INFO_ENABLED = B.LOG_CONFIG.INFO_ENABLED !== undefined ? B.LOG_CONFIG.INFO_ENABLED : true; + B.LOG_CONFIG.WARN_ENABLED = B.LOG_CONFIG.WARN_ENABLED !== undefined ? B.LOG_CONFIG.WARN_ENABLED : true; + B.LOG_CONFIG.ERROR_ENABLED = B.LOG_CONFIG.ERROR_ENABLED !== undefined ? B.LOG_CONFIG.ERROR_ENABLED : true; + + // Steuerung für große Datenmengen (B.logData) + B.LOG_CONFIG.DATA_ENABLED = B.LOG_CONFIG.DATA_ENABLED !== undefined ? B.LOG_CONFIG.DATA_ENABLED : true; + + // NEU: Objekt zur Speicherung des individuellen Log-Status pro Plugin (Standard: leeres Objekt) + B.LOG_CONFIG.PLUGINS = B.LOG_CONFIG.PLUGINS || {}; + + /** + * Zentrale Log-Funktion mit Prüfung auf globale Schalter, Log-Ebenen und Plugin-spezifische Schalter. + * @param {string} pluginName - Der Name des aufrufenden Plugins (KRITISCH für die neue Logik). + * @param {string} message - Die zu loggende Nachricht. + * @param {string} color - CSS-Farbe für die Nachricht (optional). + * @param {string} type - Log-Typ ('info', 'warn', 'error'). + * @param {boolean} force - Wenn true, wird geloggt, auch wenn GLOBAL_DEBUG/Plugin-Log false ist. + */ + B.log = (pluginName, message, color = 'inherit', type = 'info', force = false) => { + const config = B.LOG_CONFIG; + + // 1. Prüfe auf force (immer loggen) + if (!force) { + // 🛑 KRITISCHE KORREKTUR: Prüfe auf GLOBAL_DEBUG an 2. Stelle (wenn nicht 'force') + if (!config.GLOBAL_DEBUG) { + return; + } + + // 2. Prüfe den PLUGIN-SPEZIFISCHEN SCHALTER + // Wenn der Schalter im PLUGINS-Objekt existiert UND auf false gesetzt ist, abbrechen. + const pluginStatus = config.PLUGINS[pluginName]; + if (pluginStatus === false) { + return; + } + + // 3. Prüfe auf spezifische Log-Ebenen-Schalter + if (type === 'info' && !config.INFO_ENABLED) return; + if (type === 'warn' && !config.WARN_ENABLED) return; + if (type === 'error' && !config.ERROR_ENABLED) return; + } + + // Führe das Logging aus + const stylePlugin = `color:orange; font-weight:bold;`; + const styleMessage = `color:${color}; font-weight:normal;`; + + const logFn = (type === 'error') ? console.error : (type === 'warn' ? console.warn : console.log); + + logFn(`%c[${pluginName}] %c${message}`, stylePlugin, styleMessage); + }; + + /** + * Spezielle Funktion zum Loggen großer Datenmengen (prüft B.LOG_CONFIG.DATA_ENABLED und Plugin-Schalter). + * Wird jetzt als Wrapper für B.log verwendet. + */ + B.logData = (pluginName, data) => { + // 1. Prüfe, ob das Daten-Logging global erlaubt ist + if (!B.LOG_CONFIG.DATA_ENABLED) return; + + // 2. Den "Daten-Ausgabe..." Log durch B.log schicken, um die Filter zu durchlaufen + // Wir verwenden force=false, damit GLOBAL_DEBUG und Plugin-Schalter angewendet werden + B.log(pluginName, 'Daten-Ausgabe (nächste Zeile):', 'gray', 'info', false); + + // 3. Wenn B.log den Filter passiert hätte, loggen wir hier das eigentliche Objekt (nur wenn GLOBAL_DEBUG true) + const pluginStatus = B.LOG_CONFIG.PLUGINS?.[pluginName]; + if (B.LOG_CONFIG.GLOBAL_DEBUG && pluginStatus !== false) { + console.log(data); // Das eigentliche Objekt-Log ohne Formatierung + } + }; + + + // --- 2. Hilfsfunktion zur Sortiergewichtung --- + const getSortWeight = (id) => { + if (['text', 'image', 'link', 'section', 'column', 'button', 'divider', 'map'].includes(id)) return 99; + if (id.startsWith('cust-')) return 1; + if (id.startsWith('lib-')) return 2; + if (id.endsWith('-fix') || id.endsWith('-flex')) { + return 3; + } + if (!id.includes('-')) return 99; + return 50; + }; + + // --- 3. Hilfsfunktion zur Sortierung --- + const sortBlocksByPrefixAndLabel = (blocks) => { + blocks.sort((a, b) => { + const aId = String((a.get ? a.get('id') : a.id) || ''); + const bId = String((b.get ? b.get('id') : b.id) || ''); + const aLabel = String((a.get ? a.get('label') : a.label) || '').toLowerCase(); + const bLabel = String((b.get ? b.get('label') : b.label) || '').toLowerCase(); + + const aWeight = getSortWeight(aId); + const bWeight = getSortWeight(bId); + + if (aWeight !== bWeight) return aWeight - bWeight; + if (aLabel < bLabel) return -1; + if (aLabel > bLabel) return 1; + + return 0; + }); + }; + + // --- 4. Funktionen zum BridgeParts-Objekt hinzufügen --- + B.getSortWeight = getSortWeight; + B.sortBlocksByPrefixAndLabel = sortBlocksByPrefixAndLabel; + +})(window.BridgeParts || (window.BridgeParts = {})); diff --git a/public/assets/js/bridge/helpers.js b/public/assets/js/bridge/helpers.js new file mode 100644 index 0000000..f448337 --- /dev/null +++ b/public/assets/js/bridge/helpers.js @@ -0,0 +1,39 @@ +/* /assets/js/bridge/helpers.js — Namespace + Utilities (kein ES-Module) */ +(function(w){ + var B = w.BridgeParts = w.BridgeParts || {}; + + B.post = function(m){ try { parent.postMessage(m,'*'); } catch{} }; + B.send = function(type, payload){ B.post(Object.assign({ source:'email-editor', type:type }, payload||{})); }; + B.log = function(msg){ B.post({ source:'bridge', type:'log', detail:String(msg||'') }); }; + + B.ready = function(cb){ (function t(){ if (w.grapesjs) return cb(); setTimeout(t,40); })(); }; + + B.BADGE = function(){ return document.getElementById('badge'); }; + B.badgeSay = function(txt, tone){ + var b = B.BADGE(); if(!b) return; + b.textContent = txt; + var cfg = { + ok: ['#ecfeff','#155e75','#a5f3fc'], + warn: ['#fef3c7','#92400e','#fde68a'], + err: ['#fee2e2','#7f1d1d','#fecaca'], + base: ['#eef2ff','#1e3a8a','#c7d2fe'] + }[tone||'base']; + b.style.background = cfg[0]; b.style.color = cfg[1]; b.style.borderColor = cfg[2]; + }; + + B.waitForBlocks = function(ed, opt){ + opt = opt || {}; + var timeoutMs = opt.timeoutMs || 4000, interval = opt.interval || 80; + var bm = ed.BlockManager, t0 = Date.now(); + return new Promise(function(resolve){ + (function tick(){ + var n = (bm && bm.getAll && bm.getAll().length) || 0; + if (n > 0 || Date.now() - t0 > timeoutMs) return resolve(n); + setTimeout(tick, interval); + })(); + }); + }; + + B.renderBlocks = function(ed){ try { ed.BlockManager.render(); } catch{} }; +})(window); + diff --git a/public/assets/js/bridge/library-api.js b/public/assets/js/bridge/library-api.js new file mode 100644 index 0000000..e5eb60c --- /dev/null +++ b/public/assets/js/bridge/library-api.js @@ -0,0 +1,246 @@ +/* /assets/js/bridge/library-api.js (FINAL & KORRIGIERT FÜR FLEXIBLE API-BASES) */ + +(function(B){ +     +    // 🛑 WICHTIG: Globalen Cache-Speicher initialisieren (wird von blocks-api.js gelesen) +    B.ApiItemCache = B.ApiItemCache || {}; + +    if (!B || typeof grapesjs === 'undefined') return; + +    const PluginName = 'bridge-library-api'; + + // NEU: Standard-API-Basis für Abwärtskompatibilität, falls nichts konfiguriert + const API_BASE_FALLBACK = (B.API_BASE || '/api/editor'); + +    // Konstanten +    const TARGET_CAT_ID = 'custom'; + const PLACEHOLDER_ID = 'api-placeholder-loading'; + const REFERENCE_COMPONENT_TYPE = 'library-reference'; + +    if (B.LOG_CONFIG && B.LOG_CONFIG.PLUGINS) { +        B.LOG_CONFIG.PLUGINS[PluginName] = true;  +    } + +    const log = (type, message, color = '#6A5ACD', logType = 'info', force = false) => { +        if (typeof B.log === 'function') { +            B.log(PluginName, `[${type}] ${message}`, color, logType, force); +        } else { +            if (logType === 'error') { +                 console.error(`%c[${PluginName} - ${type}] %c${message}`, 'color:red; font-weight:bold;', 'color:inherit;'); +            } +        } +    }; +    const logApiData = (data) => B.logData(PluginName, data); + +    log('INIT', 'API-Schicht initialisiert.'); +     +    // --- HILFSFUNKTIONEN --- + + /** + * Gibt die korrekte API-Basis-URL für einen Ressourcentyp (kind) zurück. + * Nutzt die zentrale Map B.RESOURCE_API_BASES, die in category-config.js gefüllt wurde. + */ + const getApiBase = (resource) => { + // Fallback auf die konfigurierte Standard-Basis, falls die Map noch nicht existiert oder der Eintrag fehlt. + return (B.RESOURCE_API_BASES && B.RESOURCE_API_BASES[resource]) || API_BASE_FALLBACK; + }; + +    const buildApiUrl = (resource, action='list', params = {}) => { + // KORREKTUR: Nutzt jetzt die dynamisch ermittelte API-Basis + const apiBase = getApiBase(resource); + +        const url = new URL(apiBase, window.location.origin); +         +        url.searchParams.set('resource', resource); +        url.searchParams.set('action', action); +         +        Object.entries(params).forEach(([key, value]) => { +            if (value !== null && value !== undefined) url.searchParams.set(key, value); +        }); +        return url.toString(); +    }; + +    const shouldLoad = (resource) => { +        const mode = (B.EDITOR_MODE || 'TEMPLATES').toUpperCase(); +         + // HINWEIS: Hier muss für neue Ressourcen (wie 'products') ggf. der mode angepasst werden, + // falls sie nicht in TEMPLATES geladen werden sollen. +        switch (mode) { +            case 'TEMPLATES': +                const templateResources = ['templates', 'sections', 'blocks', 'snippets', 'products']; // Beispiel: products hinzugefügt +                return templateResources.includes(resource); + +            case 'SECTIONS': +                const sectionResources = ['blocks', 'snippets']; +                return sectionResources.includes(resource); + +            case 'BLOCKS': +                return resource === 'snippets'; +             +            default: +                log('MODE WARN', `Unbekannter Editor Modus '${mode}' festgestellt.`, 'orange', 'warn'); +                return resource === 'snippets'; +        } +    }; + + +    const fetchData = (resource, action='list', params = {}) => { + // ... (Rest der fetchData-Funktion bleibt unverändert, nutzt aber die korrigierte buildApiUrl) +        const url = buildApiUrl(resource, action, params);  +        const cacheKey = action === 'get' ? `${resource}-${params.id}` : null; + +        // Cache-Check verwendet B.ApiItemCache +        if (cacheKey && B.ApiItemCache.hasOwnProperty(cacheKey)) { +            log('CACHE HIT', `Cache Hit für /${resource}-${cacheKey}.`, '#708090', 'info'); +            return Promise.resolve(B.ApiItemCache[cacheKey]); +        } + +        return fetch(url, { +            method: 'GET', +            headers: {  +                'Content-Type': 'application/json'  +            },  +        }) +            .then(response => { +                if (!response.ok) { +                    log('API ERROR', `API-Aufruf fehlgeschlagen für /${resource}/${action}: ${response.status} (${response.statusText})`, 'red', 'error'); +                    // 💡 KORREKTUR: Bei HTTP-Fehler immer ein leeres Array für LIST und leeres Objekt für GET zurückgeben. +                    return action === 'get' ? {} : { items: [] };  +                } +                return response.json(); +            }) +            .then(data => { +                if (data.ok === false) { +                    log('API ERROR', `API-Fehler für /${resource}: ${data.error || 'Unbekannt'}`, 'red', 'error'); +                    // 💡 KORREKTUR: Bei API-Fehler ('ok: false') immer leeres Array/Objekt zurückgeben. +                    return action === 'get' ? {} : { items: [] }; +                } +                 +                const result = data.items || data.data || data.item; +                const finalResult = result ? (Array.isArray(result) ? result : (action === 'list' ? (result.items || []) : result)) : (action === 'list' ? [] : {}); + +                const resultIsArray = Array.isArray(finalResult); +                const resultLength = resultIsArray ? finalResult.length : (Object.keys(finalResult).length > 0 ? 1 : 0); + +                log('EXTRACT SUCCESS', `Extrahiert ${resultLength} Elemente (Typ: ${action}) für /${resource}.`); +                 +                // Cache-Speicherung verwendet B.ApiItemCache +                if (cacheKey && resultLength > 0) { +                    B.ApiItemCache[cacheKey] = finalResult; +                } +                 +                // 💡 KORREKTUR: Bei LIST (action='list') geben wir immer ein Array zurück, sonst das Objekt +                return finalResult; +            }) +            .catch(error => { +                log('FETCH ERROR', `FEHLER beim Fetchen oder Parsen von /${resource}: ${error.message}`, 'red', 'error', true); +                return action === 'get' ? {} : []; +            }); +    }; + +// --- Exportierte Core-Funktionen (jetzt generisch) --- + + // NEU: Generische Fetch-Funktion für jeden Ressourcentyp ('kind') + B.fetchResource = (kind) => { +        if (!shouldLoad(kind)) { +            log('BLOCKED', `Blockiert: ${kind} (Modus: ${B.EDITOR_MODE})`, '#708090', 'info'); +            return Promise.resolve([]); +        } +        return fetchData(kind).then(items => Array.isArray(items) ? items : []); + }; + + // Die alten hardcodierten Funktionen verwenden jetzt die neue generische Funktion + B.fetchTemplates = () => B.fetchResource('templates'); +    B.fetchSnippets = () => B.fetchResource('snippets'); +    B.fetchSections = () => B.fetchResource('sections'); +    B.fetchBlocks = () => B.fetchResource('blocks'); + +    B.getApiItem = (kind, id) => fetchData(kind, 'get', { id: id });  + +    B.clearApiCache = () => { +        B.ApiItemCache = {}; // Cache leeren +        log('CACHE CLEAR', `API-Cache geleert.`, 'orange', 'warn'); +    }; + +    // 🚀 Zentrale Funktion zum Laden und Registrieren der Blöcke + B.loadAndRegisterApiBlocks = (editor) => { + const bm = editor.BlockManager; + + // NEU: Ressourcen-Kinds aus der Konfiguration sammeln + const resourceKindsToLoad = Object.keys(B.RESOURCE_API_BASES || {}); + + if (resourceKindsToLoad.length === 0) { + log('FEHLER', 'Keine Ressourcen-Kind-Konfiguration (B.RESOURCE_API_BASES) gefunden.', '#dc3545', 'error', true); + bm.remove(PLACEHOLDER_ID); + return; + } + + // Map aller Fetch-Promises erstellen + const fetchPromises = resourceKindsToLoad.map(kind => + B.fetchResource(kind).then(items => items.map(i => ({ ...i, kind: kind }))) + ); + + + log('API START', `Starte Promise.all für API-Abruf der Blöcke/Sektionen (${resourceKindsToLoad.join(', ')})...`, '#1E90FF'); + + Promise.all(fetchPromises) + .then(results => { + const apiItems = results.flat().filter(item => item && item.id); +   + log(`API SUCCESS`, `${apiItems.length} Elemente gefunden.`, '#9400D3'); + logApiData(apiItems);  +   + if (apiItems.length === 0) { + log('NO DATA', 'Keine API-Daten gefunden.', 'orange', 'warn', true); + } else { + apiItems.forEach(item => { + const blockId = `lib-${item.kind}-${item.id}`; + const label = item.name || item.label || 'Unbenannter Block'; + const itemKindUpper = item.kind.toUpperCase(); +   + // Hier wird der Block-Manager-Block registriert + // ... (Der Rest der Logik bleibt unverändert) ... + const blockDefinition = { + label: label, + category: TARGET_CAT_ID, +                             // 💡 KORREKTUR: Immer die library-reference-Komponente verwenden, um die Referenz-Logik +                             // (mit editable: false) aus blocks-api.js zu erzwingen. + content: { + type: REFERENCE_COMPONENT_TYPE, + 'lib-kind': item.kind, + 'lib-id': item.id, +                                 // NEU: startContent wird nur als reines HTML übergeben. +                                 // Die Logik in blocks-api.js (init/reloadComponentContent) kümmert sich um die Anzeige. + startContent: item.html || item.content || '
🛑 Fehler: Inhalt fehlte beim Laden.
', +                                 content: '', // Wichtig: Beim Drop keinen GrapesJS-Content setzen + }, + attributes: { 'title': itemKindUpper }, + media: item.preview_url ? `` : '', + }; + bm.add(blockId, blockDefinition); + }); +   + bm.remove(PLACEHOLDER_ID); + log(`REGISTRATION`, `${apiItems.length} API-Blöcke registriert. Platzhalter entfernt.`, '#008000'); + + const reloadExistingComponents = () => { + const allComponents = editor.DomComponents.getWrapper().find(`[data-gjs-type="${REFERENCE_COMPONENT_TYPE}"]`); + allComponents.forEach(component => { + if (component.get('lib-id') && component.components().length === 0 && typeof component.reloadComponentContent === 'function') { + log(`RELOAD START`, `Lade ${component.get('lib-kind')}/${component.get('lib-id')} nach Cache-Füllung (Sicherheitsnetz).`, '#FF4500'); + component.reloadComponentContent({ forced: true, reason: 'EXISTING_CONTENT_RELOAD' });  + } + }); + }; + + setTimeout(reloadExistingComponents, 100); + } + }) + .catch(error => { + // Hier wird der Fehler von fetchData oder map abgefangen + log('FETCH ERROR', `FEHLER beim Laden der API-Blöcke: ${error.message}`, '#dc3545', 'error', true); + bm.remove(PLACEHOLDER_ID); + }); + }; + +})(window.BridgeParts || (window.BridgeParts = {})); diff --git a/public/assets/js/bridge/library-parts.js b/public/assets/js/bridge/library-parts.js new file mode 100644 index 0000000..a6381bd --- /dev/null +++ b/public/assets/js/bridge/library-parts.js @@ -0,0 +1,17 @@ +/* /assets/js/bridge/library-parts.js (BEREINIGT) */ + +(function(B){ + // Alle API-spezifischen Funktionen (fetchData, fetchTemplates, etc.) + // und der apiItemCache wurden nach library-api.js verschoben. + + if (!B || typeof grapesjs === 'undefined') return; + + const PluginName = 'bridge-library-parts-core'; + + if (B.LOG_CONFIG && B.LOG_CONFIG.PLUGINS) { + B.LOG_CONFIG.PLUGINS[PluginName] = false; + } + + // Zusätzliche Core-Funktionen, die nicht API-spezifisch sind, würden hier verbleiben. + +})(window.BridgeParts || (window.BridgeParts = {})); diff --git a/public/assets/js/bridge/library-plugin.js_NV b/public/assets/js/bridge/library-plugin.js_NV new file mode 100644 index 0000000..973d2e6 --- /dev/null +++ b/public/assets/js/bridge/library-plugin.js_NV @@ -0,0 +1,19 @@ +/* /assets/js/bridge/library-plugin.js (Plugin für Standard-Bausteine) */ +(function(B){ + if (!B || typeof grapesjs === 'undefined') return; + + const PluginName = 'bridge-library-plugin'; + + /** + * GrapesJS Plugin Registrierung: bridge-library-plugin + * Dieses Plugin dient als Platzhalter für die zukünftige Konfiguration + * der Standard-Blöcke (Bausteine). Es fügt aktuell keine Blöcke hinzu, + * sondern wartet auf die Blöcke aus dem Preset (gjs-preset-newsletter). + * Der Categorization Master wird diese Blöcke später in die Kategorie 'bausteine' verschieben. + */ + grapesjs.plugins.add(PluginName, (editor, opts = {}) => { + console.log(`[${PluginName}] Plugin registriert. Erwartet Blöcke vom Preset.`); + // ToDo: Zukünftige Standardblöcke hier hinzufügen + }); + +})(window.BridgeParts || (window.BridgeParts = {})); diff --git a/public/assets/js/bridge/library.js b/public/assets/js/bridge/library.js new file mode 100644 index 0000000..74c98a6 --- /dev/null +++ b/public/assets/js/bridge/library.js @@ -0,0 +1,166 @@ +/* /assets/js/bridge/library.js — Kategorien, Defaults, Snippets (FINAL UND KORRIGIERT) */ +(function(w){ +  var B = w.BridgeParts = w.BridgeParts || {}; + if (!B.CATEGORY_CONFIG) B.CATEGORY_CONFIG = {}; // Muss vorhanden sein + +  /* Panels/Views sicherstellen (Unverändert) */ +  B.ensureViews = function(ed){ +    var pn = ed.Panels; +    if (!pn.getPanel('views')) pn.addPanel({ id:'views' }); +    if (!pn.getButton('views','open-blocks')) +      pn.addButton('views',[{ id:'open-blocks', command:'open-blocks', togglable:1, className:'gjs-pn-btn' }]); +    if (!pn.getButton('views','open-layers')) +      pn.addButton('views',[{ id:'open-layers', command:'open-layers', togglable:1, className:'gjs-pn-btn' }]); +    if (!pn.getButton('views','open-sm')) +      pn.addButton('views',[{ id:'open-sm', command:'open-sm', togglable:1, className:'gjs-pn-btn' }]); +    try{ var b=pn.getButton('views','open-blocks'); b && b.set('active',true); }catch{} +  }; + +  /* Helpers --------------------------------------------------------------- */ +  function addOnce(bm, id, def){ +    if (!id || typeof id !== 'string') return; +    try{ if (bm.get && bm.get(id)) return; bm.add(id, def); }catch{} +  } + +  // Kategorien erzeugen (Funktion unverändert) +  function forceCategory(bm, id, label, open){ +    try{ +      if (typeof bm.addCategory === 'function') { +        var cts = bm.getCategories && bm.getCategories(); +        var find = function(){ +          if (!cts) return null; +          if (typeof cts.findWhere === 'function') { +            return cts.findWhere({ id }) || cts.findWhere({ label }); +          } +          var arr = cts.models || cts || []; +          for (var i=0;i', content:'
' }); +  addOnce(bm,'blk-btn', { label:'Button', category:cat_bausteine, media:'', content:'
Call to Action
' }); +  addOnce(bm,'blk-text', { label:'Text', category:cat_bausteine, media:'', content:'

Überschrift

Fließtext …

' }); +  addOnce(bm,'blk-2cols', { label:'2 Spalten', category:cat_bausteine, media:'', content:'

Linke Spalte

Rechte Spalte

' }); +  addOnce(bm,'blk-600', { label:'Container 600px', category:cat_bausteine, media:'', content:'

Inhalt hier hinein …

' }); +  addOnce(bm,'blk-hr', { label:'Trenner', category:cat_bausteine, media:'', content:'

' }); +  addOnce(bm,'blk-spacer', { label:'Abstand', category:cat_bausteine, media:'', content:'
 
' }); +  }; + +  /* Snippets → Custom (Initiale Zuweisung zur ID 'custom') */ +  B.replaceSnippetBlocks = function(ed, list){ +    try{ +      var bm = ed.BlockManager; +      B._ensureCategories(bm); + +      var all = (bm.getAll && bm.getAll()) || []; +      (all.models || all).forEach(function(b){ +        if (!b) return; +        var id=b.get&&b.get('id'); +        // Entferne alte Snippets +        if(id && String(id).startsWith('snip-')) try{ bm.remove(id); }catch{} +      }); + +      // Explizite Kategorie-Definition basierend auf der ID 'custom' +      var cat_custom = { id:'custom', label:B.CATEGORY_CONFIG.custom.label, open:true }; + + +      (list||[]).forEach(function(raw){ +        if(!raw) return; +        var html = raw.html || raw.content || ''; +        if(!html) return; +        var id = 'snip-'+(raw.id ?? ('x'+Math.random().toString(36).slice(2))); +        addOnce(bm, id, { +          label: raw.name || ('Snippet '+(raw.id ?? '')), +          // Zuweisung zur 'Custom' Kategorie +          category: cat_custom, +          media:'', +          content: html +        }); +      }); + +    }catch{} +    B.renderBlocks && B.renderBlocks(ed); +  }; + +  /* Snippets nachladen (für Buttons) */ +  B.fetchSnippets = async function(){ +    try{ +      var res = await fetch('../api.php?resource=snippets&action=list&t='+Date.now(), { +        credentials:'same-origin', cache:'no-store', headers:{'Cache-Control':'no-cache'} +      }); +      var rows = await res.json(); +      rows = rows && rows.items ? rows.items : (Array.isArray(rows) ? rows : []); +      return rows.map(function(r){ return { id:r.id, name:r.name, html:r.content||r.html||'' }; }); +    }catch(e){ B.log && B.log('reload-snippets-error:'+e); return []; } +  }; + +})(window); diff --git a/public/assets/js/bridge/refs.js b/public/assets/js/bridge/refs.js new file mode 100644 index 0000000..d2ee9f8 --- /dev/null +++ b/public/assets/js/bridge/refs.js @@ -0,0 +1,166 @@ +/* /assets/js/bridge/refs.js — Referenzen & Custom Fix/Flex (FINAL KORRIGIERT: Snippet Cleanup) */ +(function (w) { +  var B = w.BridgeParts = w.BridgeParts || {}; +  if (!B.CATEGORY_CONFIG) B.CATEGORY_CONFIG = {};  + +  /* ---------- Basis-Konfig (unverändert) ---------- */ +  var SHOW_SNIPPETS_IN_FIX_DEFAULT = false; +  var MODE = (window.__editorMode || 'templates').toLowerCase(); + +  /* ---------- Hilfs-UI (unverändert) ---------- */ +  B.editorRefPlaceholder = function (type, id, name) { +    var safe = (name || '').replace(/[<>&"]/g, ''); +    return { +      html: +        '
' + +        'Ref: ' + type + ' #' + id + '' + +        '
' + safe + '
' + +        '
' +    }; +  }; + +  /* ---------- Loader (REST) (unverändert) ---------- */ +  async function jsonList(url){ +    try{ +      var res = await fetch(url, { credentials:'same-origin', cache:'no-store' }); +      var data = await res.json(); +      return data && data.items ? data.items : (Array.isArray(data) ? data : []); +    }catch(e){ return []; } +  } +  B.fetchTemplates = async function(){  +    var rows = await jsonList('../api.php?action=templates.list&t='+Date.now()); +    return rows.map(r => ({ id:r.id, name:r.name })); +  }; +  B.fetchTemplateFull = async function (id) { +    try { +      var url = '../api.php?action=templates.get&id=' + encodeURIComponent(id) + '&t=' + Date.now(); +      var res = await fetch(url, { credentials: 'same-origin', cache: 'no-store' }); +      var data = await res.json(); +      var it = data && (data.item || data); +      return (it && (it.html || it.content)) ? (it.html || it.content) : ''; +    } catch (e) { return ''; } +  }; +  B.fetchSections = async function(){ +    var rows = await jsonList('../api.php?action=sections.list&t='+Date.now()); +    return rows.map(r => ({ id:r.id, name:r.name, html:r.html || '' })); +  }; +  B.fetchBlocks = async function(){ +    var rows = await jsonList('../api.php?action=blocks.list&t='+Date.now()); +    return rows.map(r => ({ id:r.id, name:r.name, html:r.html || '' })); +  }; +  B.fetchSnippets = async function(){ +    var rows = await jsonList('../api.php?action=snippets.list&t='+Date.now()); +    return rows.map(r => ({ id:r.id, name:r.name, html:r.html || r.content || '' })); +  }; + +  /* ---------- lokale Helfer (unverändert) ---------- */ +  function addOnce(bm, id, def){ +    if (!id || typeof id !== 'string') return; +    try{ if (bm.get && bm.get(id)) return; bm.add(id, def); }catch{} +  } +  function removeByPrefix(bm, prefix){ +    try{ +      var all = (bm.getAll && bm.getAll()) || []; +      (all.models || all).forEach(function(b){ +        if (!b) return; +        var id = (b.get && b.get('id')) || b.id || ''; +        if (id && String(id).startsWith(prefix)) { +          try{ bm.remove(id); }catch{} +        } +      }); +    }catch{} +  } + +  /* ---------- Referenzbibliothek (lib-*) (angepasst: Zuweisung zu 'custom') ---------- */ +  B.addReferenceLibrary = function (ed, payload) { +    payload = payload || {}; +    var templates = payload.templates || []; +    var sections  = payload.sections  || []; +    var blocks    = payload.blocks    || []; + + // Aggressive Bereinigung aller lib-tpl-ref-* Blöcke + removeByPrefix(ed.BlockManager, 'lib-tpl-ref-'); + +    var bm = ed.BlockManager; +    if (B._ensureCategories) B._ensureCategories(bm); // Stellt sicher, dass die Hauptkategorien existieren + +    // Explizite Kategorie-Definitionen +    var cat_templates = { id:'lib-templates', label:B.CATEGORY_CONFIG['lib-templates'].label, open:true }; +    var cat_custom = { id:'custom', label:B.CATEGORY_CONFIG.custom.label, open:true }; +     +    // Template-Referenzen (Prio 1) - NUR IM TEMPLATE-MODUS HINZUFÜGEN + if (MODE === 'templates') { +      templates.forEach(function (t) { +        addOnce(bm, 'lib-tpl-ref-' + t.id, { +          label: (t.name || ('Vorlage #' + t.id)), +          category: cat_templates, // Zuweisung zur Prio 1 +          media: '', +          content: B.editorRefPlaceholder('template', t.id, t.name).html +        }); +      }); + } + +    // Sections-Referenzen (werden zu Custom umgeleitet, Prio 2) +    sections.forEach(function (s) { +      addOnce(bm, 'lib-sec-' + s.id, { +        label: s.name || ('Section #' + s.id), +        category: cat_custom, // Explizit Custom +        media: '', +        content: B.editorRefPlaceholder('section', s.id, s.name).html +      }); +    }); + +    // Blocks-Referenzen (werden zu Custom umgeleitet, Prio 2) +    blocks.forEach(function (b) { +      addOnce(bm, 'lib-blk-' + b.id, { +        label: b.name || ('Block #' + b.id), +        category: cat_custom, // Explizit Custom +        media: '', +        content: B.editorRefPlaceholder('block', b.id, b.name).html +      }); +    }); +  }; + +  /* ---------- Custom Fix/Flex (ENTFERNT / GELEERT) ---------- */ +  B.addCustomLibrary = function (ed, payload, mode) { +    /* (Keine Aktion nötig.) */ +  }; + + // WICHTIGE NEUE FUNKTION: Entfernt alle alten Snippet-Blöcke + B.addEditableTemplatesLibrary = function(ed) { + // Aggressive Bereinigung aller alten flexiblen Snippet-Blöcke, + // um Konflikte mit den neuen custom-snippet-* Blöcken zu vermeiden. + removeByPrefix(ed.BlockManager, 'snip-'); + return Promise.resolve(); + }; + +  /* ---------- Ref-Sammlung für Speichern/Render (unverändert) ---------- */ +  B.collectRefs = function (ed) { +    var root = ed.getWrapper && ed.getWrapper(); +    var els = root && root.find ? root.find('[data-ref-type]') : []; +    var out = []; +    if (Array.isArray(els) && els.length) { +      els.forEach(function (el) { +        try { +          var m = el.getAttributes ? el.getAttributes() : {}; +          var t = (m['data-ref-type'] || '').toString().toLowerCase(); +          var i = parseInt(m['data-ref-id'] || '0', 10); +          if (!t || !i) return; +          if (!/^(template|section|block|snippet)$/.test(t)) return; +          if (t === 'snippet') return; // Snippets immer flex/by value + +          out.push({ +            sort: out.length, +            ref_type: t === 'template' ? 'section' : t, +            ref_id: i, +            overrides_json: null, +            lock_to_version: null +          }); +        } catch {} +      }); +    } +    return out; +  }; + +})(window); diff --git a/public/assets/js/toast.js b/public/assets/js/toast.js new file mode 100644 index 0000000..aef07d2 --- /dev/null +++ b/public/assets/js/toast.js @@ -0,0 +1,57 @@ +// assets/js/toast.js +// Shows toast in the TOP LAYER: if a exists, append inside it. +// Otherwise append to . Default type = success (green). + +window.Toast = (function () { + // create (or reuse) a toast root inside a given container + function ensureRoot(container) { + // Find last (topmost) open dialog if not explicitly passed + const host = container || (() => { + const dialogs = Array.from(document.querySelectorAll('dialog[open]')); + return dialogs.length ? dialogs[dialogs.length - 1] : document.body; + })(); + + // Root per container (class-based to allow multiple roots) + let root = host.querySelector(':scope > .toast-root'); + if (!root) { + root = document.createElement('div'); + root.className = 'toast-root'; + host.appendChild(root); + } + return root; + } + + function render(msg, type, duration, container) { + const root = ensureRoot(container); + + const n = document.createElement('div'); + n.className = 'toast' + (type === 'error' ? ' error' : ' success'); + n.innerHTML = ` + ${type === 'error' ? '⚠️' : '✅'} + ${msg || ''} + + `; + root.appendChild(n); + + const close = () => { try { n.remove(); } catch {} }; + n.querySelector('.close')?.addEventListener('click', close); + + const t = setTimeout(close, Number(duration) || 2200); + // clean timer if user closes early + n.addEventListener('remove', () => clearTimeout(t), { once:true }); + } + + // API + function show(msg, opt) { + opt = opt || {}; + render( + msg, + opt.type === 'error' ? 'error' : 'success', + opt.duration, + opt.container // optional: pass a specific container + ); + } + + return { show }; +})(); + diff --git a/public/assets/js/ui-auth.js b/public/assets/js/ui-auth.js new file mode 100644 index 0000000..97c9b61 --- /dev/null +++ b/public/assets/js/ui-auth.js @@ -0,0 +1,69 @@ +// assets/js/ui-auth.js +/** + * Bindet einen Logout-Button und leitet nach dem Logout weiter (default: /login.php). + * Usage: + * import { mountLogoutButton, ensureFloatingLogout } from './ui-auth.js'; + * mountLogoutButton('#btn-logout', { redirect: '/login.php' }); + */ +export function mountLogoutButton(selector = '#btn-logout', opts = {}) { + const { redirect = '/login.php' } = opts; + const btn = document.querySelector(selector); + if (!btn) return; + + // Doppelte Bindings verhindern + if (btn.dataset.bound === '1') return; + + btn.addEventListener('click', async (e) => { + e.preventDefault(); + btn.disabled = true; + const oldText = btn.textContent; + btn.textContent = 'Abmelden…'; + try { + await fetch('api.php?action=auth.logout', { + method: 'POST', + credentials: 'include', + headers: { 'Content-Type': 'application/json' } + }); + } catch (err) { + console.error('Logout failed', err); + // Fallback: trotzdem auf Login + } finally { + window.location.href = redirect; + // Falls Redirect durch Policy o.ä. blockiert wäre: + setTimeout(() => { + btn.disabled = false; + btn.textContent = oldText; + }, 1500); + } + }); + + btn.dataset.bound = '1'; +} + +/** + * Erzeugt bei Bedarf automatisch einen Floating-Logout-Button (oben rechts) + * und bindet ihn (gut für Staging/Admin). + */ +export function ensureFloatingLogout(opts = {}) { + if (document.querySelector('#btn-logout')) { + mountLogoutButton('#btn-logout', opts); + return; + } + const btn = document.createElement('button'); + btn.id = 'btn-logout'; + btn.textContent = 'Logout'; + Object.assign(btn.style, { + position: 'fixed', + right: '12px', + top: '12px', + zIndex: '10000', + padding: '8px 12px', + borderRadius: '8px', + border: '1px solid #ccc', + background: '#f5f5f5', + cursor: 'pointer' + }); + document.body.appendChild(btn); + mountLogoutButton('#btn-logout', opts); +} + diff --git a/public/assets/js/ui-create.js b/public/assets/js/ui-create.js new file mode 100644 index 0000000..eed1a7c --- /dev/null +++ b/public/assets/js/ui-create.js @@ -0,0 +1,26 @@ +import { apiList, apiCreate, toast } from './api.js'; +export function initCreate(){ + const btn=document.getElementById('btn-new'), dlg=document.getElementById('createDialog'), form=document.getElementById('createForm'), fields=document.getElementById('createFields'), hint=document.getElementById('createHint'); + if(!btn||!dlg||!form||!fields) return; + const curTab=()=>{ const a=document.querySelector('nav [data-tab].bg-sky-50')||document.querySelector('nav [data-tab]'); return a?a.getAttribute('data-tab'):'templates'; }; + + btn.onclick = async ()=>{ + fields.innerHTML=''; const tab=curTab(); + const name=document.createElement('input'); name.type='text'; name.required=true; name.placeholder='Name*'; name.className='w-full border rounded-lg px-3 py-2'; name.id='f-name'; fields.appendChild(name); + async function addSel(id,label,res){ const sel=document.createElement('select'); sel.id=id; sel.className='w-full border rounded-lg px-3 py-2'; sel.innerHTML=``; const data=await apiList(res); (data||[]).forEach(t=>{ const o=document.createElement('option'); o.value=t.id; o.textContent=`#${t.id} · ${t.name||''}`; sel.appendChild(o); }); fields.appendChild(sel); } + if(tab==='sections') await addSel('f-template','Template','templates'); + if(tab==='blocks') await addSel('f-section','Section','sections'); + if(tab==='snippets') await addSel('f-block','Block','blocks'); + hint.textContent=`Neues ${tab} anlegen`; dlg.showModal(); + + form.onsubmit=async(e)=>{ e.preventDefault(); + const payload={ name:(document.getElementById('f-name')?.value||'').trim() }; if(!payload.name) return; + if(tab==='snippets') payload.content=''; else payload.html=''; + if(tab==='sections') payload.template_id=document.getElementById('f-template')?.value||null; + if(tab==='blocks') payload.section_id =document.getElementById('f-section')?.value ||null; + if(tab==='snippets') payload.block_id =document.getElementById('f-block')?.value ||null; + const r=await apiCreate(tab,payload); if(r&&r.id){ dlg.close(); toast('Erstellt',true); window.loadList && window.loadList(tab); } else { toast('Erstellen fehlgeschlagen',false,{duration:3000}); console.error('Create failed',r); } + }; + }; + const cancel=document.getElementById('createCancel'); cancel && (cancel.onclick=()=>dlg.close()); +} diff --git a/public/assets/js/ui-editor.js b/public/assets/js/ui-editor.js new file mode 100644 index 0000000..0249941 --- /dev/null +++ b/public/assets/js/ui-editor.js @@ -0,0 +1,438 @@ +/* /assets/js/ui-editor.js (KORRIGIERT: Speichern wird an iFrame-Editor delegiert) */ +// Öffnen, Befüllen, Speichern (mit Live-HTML), Preview – Race-Schutz & Lade-Overlay. + +import { apiUpdate, apiList, apiGet, toast, apiAction } from './api.js'; + +export function initEditor() { +  // ... (Alle Konstanten bleiben unverändert) ... +  const dlg          = document.getElementById('editorDialog'); +  const iframe       = document.getElementById('editorFrame'); +  const btnSave      = document.getElementById('btn-save'); +  const btnPreview   = document.getElementById('btn-preview'); +  const btnTest      = document.getElementById('btn-test'); +  const btnClose     = document.getElementById('btn-close'); +  const btnClear     = document.getElementById('btn-clear-main'); + +  const prevDlg      = document.getElementById('previewDialog'); +  const sendDlg      = document.getElementById('sendTestDialog'); +  const sendForm     = document.getElementById('sendTestForm'); +  const sendTo       = document.getElementById('send_to'); +  const sendSubject  = document.getElementById('send_subject'); +  const btnCancelSend= document.getElementById('btn-cancel-send'); +  const btnSendNow   = document.getElementById('btn-send-now'); +  const prevFrame    = document.getElementById('previewFrame'); +  const btnPrevClose = document.getElementById('btn-close-preview'); + +  let current = null;   // { resource, id, name } +  let bridgeListener = null; +  let reqToken = 0;     // steigender Token pro Öffnen -> ignoriert verspätete Events + +  const ok  = (m) => toast(m, true); +  const err = (m) => toast(m, false); + +  // ---------- Hilfen ---------- +  function activeMode() { +    const b = document.querySelector('nav [data-tab].bg-sky-50, nav [data-tab].text-sky-700, nav [data-tab].active'); +    return (b?.dataset?.tab) || (current?.resource) || 'templates'; +  } + +  function writeHtmlToFrame(html) { +    iframe.srcdoc = ` +      +      ${html || ''} +    `; +  } + +  async function readEditedHtml() { +    const win = iframe?.contentWindow; +    const doc = iframe?.contentDocument; +    if (!win || !doc) return ''; + +    const ed = win.__gjs || (win.grapesjs && win.grapesjs.editors && win.grapesjs.editors[0]) || null; +    if (ed && typeof ed.getHtml === 'function') { +      const html = ed.getHtml(); +      const css  = (typeof ed.getCss === 'function') ? ed.getCss() : ''; +      return css ? `\n${html}` : html; +    } +    const root = doc.querySelector('#gjs') || doc.body || doc.documentElement; +    return root ? root.innerHTML : ''; +  } + +  function waitForEditor(maxMs = 8000) { +    return new Promise((resolve, reject) => { +      const start = Date.now(); +      (function poll() { +        const win = iframe?.contentWindow; +        const ed  = win?.__gjs || (win?.grapesjs && win.grapesjs.editors && win.grapesjs.editors[0]) || null; +        if (ed) return resolve(ed); +        if (Date.now() - start > maxMs) return reject(new Error('Editor not ready')); +        setTimeout(poll, 120); +      })(); +    }); +  } +   +  // 🚨 NEUE FUNKTION: Delegiert das Kommando an den Editor im iFrame +  async function delegateCommand(commandName) { +    try { +      const editor = await waitForEditor(3000); +      if (editor.Commands.has(commandName)) { +        // Führt den Command im iFrame aus (z.B. 'save-data') +        editor.runCommand(commandName); +        return true; +      } else { +        err(`Delegieren fehlgeschlagen: Command '${commandName}' nicht gefunden.`); +        return false; +      } +    } catch (e) { +      err(`Delegieren fehlgeschlagen: Editor nicht bereit (${commandName}).`); +      console.error(e); +      return false; +    } +  } +  // ... (hideReadyBadge bleibt unverändert) ... +  function hideReadyBadge(doc) { +    if (!doc) return; +    const kill = () => { +      const el = doc.getElementById('badge'); +      if (el) el.style.display = 'none'; +    }; +    kill(); + +    const style = doc.createElement('style'); +    style.textContent = ` +      #badge { display:none !important; } +      .gjs-pn-status { display:none !important; } +      .ready-badge, +      .status-badge.ready, +      [data-status="ready"], +      [data-badge="ready"], +      .gjs-ready, +      .gjs-badge-ready { display:none !important; } +    `; +    doc.head.appendChild(style); + +    const mo = new MutationObserver(() => { kill(); /* hideByText(doc); */ }); +    mo.observe(doc.documentElement, { childList: true, subtree: true }); + +    setTimeout(() => { kill(); /* hideByText(doc); */ }, 150); +    setTimeout(() => { kill(); /* hideByText(doc); */ }, 500); +    setTimeout(() => { kill(); /* hideByText(doc); */ }, 1200); +  } +   +  // ... (Lade-Overlay bleibt unverändert) ... +  let veilEl = null; +  function ensureVeil() { +    if (veilEl) return veilEl; +    veilEl = document.createElement('div'); +    Object.assign(veilEl.style, { +      position:'absolute', inset:'0', background:'rgba(248,250,252,.85)', +      display:'flex', alignItems:'center', justifyContent:'center', +      zIndex:'2147483000', fontFamily:'system-ui, -apple-system, Segoe UI, Roboto, Arial', +      fontSize:'14px', color:'#0f172a' +    }); +    veilEl.innerHTML = ` +     
+       
+       
Lade Editor …
+     
+      +    `; +    const host = dlg?.querySelector('.h-full, .flex, .flex-col') || dlg; +    (host || document.body).appendChild(veilEl); +    return veilEl; +  } +  function showVeil(){ ensureVeil().style.display = 'flex'; } +  function hideVeil(){ if (veilEl) veilEl.style.display = 'none'; } + +  // ... (Kontext-Filter-Ladung bleibt unverändert) ... +  async function listBlocksForTemplate(templateId){ +    try { +      const direct = await apiList('blocks', { template_id: templateId }); +      if (Array.isArray(direct) && direct.length) return direct; +    } catch {} +    const sections = await apiList('sections', { template_id: templateId }).catch(()=>[]); +    const out = []; +    for (const s of (sections || [])) { +      const b = await apiList('blocks', { section_id: s.id }).catch(()=>[]); +      if (b?.length) out.push(...b); +    } +    return out; +  } +  // Snippets eines Templates (direkt oder via Sections->Blocks als Fallback) +  async function listSnippetsForTemplate(templateId){ +    try { +      const direct = await apiList('snippets', { template_id: templateId }); +      if (Array.isArray(direct) && direct.length) return direct; +    } catch {} +    const sections = await apiList('sections', { template_id: templateId }).catch(()=>[]); +    const blocksAll = []; +    for (const s of (sections || [])) { +      const b = await apiList('blocks', { section_id: s.id }).catch(()=>[]); +      if (b?.length) blocksAll.push(...b); +    } +    const out = []; +    for (const b of blocksAll) { +      const sn = await apiList('snippets', { block_id: b.id }).catch(()=>[]); +      if (sn?.length) out.push(...sn); +    } +    return out; +  } +  // Referenz-Bibliothek (für „Custom – Fix“) +  async function buildRefLibForContext(ctx){ +    const kind = (ctx.resource || 'templates').replace(/s$/,''); // template|section|block +    const id   = ctx.id; +    if (kind === 'template'){ +      const [sections, blocks] = await Promise.all([ +        apiList('sections', { template_id: id }).catch(()=>[]), +        listBlocksForTemplate(id) +      ]); +      return { sections, blocks }; +    } +    if (kind === 'section'){ +      const blocks = await apiList('blocks', { section_id: id }).catch(()=>[]); +      return { sections: [], blocks }; +    } +    return { sections: [], blocks: [] }; // block -> keine Sections/Blocks in Fix +  } +  // Snippets (für „Custom – Flex“) kontextabhängig +  async function buildSnippetsForContext(ctx){ +    const kind = (ctx.resource || 'templates').replace(/s$/,''); +    const id   = ctx.id; +    let rows = []; +    if (kind === 'template')      rows = await listSnippetsForTemplate(id); +    else if (kind === 'section')  rows = await apiList('snippets', { section_id: id }).catch(()=>[]); +    else if (kind === 'block')    rows = await apiList('snippets', { block_id: id }).catch(()=>[]); +    else                          rows = await apiList('snippets').catch(()=>[]); +    return (rows || []).map(r => ({ id: r.id, name: r.name, html: r.content || r.html || '' })); +  } + +  // ---------- Initialen HTML-Inhalt in Editor pushen (mit Token/Race-Schutz) ---------- +  async function pushInitialHtmlToEditor({ mode, html, snippets, ref, token }) { +    if (token !== reqToken) return; // veraltete Anfrage ignorieren + +    const win = iframe?.contentWindow; +    const doc = iframe?.contentDocument; + +    // NEU: HTML wird NUR über postMessage gesendet. Die Bridge im iFrame ist verantwortlich +    // dafür, das HTML in GrapesJS zu setzen, NACHDEM ihre Plugins fertig sind. +    try { +      win?.postMessage({ source:'admin', type:'init', mode, html: html || '', snippets: snippets || [], ref: ref || {} }, '*'); +    } catch {} + +    try { +      // Warten auf Editor ist noch sinnvoll, um das Lade-Badge zu unterdrücken, +      // aber wir manipulieren den Editor NICHT MEHR direkt von hier aus. +      await waitForEditor(6000);  +      if (token !== reqToken) return; +       +      // ... (Gelöschte Logik: ed.setComponents(html) ist nun in der Bridge-Logik) ... +    } catch { +      /* Falls GJS noch nicht bereit ist, arbeiten wir nur via postMessage. */ +    } + +    try { hideReadyBadge(doc); } catch {} +    if (token === reqToken) hideVeil(); +  } + +  // ---------- Öffnen ---------- +  async function open(item, resource) { +    current = { +      resource: String(resource || activeMode() || 'templates').toLowerCase(), +      id: Number(item?.id || 0), +      name: item?.name || '' +    }; +    if (!current.id) return err('Ungültige ID'); + +    // globaler Kontext +    window.__currentItemId    = current.id; +    window.__currentEditorCtx = { id: current.id, mode: current.resource }; + +    // Neuen Token erzeugen & alten Listener entfernen +    reqToken++; +    const myToken = reqToken; +    if (bridgeListener) window.removeEventListener('message', bridgeListener); +    bridgeListener = null; + +    // Overlay zeigen +    showVeil(); + +    // Daten parallel laden (fresh HTML + kontextgefilterte Snippets + Referenzen) +    let fresh = ''; +    let snippets = []; +    let refLib = { sections: [], blocks: [] }; + +    await Promise.all([ +      (async() => { +        try { +          const row = await apiGet(current.resource, current.id); +          // API liefert jetzt top-level html/content; fallback auf item.* +          fresh = row?.html ?? row?.content ?? row?.item?.html ?? row?.item?.content ?? ''; +        } catch {} +      })(), +      (async() => { snippets = await buildSnippetsForContext(current); })(), +      (async() => { refLib   = await buildRefLibForContext(current); })() +    ]); + +    // iFrame-Load -> Bridge-Ready abhören +    iframe.onload = function () { +      if (myToken !== reqToken) return; + +      try { hideReadyBadge(iframe.contentDocument); } catch {} + +      bridgeListener = (ev) => { +        const d = ev?.data || {}; +        if (!d) return; +        // wir erwarten Nachrichten aus der Bridge/Editor +        if (d.source !== 'bridge' && d.source !== 'editor') return; +        if (myToken !== reqToken) return; + +        // NEU: Wenn der Editor meldet, dass er *gespeichert* hat, +        // aktualisieren wir die Liste im Elternfenster +        if (d.type === 'save:success') { +          ok('Gespeichert'); +          try { +            if (typeof window.reloadActiveList === 'function') window.reloadActiveList(); +            else if (typeof window.__reloadList === 'function') window.__reloadList(current.resource); +          } catch {} +          return; +        } +         +        // neue Bridge meldet gjs:ready; ältere evtl. core-ready/bridge:ready +        if (d.type === 'gjs:ready' || d.type === 'core-ready' || d.type === 'bridge:ready' || d.type === 'bridge:booted') { +          pushInitialHtmlToEditor({ +            mode: current.resource, +            html: fresh, +            snippets, +            ref: { +              sections: (refLib.sections || []).map(r => ({ id:r.id, name:r.name, html:r.html || '' })), +              blocks:   (refLib.blocks   || []).map(r => ({ id:r.id, name:r.name, html:r.html || '' })) +            }, +            token: myToken +          }); +        } +      }; +      window.addEventListener('message', bridgeListener); + +      // Fallback, falls kein Ready ankommt +      setTimeout(() => { +        pushInitialHtmlToEditor({ +          mode: current.resource, +          html: fresh, +          snippets, +          ref: { +            sections: (refLib.sections || []).map(r => ({ id:r.id, name:r.name, html:r.html || '' })), +            blocks:   (refLib.blocks   || []).map(r => ({ id:r.id, name:r.name, html:r.html || '' })) +          }, +          token: myToken +        }); +      }, 1200); +    }; + +    // Jetzt den Editor-Core laden (erst NACH about:blank) +    iframe.src = `editor/editor-core.php?mode=${encodeURIComponent(current.resource)}&id=${current.id}&t=${Date.now()}`; + +    dlg?.showModal?.(); +  } + +  // ---------- Speichern (DELEGIERT) ---------- +  // 🚨 KORRIGIERT: Delegiert Speichern an den iFrame, der die JSON-Daten holt! +  async function save() { +    if (!current?.id) return err('Keine aktive ID'); + +    const mode = activeMode(); +    if (mode !== 'snippets') { // Nur Templates/Blocks/Sections delegieren, Snippets behalten die alte Logik (NUR HTML) +      return delegateCommand('save-data'); +    } +     +    // Alte Snippet-Logik beibehalten (falls der Snippet-Editor nicht GrapesJS ist und nur HTML erwartet) +    const liveHtml = await readEditedHtml(); + +    const payload = { id: current.id, content: liveHtml }; + +    const res = await apiUpdate(mode, current.id, payload); +    if (!res?.ok) { err('Speichern fehlgeschlagen'); return; } + +    ok('Gespeichert'); +    try { +      if (typeof window.reloadActiveList === 'function') await window.reloadActiveList(); +      else if (typeof window.__reloadList === 'function') window.__reloadList(mode); +    } catch {} +  } + +  // ... (Der Rest der Funktionen bleibt unverändert) ... +  async function clearEditor() { +    const win = iframe?.contentWindow; +    const ed  = win?.__gjs || (win?.grapesjs && win.grapesjs.editors && win.grapesjs.editors[0]) || null; +    if (ed) { +      ed.setComponents(''); +      ed.setStyle(''); +    } else { +      writeHtmlToFrame(''); +    } +  } + +  async function openPreview() { +    const html = await readEditedHtml(); +    prevFrame.srcdoc = `${html || '(leer)'}`; +    prevDlg?.showModal?.(); +  } +   +  async function openSend() { +    sendSubject.value = 'Testversand'; +    sendTo.value = ''; +    sendDlg?.showModal?.(); +  } +  function closeSend(){ sendDlg?.close?.(); } + +  async function doSend(ev){ +    ev?.preventDefault?.(); +    const to = sendTo.value.trim(); +    if(!to){ toast("Bitte Empfänger angeben", false); return; } +    const win = iframe?.contentWindow; +    const ctx = (win && win.__currentEditorCtx) || {}; +    const id  = (window.__currentItemId || ctx?.id || 0); +    if(!id){ toast("Kein Template geladen", false); return; } +    // Hier wird der gespeicherte HTML-Code verwendet, nicht der Live-HTML, da apiAction +    // keine Live-Daten erwartet. Es geht um template_id. +    const r = await apiAction('templates.test_send', { method:'POST', data:{ template_id: id, to, subject: sendSubject.value || 'Testversand' } }); +    if(r?.ok){ toast("Testversand ausgelöst"); closeSend(); } else { toast("Senden fehlgeschlagen", false); } +  } +  function closePreview(){ prevDlg?.close?.(); } + +  function close() { +    // nächstes Öffnen invalidiert laufende asyncs +    reqToken++; + +    try { iframe.contentWindow?.postMessage({source:'admin',type:'reset'}, '*'); } catch {} +    if (bridgeListener) window.removeEventListener('message', bridgeListener); +    bridgeListener = null; + +    hideVeil(); +    dlg?.close?.(); + +    // iFrame zurück auf blank +    iframe.src = 'about:blank#' + Date.now(); + +    // Kontext leeren +    current = null; +    window.__currentItemId = undefined; +    window.__currentEditorCtx = undefined; +  } + +  // Buttons +  btnSave      && (btnSave.onclick      = save); +  btnClear     && (btnClear.onclick     = clearEditor); +  btnClose     && (btnClose.onclick     = close); +  btnPrevClose && (btnPrevClose.onclick = closePreview); +  btnPreview   && (btnPreview.onclick   = openPreview); +  btnTest      && (btnTest.onclick      = openSend); +  btnCancelSend&& (btnCancelSend.onclick= closeSend); +  sendForm     && (sendForm.onsubmit    = doSend); + +  // Public API +  window.EditorUI = { open, save, close, clear: clearEditor, preview: openPreview }; +} + +// Default-Export + globaler Fallback +export default initEditor; +window.initEditor = initEditor; diff --git a/public/assets/js/ui-list.js b/public/assets/js/ui-list.js new file mode 100644 index 0000000..c5dae63 --- /dev/null +++ b/public/assets/js/ui-list.js @@ -0,0 +1,170 @@ +import { apiList, apiGet, apiDelete, apiUpdate, toast } from './api.js'; + +function esc(s=''){ + return String(s) + .replace(/&/g,'&') + .replace(//g,'>') + .replace(/"/g,'"') + .replace(/'/g,'''); +} + +async function openSnippetEditor(id){ + const dlg = document.getElementById('editSnippetDialog'); + const form = document.getElementById('editSnippetForm'); + const inpName = document.getElementById('edit_snip_name'); + const taContent = document.getElementById('edit_snip_content'); + const btnCancel = document.getElementById('editSnippetCancel'); + + // Daten laden + let row = {}; + try { row = await apiGet('snippets', id) || {}; } catch(e){} + + if (inpName) inpName.value = row.name || ''; + if (taContent) taContent.value = row.content || ''; + + function cleanup(){ + form && form.removeEventListener('submit', onSubmit); + btnCancel && (btnCancel.onclick = null); + } + + async function onSubmit(ev){ + ev.preventDefault(); + try{ + const res = await apiUpdate('snippets', id, { + name: inpName ? inpName.value : '', + content: taContent ? taContent.value : '' + }); + toast(res && res.ok ? 'Snippet gespeichert' : 'Speichern fehlgeschlagen', !!(res && res.ok)); + dlg && dlg.close(); + cleanup(); + // Liste neu laden + loadList('snippets'); + }catch(e){ + toast('Speichern fehlgeschlagen', false); + } + } + + if (form) form.addEventListener('submit', onSubmit, { once:false }); + if (btnCancel) btnCancel.onclick = () => { dlg && dlg.close(); cleanup(); }; + + dlg && dlg.showModal(); +} + +export async function loadList(resource){ + const el=document.getElementById(`view-${resource}`); if(!el) return; + + el.innerHTML=`
+
${resource.charAt(0).toUpperCase()+resource.slice(1)}
+
Lade …
`; + + const data=await apiList(resource); + const list=el.querySelector(`#list-${resource}`); + + if(!Array.isArray(data)||data.length===0){ + list.innerHTML=`
Keine Einträge
`; + return; + } + + function parentBadge(r,it){ + if(r==='sections'&&it.template_id) return ` Template #${it.template_id}${it.template_name ? ' · '+esc(it.template_name) : ''}`; + if(r==='blocks'&&it.section_id) return ` Section #${it.section_id}${it.section_name ? ' · '+esc(it.section_name) : ''}`; + if(r==='snippets'&&it.block_id) return ` Block #${it.block_id}${it.block_name ? ' · '+esc(it.block_name) : ''}`; + return ' frei'; + } + + list.innerHTML=data.map(item=>{ + const name = esc(item.name||''); + const openBtn = (['templates','sections','blocks'].includes(resource)) + ? `` : ''; + + const editBtn = (resource==='snippets') + ? `` : ''; + + const prevBtn = ``; + const delBtn = ``; + const debugBtn= `GET`; + + return `
+
${name || '(ohne Name)'}
+
#${item.id}
+
${parentBadge(resource,item)}
+
${[openBtn, editBtn, prevBtn, delBtn, debugBtn].filter(Boolean).join('')}
+
`; + }).join(''); + + // --- Editor öffnen (ANPASSUNG) ----------------------------------------- + list.querySelectorAll('[data-open]').forEach(b=>b.addEventListener('click', async ()=>{ + const [res,id]=b.dataset.open.split(':'); + + // Detail laden, um Name + aktuellen HTML/Content zu haben + const obj = await apiGet(res,id); + const name = obj?.name || ''; + const html = obj ? (obj.html ?? obj.content ?? '') : ''; + + // Globale Kontexte (werden von Editor/anderen Modulen genutzt) + window.__currentItemId = Number(id); + window.__currentEditorCtx = { id:Number(id), mode:res }; + + // Bevorzugt EditorUI.open nutzen; Fallback: __openEditor (Bestand) + if (window.EditorUI && typeof window.EditorUI.open === 'function') { + window.EditorUI.open({ id:Number(id), name, html }, res); + } else if (window.__openEditor) { + window.__openEditor({ resource:res, id:Number(id), name, html }); + } else { + console.warn('Kein Editor-Entry-Point gefunden (EditorUI.open / __openEditor).'); + toast('Editor ist nicht initialisiert.', false); + } + })); + // ----------------------------------------------------------------------- + + // edit snippet + list.querySelectorAll('[data-edit]').forEach(b=>b.addEventListener('click', async ()=>{ + const [, id] = b.dataset.edit.split(':'); + await openSnippetEditor(id); + })); + + // preview + const prevDlg=document.getElementById('previewDialog'), prevFrame=document.getElementById('previewFrame'); + list.querySelectorAll('[data-preview]').forEach(b=>b.addEventListener('click', async ()=>{ + const [res,id]=b.dataset.preview.split(':'); + const obj=await apiGet(res,id); + const html=(obj?.html||obj?.content||'(leer)'; + prevDlg.showModal(); + })); + + // delete + const delDlg=document.getElementById('deleteDialog'), + delText=document.getElementById('deleteText'), + delForm=document.getElementById('deleteForm'), + delCancel=document.getElementById('deleteCancel'); + + let pending=null; + delCancel && (delCancel.onclick=()=>{pending=null;delDlg.close();}); + + list.querySelectorAll('[data-del]').forEach(b=>b.addEventListener('click',()=>{ + const [res,id]=b.dataset.del.split(':'); const nm=b.dataset.name||''; + pending={res,id,nm}; + delText && (delText.innerHTML=`Soll ${nm || '(ohne Name)'} #${id} aus ${res} wirklich gelöscht werden?
Achtung: Kinder-Elemente werden nicht automatisch mit gelöscht.`); + delDlg.showModal(); + })); + + delForm && (delForm.onsubmit=async(e)=>{ + e.preventDefault(); + if(!pending) return delDlg.close(); + const r=await apiDelete(pending.res,pending.id); + delDlg.close(); + toast(r&&r.ok?'Gelöscht':'Löschen fehlgeschlagen', !!(r&&r.ok), {duration:3000}); + loadList(resource); + }); +} + +export function initLists(){ + loadList('templates'); + // Public reload helper (wird vom Snippet-Editor genutzt) + window.__reloadList = loadList; + // Backwards compat (falls woanders genutzt) + window.loadList = loadList; +} + diff --git a/public/assets/js/ui-tabs.js b/public/assets/js/ui-tabs.js new file mode 100644 index 0000000..cb5dd46 --- /dev/null +++ b/public/assets/js/ui-tabs.js @@ -0,0 +1,11 @@ +export function initTabs(){ + const tabs=document.querySelectorAll('nav [data-tab]'); if(!tabs.length) return; + const views={ templates:document.getElementById('view-templates'), sections:document.getElementById('view-sections'), blocks:document.getElementById('view-blocks'), snippets:document.getElementById('view-snippets') }; + tabs.forEach(btn=>btn.addEventListener('click',()=>{ + tabs.forEach(b=>b.classList.remove('bg-sky-50','text-sky-700')); + btn.classList.add('bg-sky-50','text-sky-700'); + document.querySelectorAll('.view').forEach(v=>v.classList.add('hidden')); + const tab=btn.dataset.tab; views[tab]?.classList.remove('hidden'); + window.loadList && window.loadList(tab); + })); +} \ No newline at end of file diff --git a/public/assets/js/ui-tools.js b/public/assets/js/ui-tools.js new file mode 100644 index 0000000..d7e98cc --- /dev/null +++ b/public/assets/js/ui-tools.js @@ -0,0 +1,158 @@ +// assets/js/ui-tools.js +// Öffnet API-Health (JSON), DB-Doctor (Iframe) & beliebige JSON-GETs im Popup, +// ohne die Seite zu verlassen. Links bleiben als Fallback nutzbar. + +(function () { + const dlg = document.getElementById('toolsDialog'); + if (!dlg) return; + + const title = document.getElementById('toolsTitle'); + const btnX = document.getElementById('toolsClose'); + const btnCopy = document.getElementById('toolsCopy'); + const btnDl = document.getElementById('toolsDownload'); + + const jsonWrap = document.getElementById('toolsJsonWrap'); + const jsonPre = document.getElementById('toolsJsonPre'); + const frame = document.getElementById('toolsFrame'); + + function showJson(obj, ttl) { + title.textContent = ttl || 'Antwort (JSON)'; + const txt = (typeof obj === 'string') ? obj : JSON.stringify(obj, null, 2); + jsonPre.textContent = txt; + jsonWrap.classList.remove('hidden'); + frame.classList.add('hidden'); + btnCopy.classList.remove('hidden'); + btnDl.classList.remove('hidden'); + try { dlg.showModal(); } catch {} + } + + function showFrame(url, ttl) { + title.textContent = ttl || 'Werkzeug'; + frame.src = url + (url.includes('?') ? '&' : '?') + 't=' + Date.now(); + frame.classList.remove('hidden'); + jsonWrap.classList.add('hidden'); + btnCopy.classList.add('hidden'); + btnDl.classList.add('hidden'); + try { dlg.showModal(); } catch {} + } + + btnX?.addEventListener('click', () => { + try { dlg.close(); } catch {} + frame.src = 'about:blank'; + }); + + btnCopy?.addEventListener('click', async () => { + const txt = jsonPre.textContent || ''; + try { + await navigator.clipboard.writeText(txt); + // optional: kleines Feedback + (window.Toast?.show || window.toast || (()=>{}))('In Zwischenablage kopiert'); + } catch {} + }); + + btnDl?.addEventListener('click', () => { + const blob = new Blob([jsonPre.textContent || ''], { type:'application/json;charset=utf-8' }); + const a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + const stamp = new Date().toISOString().replace(/[:.]/g,'-'); + a.download = `response-${stamp}.json`; + document.body.appendChild(a); + a.click(); + setTimeout(()=>{ URL.revokeObjectURL(a.href); a.remove(); }, 0); + }); + + // ------------------------------------------------------------ + // 1) Offizieller Weg: Links mit data-popup="json" | "frame" + // ------------------------------------------------------------ + document.addEventListener('click', async (ev) => { + const a = ev.target.closest('a[data-popup]'); + if (!a) return; + + const mode = (a.getAttribute('data-popup') || '').toLowerCase(); + const href = a.getAttribute('href') || '#'; + const ttl = a.getAttribute('data-title') || a.textContent.trim() || 'Werkzeug'; + + if (!/^json|frame$/.test(mode)) return; + // Cmd/Strg-Klick & Mittelklick respektieren (neuer Tab) + if (ev.metaKey || ev.ctrlKey || ev.button === 1) return; + + ev.preventDefault(); + + if (mode === 'frame') { + showFrame(href, ttl); + return; + } + + // mode === 'json' + try { + const r = await fetch(href, { credentials: 'include' }); + const txt = await r.text(); + let data = null; + try { data = JSON.parse(txt); } catch { data = txt; } + showJson(data, ttl); + } catch (e) { + showJson({ ok:false, error: String(e) }, ttl); + } + }); + + // ------------------------------------------------------------ + // 2) Fallback: *alle* API-GET-Links (action=get) ohne data-popup + // -> automatisch im JSON-Popup öffnen + // ------------------------------------------------------------ + document.addEventListener('click', async (ev) => { + const a = ev.target.closest('a'); + if (!a) return; + // bereits oben behandelt + if (a.hasAttribute('data-popup')) return; + + const href = a.getAttribute('href') || ''; + // nur api.php-GET-Routen mit action=get abfangen + if (!/api\.php/i.test(href) || !/[?&]action=get(&|$)/i.test(href)) return; + + // Cmd/Strg/Mittelklick respektieren + if (ev.metaKey || ev.ctrlKey || ev.button === 1) return; + + ev.preventDefault(); + + const makeTitle = () => { + try { + const u = new URL(href, location.href); + const res = u.searchParams.get('resource') || 'resource'; + const id = u.searchParams.get('id') || ''; + // Optional: Name aus data-title wenn vorhanden + const custom = a.getAttribute('data-title'); + return custom || `GET ${res}${id ? ` #${id}` : ''}`; + } catch { return 'GET'; } + }; + + const title = makeTitle(); + + // Popup öffnen (wie oben) + try { + const r = await fetch(href, { credentials: 'include' }); + const txt = await r.text(); + let data = null; + try { data = JSON.parse(txt); } catch { data = txt; } + showJson(data, title); + } catch (e) { + showJson({ ok:false, error: String(e) }, title); + } + }, true); + + // Utility: Öffnen aus Code + window.AdminTools = { + openJson(url, title) { + fetch(url, { credentials: 'include' }) + .then(r => r.text()) + .then(txt => { + try { showJson(JSON.parse(txt), title); } + catch { showJson(txt, title); } + }) + .catch(err => showJson({ ok:false, error:String(err) }, title)); + }, + openFrame(url, title) { + showFrame(url, title); + } + }; +})(); + diff --git a/public/editor/bridge-core (Kopie).js b/public/editor/bridge-core (Kopie).js new file mode 100644 index 0000000..7ef4623 --- /dev/null +++ b/public/editor/bridge-core (Kopie).js @@ -0,0 +1,496 @@ +/* /editor/bridge-core.js — Loader + Orchestrator (FINAL & LOG-KONTROLLIERT) */ +(function () { + + // --- Initialisierung BridgeParts (B) und Plugin-Registry --- + if (!window.BridgeParts) window.BridgeParts = {}; + const B = window.BridgeParts; + + // ---------------------------------------------------------------------- + // 🎯 LOKALE LOG-KONFIGURATION & WRAPPER + // ---------------------------------------------------------------------- + const PluginName = 'bridge-core'; + + // Setzen Sie dies auf 'false', um alle Logs NUR für dieses Plugin zu deaktivieren. + if (B.LOG_CONFIG) { + B.LOG_CONFIG.PLUGINS[PluginName] = false; // bridge-core spezifisch deaktivieren (optional) + } + + /** + * NEUER LOKALER WRAPPER, der die zentrale B.log Funktion verwendet. + * Der unformatierte Fallback WURDE ENTFERNT, da er das console.log erzeugt hat. + * Die ersten kritischen Logs WURDEN EBENFALLS ENTFERNT, da sie vor B.log lagen. + */ + const log = (type, message, color = '#1E90FF', logType = 'info', force = false) => { + // Loggt NUR, wenn B.log verfügbar ist (aus general-functions.js). + if (typeof B.log === 'function') { + B.log(PluginName, `[${type}] ${message}`, color, logType, force); + } + // Ansonsten wird NICHTS geloggt, bis general-functions.js geladen ist. + }; + // ---------------------------------------------------------------------- + + // 🛑 GLOBALER LOG ZUR BESTÄTIGUNG DER SKRIPT-AUSFÜHRUNG + // Dieser erste Log-Aufruf wird nun still ignoriert, da B.log noch fehlt. + // Er wird durch den SUCCESS-Log der general-functions.js ersetzt. + // log('START', `SKRIPT-AUSFÜHRUNG GESTARTET.`, '#DC143C', 'info', true); // DEAKTIVIERT/IGNORIERT DURCH FEHLENDEN B.log + + // ---------------------------------------------------------------------- + // 🛑 KONFIGURATION: NEWSLETTER-PRESET-TOGGLE + // ---------------------------------------------------------------------- + const LOAD_NEWSLETTER_PRESET = false; // <<< KRITISCHER FIX: Auf FALSE gesetzt, um den "defaults" Konflikt zu beheben! + // ---------------------------------------------------------------------- + + if (window.__bridgeCoreInitialized) { + log('INIT ABORT', 'Bridge Core wurde bereits initialisiert.', 'orange'); + return; + } + window.__bridgeCoreInitialized = true; + + // --- Initialisierung BridgeParts (B) und Plugin-Registry --- + B.BASE_PATH_BRIDGE = '../assets/js/bridge/'; + B.BASE_PATH_CONFIG = B.BASE_PATH_BRIDGE; + + B.GrapesJSPlugins = []; + + B.registerGrapesJSPlugin = (name, pluginFn) => { + B.GrapesJSPlugins.push({ name, pluginFn }); + log('PLUGIN REGISTER', `Plugin zur Registry hinzugefügt: ${name}`, 'yellow'); + }; + + // --- DEBUG-HELPER UND LOADER-HELPER --- + const badgeSay = (text, type = 'info') => { + const b=document.getElementById('badge'); + if (!b) return; + b.textContent = text; + switch(type) { + case 'ok': b.style.background = '#dcfce7'; b.style.color = '#15803d'; b.style.borderColor = '#bbf7d0'; break; + case 'error': b.style.background = '#fee2e2'; b.style.color = '#7f1d1d'; b.style.borderColor = '#fecaca'; break; + default: b.style.background = '#eef2ff'; b.style.color = '#1e3a8a'; b.style.borderColor = '#c7d2fe'; + } + }; + + function loadScript(url, done) { + const filename = url.split('/').pop(); + var s = document.createElement('script'); + s.src = url + (url.indexOf('?') === -1 ? '?v=' : '&v=') + Date.now(); + s.async = false; + + s.onload = function(){ + log('LOAD SUCCESS', `Skript geladen: ${filename}`, 'green'); + try { + done && done(); + } catch(e){ + if (e.message.includes('setting getter-only property "defaults"')) { + log('RUNTIME WARNING', `IGNORIERE Block-Konflikt in ${filename}: ${e.message}`, 'orange', 'warn'); + } else { + // 🛑 KORREKTUR: force: true explizit auf false setzen (oder weglassen) + log('RUNTIME ERROR', `Fehler in Callback nach ${filename}: ${e.message}`, 'red', 'error', false); + } + } + }; + + s.onerror = function(){ + // 🛑 KORREKTUR: force: true explizit auf false setzen (oder weglassen) + log('LOAD FAILED', `Skript FEHLT oder Pfad falsch: ${filename}`, 'red', 'error', false); + badgeSay(`Ladefehler: ${filename}`, 'error'); + try { done && done(); } catch(e){} + }; + document.head.appendChild(s); + } + + /** + * HILFSFUNKTION: Wandelt den Dateinamen (z.B. blocks-standard.js) in den globalen + * Objektnamen (z.B. BridgeBlocksStandard) um. + */ + function getPluginObjectName(fileName) { + // 1. Entferne Dateiendung (.js) + let name = fileName.replace('.js', ''); // 'blocks-standard' + + // 2. Teile in Bestandteile zerlegen und den ersten Buchstaben groß schreiben + const parts = name.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)); // ['Blocks', 'Standard'] + + // 3. Mit 'Bridge' prefixen und zusammenfügen + return 'Bridge' + parts.join(''); // 'BridgeBlocksStandard' + } + + // 🛑 NEUE FUNKTION: Erstellt alle in der Konfiguration definierten Kategorien. + function ensureConfiguredCategories(editor) { + const bm = editor.BlockManager; + const config = window.BridgeParts?.CATEGORY_CONFIG || {}; + + Object.keys(config) + .sort((a, b) => (config[a].ord || 999) - (config[b].ord || 999)) + .forEach(catId => { + const catConf = config[catId]; + // Category wird nur erstellt, wenn sie noch nicht existiert + if (!bm.getCategories().get(catId)) { + bm.getCategories().add({ + id: catId, + label: catConf.label, + open: catConf.open !== false, + order: catConf.ord || 999 + }); + log('CAT INIT', `Kategorie '${catId}' explizit erstellt.`, 'green'); + } + }); + } + + function loadBridgeParts(cb){ + const base = B.BASE_PATH_BRIDGE; + + // 🛑 LOKALES LOGGING ENTFERNT, DA ES VOR B.log LIEGT. + // log('LOAD START', 'Starte Laden der modularen Bridge-Teile (Geordnet).'); + + const coreFiles = [ + // base + 'category-config.js', + // base + 'general-functions.js', + base + 'library-parts.js', + base + 'categorization-master.js', + base + 'categorization-cleanup.js', + ]; + + const initialLoadList = [...coreFiles]; + + function recursiveLoader(list, index = 0) { + if (index >= list.length) { + log('LOAD END', 'Initial-Bridge-Skripte geladen.', 'green'); + + const config = window.BridgeParts?.CATEGORY_CONFIG || {}; + let allBlockFiles = []; + + // Dynamisches Sammeln der Block-Dateien aus der Config + Object.keys(config) + .sort((a, b) => (config[a].ord || 999) - (config[b].ord || 999)) + .forEach(key => { + // Sammelt alle Dateien, egal ob sync oder async + if (Array.isArray(config[key].files)) { + allBlockFiles.push(...config[key].files.map(file => base + file)); + } + }); + + // Duplikate entfernen (falls eine Datei in mehreren Kategorien gelistet ist) + allBlockFiles = Array.from(new Set(allBlockFiles)); + + function loadBlockFiles(blockIndex = 0) { + if (blockIndex >= allBlockFiles.length) { + log('LOAD END', 'Alle Blöcke geladen.', 'green'); + return cb && cb(B); + } + log('LOADING BLOCKS', `Lade Block-Skript [${blockIndex + 1}/${allBlockFiles.length}]: ${allBlockFiles[blockIndex].split('/').pop()}`); + loadScript(allBlockFiles[blockIndex], function(){ + loadBlockFiles(blockIndex + 1); + }); + } + loadBlockFiles(); + return; + } + + // 🛑 LOKALES LOGGING ENTFERNT, DA ES VOR B.log LIEGT. + log('LOADING CORE', `Lade Skript [${index + 1}/${initialLoadList.length}]: ${list[index].split('/').pop()}`); // Loggt ab dem 3. Skript, da general-functions.js an 2. Stelle geladen wird. + + loadScript(list[index], function(){ + recursiveLoader(list, index + 1); + }); + } + + recursiveLoader(initialLoadList); + } + + try { parent.postMessage({ source:'bridge', type:'boot' }, '*'); } catch {} + var MODE = (window.__editorMode || 'templates').toLowerCase(); + + const replaceReferenceLibrary = (editor, ref, mode) => { + (window.BridgeParts?.addReferenceLibrary || (()=>{}))(editor, ref, mode); + }; + const upsertCustomForBothCats = (editor, payload) => { + (window.BridgeParts?.upsertCustomForBothCats || (()=>{}))(editor, payload); + }; + + // --- Init & Events (Plugin integriert) --------------------------------------------- + loadBridgeParts(function(B){ + log('INIT START', 'Alle Bridge-Teile geladen, starte GrapesJS-Initialisierung.', 'orange'); + + if (typeof grapesjs === 'undefined' || !grapesjs.init) { + // 🛑 KORREKTUR: force: true explizit auf false setzen (oder weglassen) + log('CRITICAL ERROR', 'Das globale Objekt grapesjs ist nicht verfügbar! Laden von grapes.min.js ist fehlgeschlagen.', 'red', 'error', false); + badgeSay('Fehler: GrapesJS nicht geladen!', 'error'); + return; + } + + // 🛑 KRITISCHER FIX TEIL 1: Registriere alle gesammelten Bridge-Plugins global. + if (typeof grapesjs.plugins.add === 'function') { + B.GrapesJSPlugins.forEach(p => { + grapesjs.plugins.add(p.name, p.pluginFn); + log('PLUGIN ACTIVATION', `GrapesJS Plugin global bereitgestellt: ${p.name}`, 'lime'); + }); + } else { + // 🛑 KORREKTUR: force: true explizit auf false setzen (oder weglassen) + log('PLUGIN ERROR', `GrapesJS Plugin-API (grapesjs.plugins.add) fehlt. Plugins können nicht registriert werden.`, 'red', 'error', false); + } + + // 🛑 KRITISCHER FIX: Safety Plugin MUSS die fehlenden Views Panels hinzufügen. + function safetyPlugin(editor){ + const pn = editor.Panels, orig = pn.getButton.bind(pn); + pn.getButton = (pid, id) => orig(pid, id) || { set(){}, get(){ return null; } }; + + // Fügen Sie das Panel 'views' hinzu, wenn es fehlt + if(!pn.getPanel('views')) { + pn.addPanel({ id: 'views', el: '.gjs-pn-views' }); + log('PANEL FIX', "Das 'views' Panel wurde nachträglich hinzugefügt.", 'yellow', 'warn'); + } + + // Stellen Sie sicher, dass der Block Manager in den Views-Container rendert + editor.Config.blockManager = editor.Config.blockManager || {}; + editor.Config.blockManager.appendTo = editor.Config.blockManager.appendTo || '.gjs-blocks'; + + // Der fehlerhafte Timeout-Block wurde entfernt. + } + + let pluginsList = [ + safetyPlugin, + // 🛑 KRITISCHE ERGÄNZUNG: Aktiviert das registrierte API-Plugin + 'bridge-blocks-api', + 'bridge-categorization-master', + 'bridge-categorization-cleanup', + ]; + + if (LOAD_NEWSLETTER_PRESET) { + pluginsList.push('gjs-preset-newsletter'); + } + + var ed = grapesjs.init({ + container: '#gjs', + height: '100vh', + storageManager: false, + plugins: pluginsList, + pluginsOpts: {}, + // 🛑 KRITISCHE ERGÄNZUNG: Verhindert das automatische Ausblenden leerer Kategorien + blockManager: { + hideEmpty: false + } + }); + + window.__gjs = ed; + + // 🛑 KRITISCHE KORREKTUR 1: Explizite Erstellung aller konfigurierten Kategorien + ensureConfiguredCategories(ed); + + // 🛑 KRITISCHE KORREKTUR 2: Sofortige Label-Korrektur + // Überschreibt den potenziell falschen, durch GrapesJS gesetzten Label-Namen + Object.keys(B.CATEGORY_CONFIG || {}).forEach(catId => { + const expectedLabel = B.CATEGORY_CONFIG[catId].label; + const categoryModel = ed.BlockManager.getCategories().get(catId); + + if (categoryModel && categoryModel.get('label') !== expectedLabel) { + // Setzen ohne das 'change:label' Event auszulösen (optional, aber sauber) + categoryModel.set('label', expectedLabel, { silent: true }); + log('LABEL FIX', `Kategorie '${catId}' Label auf korrigiert: '${expectedLabel}'`, 'yellow', 'warn'); + } + }); + // --------------------------------------------------- + + B.ensureViews && B.ensureViews(ed); + + log('BLOCK REGISTER', 'Registriere Bridge Blöcke, um Preset-Defaults zu überschreiben.', 'purple'); + + // 🛑 DYNAMISCHE AKTIVIERUNG DER SYNCHRONEN BLÖCKE (Ersetzt die fixen Aufrufe) + if (B.CATEGORY_CONFIG && ed) { + log('DYNAMIC ACTIVATION', 'Starte Aktivierung synchroner Block-Plugins (via Config).', 'purple'); + + // Iteriere über die konfigurierten Kategorien + Object.keys(B.CATEGORY_CONFIG).forEach(catId => { + const config = B.CATEGORY_CONFIG[catId]; + + // Verarbeite nur SYNCHRONE Plugins, die Dateien angeben + if (config.registration_mode === 'sync' && Array.isArray(config.files)) { + + config.files.forEach(fileName => { + + // Korrigierte Funktion liefert jetzt z.B. 'BridgeBlocksCustom' + const objectName = getPluginObjectName(fileName); + const plugin = window[objectName]; + + // Prüfen, ob das Skript geladen wurde und die Register-Funktion vorhanden ist + if (plugin && typeof plugin.register === 'function') { + log('DYNAMIC ACTIVATION', `Registriere sync Plugin: ${objectName} (${fileName})`, 'lime'); + try { + plugin.register(ed); + } catch(e) { + log('DYNAMIC ACTIVATION ERROR', `Fehler beim Registrieren von ${objectName}: ${e.message}`, 'red', 'error'); + } + } else { + log('DYNAMIC ACTIVATION WARNING', `Sync Plugin Objekt oder .register() Methode nicht gefunden: ${objectName} (${fileName})`, 'orange', 'warn'); + } + }); + } + }); + } + // --------------------------------------------------- + + log('INIT API', 'API-Elemente werden nun durch das Plugin bridge-blocks-api geladen.', 'orange'); + + // ---------------------------------------------------------------------- + // DEBUGGING: ZÄHLE REKURSIVE EVENTS + // ---------------------------------------------------------------------- + let eventCounts = {}; + let isParsing = false; + const MAX_CALLS = 1000; + + const debugEvents = [ + 'component:add', + 'component:update', + 'change:components', + 'block:add', + 'change:attributes', + 'comp:update:status' + ]; + + const debugListener = (event, model) => { + if (!isParsing) return; + + if (!eventCounts[event]) { + eventCounts[event] = 0; + } + eventCounts[event]++; + + if (eventCounts[event] === MAX_CALLS + 1) { + // Diese kritischen Debug-Meldungen bleiben DIREKT im console-Objekt, + // da sie immer sichtbar sein müssen, um Endlosschleifen zu erkennen. + console.error(`%c[DEBUG RECURSION ALARM] 🚨 Event '${event}' hat den Grenzwert von ${MAX_CALLS} überschritten!`, 'color:red; font-size: 1.1em; font-weight: bold;'); + } + + if (eventCounts[event] > MAX_CALLS && eventCounts[event] < (MAX_CALLS + 10)) { + const type = (model && typeof model.get === 'function') ? model.get('type') : 'N/A'; + const parentType = (model && typeof model.parent === 'function' && model.parent()) ? model.parent().get('type') : 'N/A'; + // Diese bleiben console.log aus demselben Grund + console.log(`%c [RECURSION SOURCE] Event: ${event}, Type: ${type}, Parent: ${parentType}`, 'color: #8b0000;'); + } + }; + + ed.on('load', function() { + debugEvents.forEach(event => ed.on(event, (model) => debugListener(event, model))); + + setTimeout(() => { + (B.waitForBlocks ? B.waitForBlocks(ed) : Promise.resolve()).then(function(){ + try { + log('CORE WARN', 'Führe finalen, verzögerten Cleanup-Lauf durch (2000ms).', 'orange', 'warn'); + + B.normalizeCategories && B.normalizeCategories(ed); + B.renderBlocks && B.renderBlocks(ed); + + } catch(e) { + log('CORE ERROR', `Finaler Cleanup-Fehler: ${e.message}`, 'red', 'error'); + } + }); + }, 2000); + + }, { once: true }); + + + // ---------------------------------------------------------------------- + // MESSAGE HANDLER + // ---------------------------------------------------------------------- + window.addEventListener('message', async function(ev){ + var data = ev.data || {}; + if (data.source !== 'admin') return; + + if (data.type === 'init'){ + B.ensureViews && B.ensureViews(ed); + + var html = (data.html || '').trim(); + if (!html) html = '

Neues Dokument

Inhalt ...

'; + + const applySnips = function(arr){ + const list = (Array.isArray(arr)?arr:[]).map(s => ({ id:s.id, name:s.name, html: s.html || s.content || '' })); + + B.replaceSnippetBlocks && B.replaceSnippetBlocks(ed, list); + + upsertCustomForBothCats(ed, { + ref: (data.ref && (Array.isArray(data.ref.sections) || Array.isArray(data.ref.blocks))) ? { + sections: data.ref.sections || [], + blocks: data.ref.blocks || [] + } : { sections: [], blocks: [] }, + snippets: list + }); + + setTimeout(() => { + try { + // Erneutes Normalisieren nach Laden der Snippets (falls nötig) + B.normalizeCategories && B.normalizeCategories(ed); + B.ensureViews && B.ensureViews(ed); + B.renderBlocks && B.renderBlocks(ed); + log('CORE WARN', 'normalize/render nach applySnips ausgeführt (1ms).', 'orange', 'warn'); + } catch(e) { + log('CORE ERROR', `applySnips-Cleanup-Fehler: ${e.message}`, 'red', 'error'); + } + }, 1); + + }; + + if (Array.isArray(data.snippets) && data.snippets.length) applySnips(data.snippets); + else (B.fetchSnippets ? B.fetchSnippets() : Promise.resolve([])).then(applySnips); + + if (data.ref && (Array.isArray(data.ref.sections) || Array.isArray(data.ref.blocks))) { + replaceReferenceLibrary(ed, { + sections: data.ref.sections || [], + blocks: data.ref.blocks || [] + }, MODE); + } + + // Finaler Aufruf nachrichtengesteuert (konsolidiert) + setTimeout(() => { + (B.waitForBlocks ? B.waitForBlocks(ed) : Promise.resolve()).then(function(){ + try { + log('CORE WARN', 'Führe nachrichtengesteuerten Final-Cleanup-Lauf durch (100ms).', 'orange', 'warn'); + + if (!ed.__contentLoaded) { + window.__GJS_IS_PARSING = true; + isParsing = true; + eventCounts = {}; + + try { + ed.setComponents(html); + } catch (e) { + log('SET COMPONENTS FAILED', `setComponents Fehler: ${e.message}. Aufgerufene Event-Zähler: ${JSON.stringify(eventCounts)}`, 'red', 'error'); + // console.table(eventCounts); bleibt eine direkte Debug-Ausgabe + throw e; + } finally { + window.__GJS_IS_PARSING = false; + isParsing = false; + log('CONTENT', 'HTML-Inhalt in den Editor geladen (FINAL FIX).', 'orange'); + + B.normalizeCategories && B.normalizeCategories(ed); + B.renderBlocks && B.renderBlocks(ed); + } + + ed.__contentLoaded = true; + + } else { + B.normalizeCategories && B.normalizeCategories(ed); + B.renderBlocks && B.renderBlocks(ed); + } + + } catch(e) { + log('CORE ERROR', `Nachrichten-Final-Cleanup-Fehler: ${e.message}. Event-Zähler (im Log-Objekt): ${JSON.stringify(eventCounts)}`, 'red', 'error'); + } + }); + }, 100); + + + try { var b=ed.Panels.getButton('views','open-blocks'); b && b.set('active',true); } catch {} + badgeSay('Inhalt geladen','ok'); + setTimeout(function(){ badgeSay('bereit'); }, 1200); + } + }, false); + + try { B.send && B.send('core-ready', { mode: MODE }); } catch {} + try { var bd=document.getElementById('badge'); if (bd) bd.remove(); } catch {} + }); + + window.onerror = function(message, source, lineno, colno, error) { + // Diese kritische Funktion MUSS console.error verwenden. + console.error(`%c[${PluginName} - GLOBAL ERROR] Uncaught JS Error: ${message} (Quelle: ${source}:${lineno})`, 'color:red; font-weight:bold;'); + return false; + }; + +})(); diff --git a/public/editor/bridge-core.js b/public/editor/bridge-core.js new file mode 100644 index 0000000..bc98490 --- /dev/null +++ b/public/editor/bridge-core.js @@ -0,0 +1,624 @@ +/* /editor/bridge-core.js — Loader + Orchestrator (FINAL & LOG-KONTROLLIERT) */ +(function () { +     +    // --- Initialisierung BridgeParts (B) und Plugin-Registry --- +    if (!window.BridgeParts) window.BridgeParts = {}; +    const B = window.BridgeParts; +     +    // ---------------------------------------------------------------------- +    // 🎯 LOKALE LOG-KONFIGURATION & WRAPPER +    // ---------------------------------------------------------------------- +    const PluginName = 'bridge-core'; +     +    // Setzen Sie dies auf 'false', um alle Logs NUR für dieses Plugin zu deaktivieren. +    if (B.LOG_CONFIG) { +    B.LOG_CONFIG.PLUGINS[PluginName] = true; // bridge-core spezifisch deaktivieren (optional) +    } +     +    /** +     * NEUER LOKALER WRAPPER, der die zentrale B.log Funktion verwendet. +     */ +    const log = (type, message, color = '#1E90FF', logType = 'info', force = false) => { +        // Loggt NUR, wenn B.log verfügbar ist (aus general-functions.js). +        if (typeof B.log === 'function') { +            B.log(PluginName, `[${type}] ${message}`, color, logType, force); +        } +        // Ansonsten wird NICHTS geloggt, bis general-functions.js geladen ist. +    }; +    // ---------------------------------------------------------------------- + +    // 🛑 GLOBALER LOG ZUR BESTÄTIGUNG DER SKRIPT-AUSFÜHRUNG +    // log('START', `SKRIPT-AUSFÜHRUNG GESTARTET.`, '#DC143C', 'info', true); // DEAKTIVIERT/IGNORIERT DURCH FEHLENDEN B.log + +    // ---------------------------------------------------------------------- +    // 🛑 KONFIGURATION: NEWSLETTER-PRESET-TOGGLE +    // ---------------------------------------------------------------------- +    const LOAD_NEWSLETTER_PRESET = false; // <<< KRITISCHER FIX: Auf FALSE gesetzt, um den "defaults" Konflikt zu beheben! +    // ---------------------------------------------------------------------- +     +    if (window.__bridgeCoreInitialized) { +        log('INIT ABORT', 'Bridge Core wurde bereits initialisiert.', 'orange'); +        return;  +    } +    window.__bridgeCoreInitialized = true; +     +    // --- Initialisierung BridgeParts (B) und Plugin-Registry --- +    B.BASE_PATH_BRIDGE = '../assets/js/bridge/'; +    B.BASE_PATH_CONFIG = B.BASE_PATH_BRIDGE;  +    // NEU: Standard-API-Endpunkt für Fallbacks, falls category-config.js ihn nicht setzt. +    // **KORREKTUR**: Auf '/api/editor' FIX eingestellt. +    B.API_BASE = '/api/editor'; // <<< FIX AUF /api/editor +    B.STORAGE_URL_BASE = '/api/editor'; // <<< FIX: Erzwingt, dass auch der Storage Manager diesen Pfad verwendet +     +    B.GrapesJSPlugins = [];  +     +    B.registerGrapesJSPlugin = (name, pluginFn) => { +        B.GrapesJSPlugins.push({ name, pluginFn }); +        log('PLUGIN REGISTER', `Plugin zur Registry hinzugefügt: ${name}`, 'yellow'); +    }; + +    // --- DEBUG-HELPER UND LOADER-HELPER --- +    const badgeSay = (text, type = 'info') => { +        const b=document.getElementById('badge'); +        if (!b) return; +        b.textContent = text; +        switch(type) { +            case 'ok': b.style.background = '#dcfce7'; b.style.color = '#15803d'; b.style.borderColor = '#bbf7d0'; break; +            case 'error': b.style.background = '#fee2e2'; b.style.color = '#7f1d1d'; b.style.borderColor = '#fecaca'; break; +            default: b.style.background = '#eef2ff'; b.style.color = '#1e3a8a'; b.style.borderColor = '#c7d2fe'; +        } +    }; + +    function loadScript(url, done) { +        const filename = url.split('/').pop(); +        var s = document.createElement('script'); +        s.src = url + (url.indexOf('?') === -1 ? '?v=' : '&v=') + Date.now();  +        s.async = false; +         +        s.onload = function(){  +            log('LOAD SUCCESS', `Skript geladen: ${filename}`, 'green'); +            try {  +                done && done();  +            } catch(e){  +                if (e.message.includes('setting getter-only property "defaults"')) { +                    log('RUNTIME WARNING', `IGNORIERE Block-Konflikt in ${filename}: ${e.message}`, 'orange', 'warn'); +                } else { +                    // 🛑 KORREKTUR: force: true explizit auf false setzen (oder weglassen) +                    log('RUNTIME ERROR', `Fehler in Callback nach ${filename}: ${e.message}`, 'red', 'error', false);  +                } +            }  +        }; +         +        s.onerror = function(){  +            // 🛑 KORREKTUR: force: true explizit auf false setzen (oder weglassen) +            log('LOAD FAILED', `Skript FEHLT oder Pfad falsch: ${filename}`, 'red', 'error', false); +            badgeSay(`Ladefehler: ${filename}`, 'error'); +            try { done && done(); } catch(e){}  +        }; +        document.head.appendChild(s); +    } + +    /** +     * HILFSFUNKTION: Wandelt den Dateinamen (z.B. blocks-standard.js) in den globalen +     * Objektnamen (z.B. BridgeBlocksStandard) um. +     */ +    function getPluginObjectName(fileName) { +        // 1. Entferne Dateiendung (.js) +        let name = fileName.replace('.js', ''); // 'blocks-standard' +         +        // 2. Teile in Bestandteile zerlegen und den ersten Buchstaben groß schreiben +        const parts = name.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)); // ['Blocks', 'Standard'] +         +        // 3. Mit 'Bridge' prefixen und zusammenfügen +        return 'Bridge' + parts.join(''); // 'BridgeBlocksStandard' +    } +     +    // 🛑 NEUE FUNKTION: Erstellt alle in der Konfiguration definierten Kategorien. +    function ensureConfiguredCategories(editor) { +        const bm = editor.BlockManager; +        // HINWEIS: B.CATEGORY_CONFIG wird in category-config.js befüllt (muss vorher geladen werden) +        const config = window.BridgeParts?.CATEGORY_CONFIG || {}; + +        Object.keys(config) +            .sort((a, b) => (config[a].ord || 999) - (config[b].ord || 999)) +            .forEach(catId => { +                const catConf = config[catId]; +                // Category wird nur erstellt, wenn sie noch nicht existiert +                if (!bm.getCategories().get(catId)) { +                    bm.getCategories().add({ +                        id: catId, +                        label: catConf.label, +                        open: catConf.open !== false, +                        order: catConf.ord || 999 +                    }); +                    log('CAT INIT', `Kategorie '${catId}' explizit erstellt.`, 'green'); +                } +            }); +    } + +    function loadBridgeParts(cb){ +        const base = B.BASE_PATH_BRIDGE;  +         +        // 🛑 LOKALES LOGGING ENTFERNT, DA ES VOR B.log LIEGT. +        // log('LOAD START', 'Starte Laden der modularen Bridge-Teile (Geordnet).');  +         +        const coreFiles = [ +            base + 'general-functions.js', // <<< RE-AKTIVIERT: Für B.log +            base + 'category-config.js', // <<< RE-AKTIVIERT: Für B.CATEGORY_CONFIG (und damit API-Flexibilität) +            base + 'library-parts.js', +            base + 'categorization-master.js', +            base + 'categorization-cleanup.js', +        ]; + +        const initialLoadList = [...coreFiles]; +         +        function recursiveLoader(list, index = 0) { +            if (index >= list.length) { +                log('LOAD END', 'Initial-Bridge-Skripte geladen.', 'green'); +                 +                const config = window.BridgeParts?.CATEGORY_CONFIG || {}; +                let allBlockFiles = []; +                 +                // Dynamisches Sammeln der Block-Dateien aus der Config +                Object.keys(config) +                    .sort((a, b) => (config[a].ord || 999) - (config[b].ord || 999)) +                    .forEach(key => { +                        // Sammelt alle Dateien, egal ob sync oder async +                        if (Array.isArray(config[key].files)) { +                            allBlockFiles.push(...config[key].files.map(file => base + file));  +                        } +                    }); +                 +                // Duplikate entfernen (falls eine Datei in mehreren Kategorien gelistet ist) +                allBlockFiles = Array.from(new Set(allBlockFiles)); +                 +                function loadBlockFiles(blockIndex = 0) { +                    if (blockIndex >= allBlockFiles.length) { +                        log('LOAD END', 'Alle Blöcke geladen.', 'green'); +                        return cb && cb(B); +                    } +                    log('LOADING BLOCKS', `Lade Block-Skript [${blockIndex + 1}/${allBlockFiles.length}]: ${allBlockFiles[blockIndex].split('/').pop()}`); +                    loadScript(allBlockFiles[blockIndex], function(){ +                        loadBlockFiles(blockIndex + 1); +                    }); +                } +                loadBlockFiles(); +                return; +            } +             +            // 🛑 LOKALES LOGGING ENTFERNT, DA ES VOR B.log LIEGT. +            log('LOADING CORE', `Lade Skript [${index + 1}/${initialLoadList.length}]: ${list[index].split('/').pop()}`); // Loggt ab dem 3. Skript, da general-functions.js an 2. Stelle geladen wird. + +            loadScript(list[index], function(){ +                recursiveLoader(list, index + 1); +            }); +        } +         +        recursiveLoader(initialLoadList); +    } + +    try { parent.postMessage({ source:'bridge', type:'boot' }, '*'); } catch {} +    var MODE = (window.__editorMode || 'templates').toLowerCase(); + +    const replaceReferenceLibrary = (editor, ref, mode) => {  +        (window.BridgeParts?.addReferenceLibrary || (()=>{}))(editor, ref, mode);  +    }; +    const upsertCustomForBothCats = (editor, payload) => {  +        (window.BridgeParts?.upsertCustomForBothCats || (()=>{}))(editor, payload); +    }; +     +    // --- Init & Events (Plugin integriert) --------------------------------------------- +    loadBridgeParts(function(B){ +        log('INIT START', 'Alle Bridge-Teile geladen, starte GrapesJS-Initialisierung.', 'orange'); +         +        if (typeof grapesjs === 'undefined' || !grapesjs.init) { +            // 🛑 KORREKTUR: force: true explizit auf false setzen (oder weglassen) +            log('CRITICAL ERROR', 'Das globale Objekt grapesjs ist nicht verfügbar! Laden von grapes.min.js ist fehlgeschlagen.', 'red', 'error', false); +            badgeSay('Fehler: GrapesJS nicht geladen!', 'error'); +            return;  +        } + +        // 🛑 KRITISCHER FIX TEIL 1: Registriere alle gesammelten Bridge-Plugins global. +        if (typeof grapesjs.plugins.add === 'function') { +            B.GrapesJSPlugins.forEach(p => { +                grapesjs.plugins.add(p.name, p.pluginFn); +                log('PLUGIN ACTIVATION', `GrapesJS Plugin global bereitgestellt: ${p.name}`, 'lime'); +            }); +        } else { +            // 🛑 KORREKTUR: force: true explizit auf false setzen (oder weglassen) +            log('PLUGIN ERROR', `GrapesJS Plugin-API (grapesjs.plugins.add) fehlt. Plugins können nicht registriert werden.`, 'red', 'error', false); +        } + +        // 🛑 KRITISCHER FIX: Safety Plugin MUSS die fehlenden Views Panels hinzufügen. +        function safetyPlugin(editor){ +            const pn = editor.Panels, orig = pn.getButton.bind(pn); +            pn.getButton = (pid, id) => orig(pid, id) || { set(){}, get(){ return null; } };  +             +            // Fügen Sie das Panel 'views' hinzu, wenn es fehlt +            if(!pn.getPanel('views')) { +                pn.addPanel({ id: 'views', el: '.gjs-pn-views' });  +                log('PANEL FIX', "Das 'views' Panel wurde nachträglich hinzugefügt.", 'yellow', 'warn'); +            } +             +            // Stellen Sie sicher, dass der Block Manager in den Views-Container rendert +            editor.Config.blockManager = editor.Config.blockManager || {}; +            editor.Config.blockManager.appendTo = editor.Config.blockManager.appendTo || '.gjs-blocks'; +             +            // Der fehlerhafte Timeout-Block wurde entfernt. +        } + +        let pluginsList = [ +            safetyPlugin,  +            // 🛑 KRITISCHE ERGÄNZUNG: Aktiviert das registrierte API-Plugin +            'bridge-blocks-api',  +            'bridge-categorization-master',  +            'bridge-categorization-cleanup', +        ]; + +        if (LOAD_NEWSLETTER_PRESET) { +            pluginsList.push('gjs-preset-newsletter'); +        } +         +        // Speicherkonfiguration extrahieren, um die URL in onLoad zu verwenden. +        // 🎯 KORREKTUR für mehr Flexibilität: Verwende B.STORAGE_URL_BASE, falls gesetzt, anstatt window.location.href. +        // Verwenden Sie B.API_BASE (Standard /api/editor) als Fallback für die Storage-URL +        const storageBase = B.STORAGE_URL_BASE || B.API_BASE; // B.API_BASE sollte jetzt korrekt sein + +        // Robustes Anhängen von Query-Parametern. +        // Prüft, ob 'storageBase' bereits Query-Parameter enthält ('?') +        const actionSeparator = storageBase.indexOf('?') === -1 ? '?' : '&'; + +        const loadUrl = storageBase + actionSeparator + 'action=get&resource=' + (window.__editorMode || 'templates') + '&id=' + (window.__editorId || 0); // KRITISCHE ERGÄNZUNG: Resource und ID +        const storeUrl = storageBase + actionSeparator + 'action=update&resource=' + (window.__editorMode || 'templates') + '&id=' + (window.__editorId || 0); // KRITISCHE ERGÄNZUNG: Resource und ID + +        const storageConf = { +            type: 'remote', +            // urlLoad: loadUrl, // ENTFERNT (korrekt, da customFetch verwendet wird) +            urlStore: storeUrl, +             +            // 🛑 KRITISCHER ABSCHNITT: customFetch MUSS DIE ERWARTETE SIGNATUR HABEN: customFetch(url, options) +            customFetch: async (url, options) => { // <<< KORREKTUR DER SIGNATUR +                // 1. Log Start +                log('STORAGE START', 'Template wird geladen.', '#008080', 'info', true);  +                // 2. Log Link +                log('API REQUEST', `Link für den API Request: ${loadUrl}`, '#4682B4', 'log', false);  + +                const fetchOptions = { +                    method: 'GET', +                    headers: { 'Content-Type': 'application/json' }, +                    // Wichtig: Die übergebenen Optionen nicht vergessen zu mergen +                    ...options +                }; +                 +                let data = {}; +                let rawResponse = ''; + +                try { +                    // Verwendung der intern definierten loadUrl +                    const response = await fetch(loadUrl, fetchOptions);  +                     +                    if (!response.ok) { +                        const errorText = await response.text(); +                        throw new Error(`HTTP-Fehler ${response.status}: ${errorText}`); +                    } + +                    // Holen des Raw Texts, um ihn loggen und parsen zu können +                    rawResponse = await response.text(); +                     +                    // 3. Log Result +                    log('API RESPONSE', 'Result vom API Request (Raw Text/JSON):', '#4682B4', 'log', false); +                    console.log(rawResponse); // Loggt den reinen String für die Analyse +                     +                    // Versuch der JSON-Analyse (um den GrapesJS-Fehler zu vermeiden) +                    try { +                        data = JSON.parse(rawResponse); +                        log('STORAGE PARSE', 'Raw Response als JSON geparst.', 'green'); +                    } catch (e) { +                        log('STORAGE PARSE ERROR', `Fehler beim Parsen der Antwort: ${e.message}. Antwort war wahrscheinlich kein gültiges JSON.`, 'red', 'error', true); +                        // Im Falle eines Parsing-Fehlers, leeres Objekt für Fallback-Logik +                        data = {}; +                    } + +                } catch (e) { +                    log('STORAGE FETCH ERROR', `Fehler beim Abruf: ${e.message}`, 'red', 'error', true); +                    // Sicherstellen, dass die Promise mit einem leeren Zustand erfüllt wird +                    // Wir müssen dennoch den Log End ausführen, bevor wir zurückkehren +                } +                 +                // 4. Log End +                log('STORAGE END', 'Template wurde geladen.', '#008080', 'info', true);  +                 +                // --- Logik zur Extraktion des GrapesJS States aus der API-Antwort --- +                let state = {}; + +                if (data && data.gjs_data) { +                    log('STORAGE LOAD', 'Voller GrapesJS State aus "gjs_data" geladen.', 'green'); +                    state = data.gjs_data;  +                } +                else if (data && data.content) { +                    try { +                        const parsedState = JSON.parse(data.content); +                        log('STORAGE LOAD', 'Voller GrapesJS State aus "content" (JSON-String) geladen.', 'yellow'); +                        state = parsedState; +                    } catch (e) { +                        log('STORAGE ERROR', `Fehler beim Parsen von "content": ${e.message}.`, 'red', 'error'); +                    } +                } +                // HINWEIS: Füge Fallback für "topContent" hinzu, basierend auf dem Server-Log +                else if (data && data.topContent) { +                    try { +                        const parsedState = JSON.parse(data.topContent); +                        log('STORAGE LOAD', 'Voller GrapesJS State aus "topContent" (JSON-String) geladen.', 'green'); +                        state = parsedState; +                    } catch (e) { +                        log('STORAGE ERROR', `Fehler beim Parsen von "topContent": ${e.message}.`, 'red', 'error'); +                    } +                } +                else { +                    log('STORAGE WARNING', 'Kein vollständiger GrapesJS State gefunden. Editor lädt leeren State.', 'orange', 'warn'); +                } + +                // customFetch MUSS den geladenen State zurückgeben +                return state; +            }, +            // --- ENDE customFetch --- + +            // onLoad ist bei customFetch nicht mehr nötig +            // onLoad: (response) => { ... },  +             +            // KRITISCH: Speichert den vollen State als JSON-String im Feld 'json_content'. +            onStore: (data) => { +                // ACHTUNG: ed existiert hier nicht, muss über window.__gjs geladen werden ODER ed als Argument akzeptiert werden +                const ed = window.__gjs; +                return { +                    json_content: JSON.stringify(data),  +                    html: ed ? ed.getHtml() : '' // Fügen Sie den HTML-Output zur Abwärtskompatibilität hinzu +                }; +            }, +        }; + +        var ed = grapesjs.init({ +            container: '#gjs', +            height: '100vh', +             +            // 🛑 KRITISCHE KORREKTUR: storageManager aktivieren und konfigurieren +            storageManager: storageConf, +             +            plugins: pluginsList,  +            pluginsOpts: {}, +            // 🛑 KRITISCHE ERGÄNZUNG: Verhindert das automatische Ausblenden leerer Kategorien +            blockManager: {  +                hideEmpty: false  +            } +        }); +         +        window.__gjs = ed; +         +        // 🛑 KRITISCHE KORREKTUR 1: Explizite Erstellung aller konfigurierten Kategorien +        ensureConfiguredCategories(ed);  + +        // 🛑 KRITISCHE KORREKTUR 2: Sofortige Label-Korrektur +        // Überschreibt den potenziell falschen, durch GrapesJS gesetzten Label-Namen +        Object.keys(B.CATEGORY_CONFIG || {}).forEach(catId => { +            const expectedLabel = B.CATEGORY_CONFIG[catId].label; +            const categoryModel = ed.BlockManager.getCategories().get(catId); +             +            if (categoryModel && categoryModel.get('label') !== expectedLabel) { +                // Setzen ohne das 'change:label' Event auszulösen (optional, aber sauber) +                categoryModel.set('label', expectedLabel, { silent: true });  +                log('LABEL FIX', `Kategorie '${catId}' Label auf korrigiert: '${expectedLabel}'`, 'yellow', 'warn'); +            } +        }); +        // --------------------------------------------------- + +        B.ensureViews && B.ensureViews(ed); +         +        log('BLOCK REGISTER', 'Registriere Bridge Blöcke, um Preset-Defaults zu überschreiben.', 'purple'); + +        // 🛑 DYNAMISCHE AKTIVIERUNG DER SYNCHRONEN BLÖCKE (Ersetzt die fixen Aufrufe) +        if (B.CATEGORY_CONFIG && ed) { +            log('DYNAMIC ACTIVATION', 'Starte Aktivierung synchroner Block-Plugins (via Config).', 'purple'); +             +            // Iteriere über die konfigurierten Kategorien +            Object.keys(B.CATEGORY_CONFIG).forEach(catId => { +                const config = B.CATEGORY_CONFIG[catId]; +                 +                // Verarbeite nur SYNCHRONE Plugins, die Dateien angeben +                if (config.registration_mode === 'sync' && Array.isArray(config.files)) { +                     +                    config.files.forEach(fileName => { +                         +                        // Korrigierte Funktion liefert jetzt z.B. 'BridgeBlocksCustom' +                        const objectName = getPluginObjectName(fileName);  +                        const plugin = window[objectName]; +                         +                        // Prüfen, ob das Skript geladen wurde und die Register-Funktion vorhanden ist +                        if (plugin && typeof plugin.register === 'function') { +                            log('DYNAMIC ACTIVATION', `Registriere sync Plugin: ${objectName} (${fileName})`, 'lime'); +                            try { +                                plugin.register(ed); +                            } catch(e) { +                                log('DYNAMIC ACTIVATION ERROR', `Fehler beim Registrieren von ${objectName}: ${e.message}`, 'red', 'error'); +                            } +                        } else { +                            log('DYNAMIC ACTIVATION WARNING', `Sync Plugin Objekt oder .register() Methode nicht gefunden: ${objectName} (${fileName})`, 'orange', 'warn'); +                        } +                    }); +                } +            }); +        } +        // --------------------------------------------------- + +        log('INIT API', 'API-Elemente werden nun durch das Plugin bridge-blocks-api geladen. (ASYNCHRON)', 'orange');  + +        // ---------------------------------------------------------------------- +        // DEBUGGING: ZÄHLE REKURSIVE EVENTS +        // ---------------------------------------------------------------------- +        let eventCounts = {}; +        let isParsing = false;  +        const MAX_CALLS = 1000;  + +        const debugEvents = [ +            'component:add',  +            'component:update',  +            'change:components',  +            'block:add', +            'change:attributes', +            'comp:update:status' +        ]; + +        const debugListener = (event, model) => { +            if (!isParsing) return; + +            if (!eventCounts[event]) { +                eventCounts[event] = 0; +            } +            eventCounts[event]++; + +            if (eventCounts[event] === MAX_CALLS + 1) {  +                // Diese kritischen Debug-Meldungen bleiben DIREKT im console-Objekt,  +                // da sie immer sichtbar sein müssen, um Endlosschleifen zu erkennen. +                console.error(`%c[DEBUG RECURSION ALARM] 🚨 Event '${event}' hat den Grenzwert von ${MAX_CALLS} überschritten!`, 'color:red; font-size: 1.1em; font-weight: bold;'); +            } +             +            if (eventCounts[event] > MAX_CALLS && eventCounts[event] < (MAX_CALLS + 10)) {  +                 const type = (model && typeof model.get === 'function') ? model.get('type') : 'N/A'; +                 const parentType = (model && typeof model.parent === 'function' && model.parent()) ? model.parent().get('type') : 'N/A'; +                 // Diese bleiben console.log aus demselben Grund +                 console.log(`%c [RECURSION SOURCE] Event: ${event}, Type: ${type}, Parent: ${parentType}`, 'color: #8b0000;'); +            } +        }; + +        ed.on('load', function() { +            debugEvents.forEach(event => ed.on(event, (model) => debugListener(event, model))); +             +            setTimeout(() => { +                (B.waitForBlocks ? B.waitForBlocks(ed) : Promise.resolve()).then(function(){ +                    try { +                        log('CORE WARN', 'Führe finalen, verzögerten Cleanup-Lauf durch (2000ms).', 'orange', 'warn'); +                         +                        B.normalizeCategories && B.normalizeCategories(ed);  +                        B.renderBlocks && B.renderBlocks(ed);  + +                    } catch(e) { +                        log('CORE ERROR', `Finaler Cleanup-Fehler: ${e.message}`, 'red', 'error'); +                    } +                }); +            }, 2000);  + +        }, { once: true }); + + +        // ---------------------------------------------------------------------- +        // MESSAGE HANDLER +        // ---------------------------------------------------------------------- +        window.addEventListener('message', async function(ev){  +            var data = ev.data || {}; +            if (data.source !== 'admin') return; + +            if (data.type === 'init'){ +                B.ensureViews && B.ensureViews(ed); + +                var html = (data.html || '').trim(); +                if (!html) html = '

Neues Dokument

Inhalt ...

'; +                 +                const applySnips = function(arr){ +                    const list = (Array.isArray(arr)?arr:[]).map(s => ({ id:s.id, name:s.name, html: s.html || s.content || '' })); +                     +                    B.replaceSnippetBlocks && B.replaceSnippetBlocks(ed, list);  +                     +                    upsertCustomForBothCats(ed, { +                        ref: (data.ref && (Array.isArray(data.ref.sections) || Array.isArray(data.ref.blocks))) ? { +                            sections: data.ref.sections || [], +                            blocks:      data.ref.blocks        || [] +                        } : { sections: [], blocks: [] }, +                        snippets: list +                    }); +                     +                    setTimeout(() => { +                        try { +                            // Erneutes Normalisieren nach Laden der Snippets (falls nötig) +                            B.normalizeCategories && B.normalizeCategories(ed);  +                            B.ensureViews && B.ensureViews(ed); +                            B.renderBlocks && B.renderBlocks(ed); +                            log('CORE WARN', 'normalize/render nach applySnips ausgeführt (1ms).', 'orange', 'warn');  +                        } catch(e) { +                            log('CORE ERROR', `applySnips-Cleanup-Fehler: ${e.message}`, 'red', 'error'); +                        } +                    }, 1);  + +                }; + +                if (Array.isArray(data.snippets) && data.snippets.length) applySnips(data.snippets); +                else (B.fetchSnippets ? B.fetchSnippets() : Promise.resolve([])).then(applySnips); + +                if (data.ref && (Array.isArray(data.ref.sections) || Array.isArray(data.ref.blocks))) { +                    replaceReferenceLibrary(ed, { +                        sections: data.ref.sections || [], +                        blocks:      data.ref.blocks        || [] +                    }, MODE); +                } + +                // Finaler Aufruf nachrichtengesteuert (konsolidiert) +                setTimeout(() => { +                    (B.waitForBlocks ? B.waitForBlocks(ed) : Promise.resolve()).then(function(){ +                        try { +                            log('CORE WARN', 'Führe nachrichtengesteuerten Final-Cleanup-Lauf durch (100ms).', 'orange', 'warn');  +                             +                            // 🛑 KRITISCHE KORREKTUR: Entferne das erzwungene ed.setComponents(html) +                            // Das Laden des Inhalts wird jetzt vom storageManager übernommen (via customFetch). +                            if (!ed.__contentLoaded) { +                                log('CONTENT', 'Erster Ladevorgang (storageManager) ist abgeschlossen.', 'orange'); +                                 +                                // HINWEIS: Wenn der Editor initial leer lädt (z.B. neue Vorlage), +                                // MUSS hier der initiale HTML-Code eingefügt werden. +                                // Da der storageManager aber automatisch lädt,  +                                // sollte dieser Block nur für den Initialfall "Neu" greifen. +                                if (html && !ed.getComponents().length) { +                                    window.__GJS_IS_PARSING = true;  +                                    isParsing = true; +                                    eventCounts = {}; +                                    try { +                                        ed.setComponents(html);  +                                    } catch (e) { +                                        log('SET COMPONENTS FAILED', `setComponents Fehler: ${e.message}. Aufgerufene Event-Zähler: ${JSON.stringify(eventCounts)}`, 'red', 'error'); +                                        throw e;  +                                    } finally { +                                        window.__GJS_IS_PARSING = false; +                                        isParsing = false; +                                        log('CONTENT', 'HTML-Inhalt in den Editor geladen (FALLBACK).', 'orange'); +                                    } +                                } + +                                ed.__contentLoaded = true; + +                            } +                             +                            // Normalisierung am Ende +                            B.normalizeCategories && B.normalizeCategories(ed);  +                            B.renderBlocks && B.renderBlocks(ed); +                             +                        } catch(e) { +                            log('CORE ERROR', `Nachrichten-Final-Cleanup-Fehler: ${e.message}. Event-Zähler (im Log-Objekt): ${JSON.stringify(eventCounts)}`, 'red', 'error'); +                        } +                    }); +                }, 100);  + + +                try { var b=ed.Panels.getButton('views','open-blocks'); b && b.set('active',true); } catch {} +                badgeSay('Inhalt geladen','ok'); +                setTimeout(function(){ badgeSay('bereit'); }, 1200); +            } +        }, false); +         +        try { B.send && B.send('core-ready', { mode: MODE }); } catch {} +        try { var bd=document.getElementById('badge'); if (bd) bd.remove(); } catch {} +    }); +     +    window.onerror = function(message, source, lineno, colno, error) {  +        // Diese kritische Funktion MUSS console.error verwenden. +        console.error(`%c[${PluginName} - GLOBAL ERROR] Uncaught JS Error: ${message} (Quelle: ${source}:${lineno})`, 'color:red; font-weight:bold;'); +        return false;  +    }; +     +})(); diff --git a/public/editor/config.js b/public/editor/config.js new file mode 100644 index 0000000..aecbbc3 --- /dev/null +++ b/public/editor/config.js @@ -0,0 +1,76 @@ +/* /editor/config.js (SCHRITT 35: LOG-EBENEN-KONTROLLE) */ +(function() { + + // Stelle sicher, dass BridgeParts existiert und hole die registrierten Plugins. + const B = window.BridgeParts || {}; + + // --- 🎯 ZENTRALE LOG-KONFIGURATION (Überschreibt general-functions.js Defaults) --- + // HINWEIS: Dies muss NACH general-functions.js geladen werden. + B.LOG_CONFIG = B.LOG_CONFIG || {}; + + // 1. HAUPTSCHALTER: Deaktiviert alle normalen Logs (muss auf 'true' sein, damit die Ebenen-Schalter wirken) + B.LOG_CONFIG.GLOBAL_DEBUG = true; + + // 2. EBENEN-SCHALTER (wirken nur, wenn GLOBAL_DEBUG = true): + B.LOG_CONFIG.INFO_ENABLED = true; // Aktiviert/Deaktiviert alle Info-Logs (B.log mit type='info') + B.LOG_CONFIG.WARN_ENABLED = true; // Aktiviert/Deaktiviert alle Warn-Logs (B.log mit type='warn') + B.LOG_CONFIG.ERROR_ENABLED = true; // Aktiviert/Deaktiviert alle Error-Logs (B.log mit type='error') + + // 3. DATEN-SCHALTER: Aktiviert/Deaktiviert die Ausgabe großer Array-Daten (B.logData) + B.LOG_CONFIG.DATA_ENABLED = true; + + // ---------------------------------------------------------------------------------- + + + // Sammle alle dynamisch registrierten Plugin-Namen. + // Der Array B.GrapesJSPlugins wurde von bridge-core.js, blocks-api.js etc. gefüllt. + const dynamicPluginNames = B.GrapesJSPlugins + ? B.GrapesJSPlugins.map(p => p.name) + : []; + + // Optional: Fügen Sie statische GrapesJS-Plugins hinzu + const staticPlugins = [ + 'gjs-preset-newsletter' // Beispiel: Fügt den Newsletter-Preset hinzu, falls gewünscht + ]; + + // Kombiniere alle Plugin-Namen zu einer eindeutigen Liste + const uniquePlugins = [...new Set([ + ...dynamicPluginNames, + ...staticPlugins + ])]; + + + // Definiere die Haupt-Konfiguration für GrapesJS + const editorConfig = { + // 1. WICHTIG: Ersetze 'gjs' durch die ID des Containers + container: '#gjs', + + // 2. KRITISCH: Die dynamisch erstellte Plugin-Liste + plugins: uniquePlugins, + + // 3. Plugin-Optionen (können leer bleiben, wenn keine Optionen benötigt werden) + pluginsOpts: { + // Hier Optionen für einzelne Plugins eintragen + }, + + // --- Andere Basis-Konfigurationen --- + panels: { + defaults: [ + { id: 'options', el: '.panel__options', buttons: [{ id: 'save', label: 'Speichern', className: 'fa fa-floppy-o' }] }, + { id: 'views', el: '.panel__views' }, + ] + }, + + // ... Fügen Sie hier weitere GrapesJS-Optionen ein (z.B. device buttons) + }; + + // Starte GrapesJS + // window.GrapesJS.init wurde in bridge-core.js definiert, um GrapesJS zu starten. + if (window.GrapesJS && window.GrapesJS.init) { + // Übergebe editorConfig und die Liste der Plugin-Funktionen + window.GrapesJS.init(editorConfig, B.GrapesJSPlugins.map(p => p.name), B.GrapesJSPlugins); + } else { + console.error('GrapesJS.init ist in window.GrapesJS nicht verfügbar. Wurde bridge-core.js geladen?'); + } + +})(); diff --git a/public/editor/editor-core (Kopie).php b/public/editor/editor-core (Kopie).php new file mode 100644 index 0000000..1e524ff --- /dev/null +++ b/public/editor/editor-core (Kopie).php @@ -0,0 +1,64 @@ + + + + + + Editor + + + + +
lädt …
+ +
+ + + + + diff --git a/public/editor/editor-core.php b/public/editor/editor-core.php new file mode 100644 index 0000000..18b011d --- /dev/null +++ b/public/editor/editor-core.php @@ -0,0 +1,79 @@ + + + + + + Editor + + + + +
lädt …
+
+ +
+ + + + diff --git a/public/index.php b/public/index.php new file mode 100644 index 0000000..d6cd6ee --- /dev/null +++ b/public/index.php @@ -0,0 +1,169 @@ + + + + + + + Email Template System – Admin + + + + + + + + + + + + + + + + + + +
+
+

Email Template System

+ +
+ + + + API-Health + + DB-Doctor +
+
+
+ +
+
+ + + +
+ + + +
+

Neues Element erstellen

+

+
+
+ + +
+
+
+ + + +
+

Eintrag löschen?

+

+
+ + +
+
+
+ + + +
+
+ E-Mail Editor + + + +
+ +
+
+ + + +
+
+ Vorschau + +
+ +
+
+ + + +
+

Snippet bearbeiten

+
+ + +
+
+ + +
+
+
+ + + +
+
+ Werkzeug + + + +
+ + + + + + +
+
+ +
+ + + + + + diff --git a/public/login.php b/public/login.php new file mode 100644 index 0000000..1c04d27 --- /dev/null +++ b/public/login.php @@ -0,0 +1,70 @@ + + + + + Login – EmailTemplate + + + + + + + + + + + + + + + + +
+

Willkommen zurück

+

Melde dich an, um deine kundenspezifischen Templates zu verwalten.

+ + + + + + +
+ + diff --git a/public/tools/config-doctor.php b/public/tools/config-doctor.php new file mode 100644 index 0000000..07efbf5 --- /dev/null +++ b/public/tools/config-doctor.php @@ -0,0 +1,9 @@ +$path,'exists'=>false,'readable'=>false,'type'=>null,'keys'=>[], 'notes'=>[]]; +if (is_file($path)) { $out['exists']=true; $out['readable']=is_readable($path); + try { $cfg = require $path; $out['type']=gettype($cfg); if (is_array($cfg)) { $out['keys']=array_keys($cfg); } } + catch (Throwable $e) { $out['notes'][] = $e->getMessage(); } +} else { $out['notes'][]='file not found'; } +echo json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); \ No newline at end of file diff --git a/public/tools/db-doctor.php b/public/tools/db-doctor.php new file mode 100644 index 0000000..8b011c3 --- /dev/null +++ b/public/tools/db-doctor.php @@ -0,0 +1,118 @@ +PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,PDO::ATTR_EMULATE_PREPARES=>false]); + $attempts[]=['dsn'=>$dsn,'ok'=>true]; + return $pdo; + }catch(Throwable $e){ + $attempts[]=['dsn'=>$dsn,'ok'=>false,'error'=>$e->getMessage()]; + return null; + } +}; + +if (is_array($cfg)) $pdo=$mkPdo($cfg); + +$tables = [ + $prefix.'templates', + $prefix.'sections', + $prefix.'blocks', + $prefix.'snippets', + $prefix.'template_items', + $prefix.'section_items', +]; + +$tblStatus=[]; +if ($pdo){ + foreach($tables as $t){ + try{ $pdo->query("SELECT 1 FROM {$t} LIMIT 1"); $tblStatus[$t]='ok'; } + catch(Throwable $e){ $tblStatus[$t]='missing/invalid: '.$e->getMessage(); } + } +} +?> + + + +DB-Doctor (<?=h($profile)?>) + + +

DB-Doctor (Profil: )

+ + + +
+

Verbindungsversuche

+ + + + + + + + + +
DSNErgebnisDetail
OK' : 'FAIL' ?>
+
+ +
+

Tabellen-Check (Templates-Schema)

+ + + + + + + + +
TabelleStatus
+ OK' : ''.h($s).''; ?> +
+
+ +
+

Rohdaten

+
$prefix,
+    'hasPdo'=>!!$pdo,
+    'configKeys'=>array_keys($conf),
+  ], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES))?>
+
+ + diff --git a/public/vendor/grapesjs-preset-newsletter/.keep b/public/vendor/grapesjs-preset-newsletter/.keep new file mode 100644 index 0000000..7c888a6 --- /dev/null +++ b/public/vendor/grapesjs-preset-newsletter/.keep @@ -0,0 +1 @@ +Place vendor files here (grapesjs, grapesjs-preset-newsletter). \ No newline at end of file diff --git a/public/vendor/grapesjs-preset-newsletter/grapesjs-preset-newsletter.min.js b/public/vendor/grapesjs-preset-newsletter/grapesjs-preset-newsletter.min.js new file mode 100644 index 0000000..17d947f --- /dev/null +++ b/public/vendor/grapesjs-preset-newsletter/grapesjs-preset-newsletter.min.js @@ -0,0 +1,15 @@ +/*! grapesjs-preset-newsletter - 0.2.21 */ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("grapesjs")):"function"==typeof define&&define.amd?define(["grapesjs"],e):"object"==typeof exports?exports["grapesjs-preset-newsletter"]=e(require("grapesjs")):t["grapesjs-preset-newsletter"]=e(t.grapesjs)}("undefined"!=typeof self?self:this,function(t){return function(t){function e(n){if(r[n])return r[n].exports;var i=r[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var r={};return e.m=t,e.c=r,e.d=function(t,r,n){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:n})},e.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=46)}([function(t,e){var r;r=function(){return this}();try{r=r||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(r=window)}t.exports=r},function(t,e){"function"==typeof Object.create?t.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},function(t,e,r){"use strict";function n(t){if(!(this instanceof n))return new n(t);c.call(this,t),l.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",i)}function i(){this.allowHalfOpen||this._writableState.ended||a.nextTick(o,this)}function o(t){t.end()}var a=r(14),s=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};t.exports=n;var u=r(8);u.inherits=r(1);var c=r(36),l=r(21);u.inherits(n,c);for(var f=s(l.prototype),h=0;h1)for(var r=1;r)[^>]*$|#([\w\-]*)$)/;e.isHtml=function(t){if("<"===t.charAt(0)&&">"===t.charAt(t.length-1)&&t.length>=3)return!0;var e=a.exec(t);return!(!e||!e[1])}},function(t,e){t.exports={trueFunc:function(){return!0},falseFunc:function(){return!1}}},function(t,e,r){(function(n){var i=r(3);e=t.exports=function(t,r){var n=e.evaluate(t,r),i=e.evaluate("",r)[0];return i.type="root",e.update(n,i),i},e.evaluate=function(t,e){return"string"==typeof t||n.isBuffer(t)?i.parseDOM(t,e):t},e.update=function(t,e){Array.isArray(t)||(t=[t]),e?e.children=t:e=null;for(var r=0;r=n())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n().toString(16)+" bytes");return 0|t}function g(t){return+t!=t&&(t=0),o.alloc(+t)}function v(t,e){if(o.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return $(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(t).length;default:if(n)return $(t).length;e=(""+e).toLowerCase(),n=!0}}function y(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,e>>>=0,r<=e)return"";for(t||(t="utf8");;)switch(t){case"hex":return B(this,e,r);case"utf8":case"utf-8":return T(this,e,r);case"ascii":return L(this,e,r);case"latin1":case"binary":return C(this,e,r);case"base64":return A(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function b(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function m(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=o.from(e,n)),o.isBuffer(e))return 0===e.length?-1:_(t,e,r,n,i);if("number"==typeof e)return e&=255,o.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):_(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function _(t,e,r,n,i){function o(t,e){return 1===a?t[e]:t.readUInt16BE(e*a)}var a=1,s=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;a=2,s/=2,u/=2,r/=2}var c;if(i){var l=-1;for(c=r;cs&&(r=s-u),c=r;c>=0;c--){for(var f=!0,h=0;hi&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var a=0;a239?4:o>223?3:o>191?2:1;if(i+s<=r){var u,c,l,f;switch(s){case 1:o<128&&(a=o);break;case 2:u=t[i+1],128==(192&u)&&(f=(31&o)<<6|63&u)>127&&(a=f);break;case 3:u=t[i+1],c=t[i+2],128==(192&u)&&128==(192&c)&&(f=(15&o)<<12|(63&u)<<6|63&c)>2047&&(f<55296||f>57343)&&(a=f);break;case 4:u=t[i+1],c=t[i+2],l=t[i+3],128==(192&u)&&128==(192&c)&&128==(192&l)&&(f=(15&o)<<18|(63&u)<<12|(63&c)<<6|63&l)>65535&&f<1114112&&(a=f)}}null===a?(a=65533,s=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),i+=s}return O(n)}function O(t){var e=t.length;if(e<=K)return String.fromCharCode.apply(String,t);for(var r="",n=0;nn)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function P(t,e,r,n,i,a){if(!o.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function M(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function R(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function I(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function N(t,e,r,n,i){return i||I(t,e,r,4,3.4028234663852886e38,-3.4028234663852886e38),X.write(t,e,r,n,23,4),r+4}function U(t,e,r,n,i){return i||I(t,e,r,8,1.7976931348623157e308,-1.7976931348623157e308),X.write(t,e,r,n,52,8),r+8}function F(t){if(t=z(t).replace(tt,""),t.length<2)return"";for(;t.length%4!=0;)t+="=";return t}function z(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function V(t){return t<16?"0"+t.toString(16):t.toString(16)}function $(t,e){e=e||1/0;for(var r,n=t.length,i=null,o=[],a=0;a55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function H(t){for(var e=[],r=0;r>8,i=r%256,o.push(i),o.push(n);return o}function G(t){return Q.toByteArray(F(t))}function Y(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function J(t){return t!==t}/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +var Q=r(55),X=r(56),Z=r(29);e.Buffer=o,e.SlowBuffer=g,e.INSPECT_MAX_BYTES=50,o.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}(),e.kMaxLength=n(),o.poolSize=8192,o._augment=function(t){return t.__proto__=o.prototype,t},o.from=function(t,e,r){return a(null,t,e,r)},o.TYPED_ARRAY_SUPPORT&&(o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0})),o.alloc=function(t,e,r){return u(null,t,e,r)},o.allocUnsafe=function(t){return c(null,t)},o.allocUnsafeSlow=function(t){return c(null,t)},o.isBuffer=function(t){return!(null==t||!t._isBuffer)},o.compare=function(t,e){if(!o.isBuffer(t)||!o.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,n=e.length,i=0,a=Math.min(r,n);i0&&(t=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(t+=" ... ")),""},o.prototype.compare=function(t,e,r,n,i){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var a=i-n,s=r-e,u=Math.min(a,s),c=this.slice(n,i),l=t.slice(e,r),f=0;fi)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return w(this,t,e,r);case"utf8":case"utf-8":return x(this,t,e,r);case"ascii":return S(this,t,e,r);case"latin1":case"binary":return j(this,t,e,r);case"base64":return k(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var K=4096;o.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e0&&(i*=256);)n+=this[t+--e]*i;return n},o.prototype.readUInt8=function(t,e){return e||q(t,1,this.length),this[t]},o.prototype.readUInt16LE=function(t,e){return e||q(t,2,this.length),this[t]|this[t+1]<<8},o.prototype.readUInt16BE=function(t,e){return e||q(t,2,this.length),this[t]<<8|this[t+1]},o.prototype.readUInt32LE=function(t,e){return e||q(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},o.prototype.readUInt32BE=function(t,e){return e||q(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},o.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||q(t,e,this.length);for(var n=this[t],i=1,o=0;++o=i&&(n-=Math.pow(2,8*e)),n},o.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||q(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},o.prototype.readInt8=function(t,e){return e||q(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},o.prototype.readInt16LE=function(t,e){e||q(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt16BE=function(t,e){e||q(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt32LE=function(t,e){return e||q(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},o.prototype.readInt32BE=function(t,e){return e||q(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},o.prototype.readFloatLE=function(t,e){return e||q(t,4,this.length),X.read(this,t,!0,23,4)},o.prototype.readFloatBE=function(t,e){return e||q(t,4,this.length),X.read(this,t,!1,23,4)},o.prototype.readDoubleLE=function(t,e){return e||q(t,8,this.length),X.read(this,t,!0,52,8)},o.prototype.readDoubleBE=function(t,e){return e||q(t,8,this.length),X.read(this,t,!1,52,8)},o.prototype.writeUIntLE=function(t,e,r,n){if(t=+t,e|=0,r|=0,!n){P(this,t,e,r,Math.pow(2,8*r)-1,0)}var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},o.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||P(this,t,e,1,255,0),o.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},o.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||P(this,t,e,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):M(this,t,e,!0),e+2},o.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||P(this,t,e,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):M(this,t,e,!1),e+2},o.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||P(this,t,e,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):R(this,t,e,!0),e+4},o.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||P(this,t,e,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):R(this,t,e,!1),e+4},o.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);P(this,t,e,r,i-1,-i)}var o=0,a=1,s=0;for(this[e]=255&t;++o>0)-s&255;return e+r},o.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);P(this,t,e,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[e+o]=255&t;--o>=0&&(a*=256);)t<0&&0===s&&0!==this[e+o+1]&&(s=1),this[e+o]=(t/a>>0)-s&255;return e+r},o.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||P(this,t,e,1,127,-128),o.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},o.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||P(this,t,e,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):M(this,t,e,!0),e+2},o.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||P(this,t,e,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):M(this,t,e,!1),e+2},o.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||P(this,t,e,4,2147483647,-2147483648),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):R(this,t,e,!0),e+4},o.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||P(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):R(this,t,e,!1),e+4},o.prototype.writeFloatLE=function(t,e,r){return N(this,t,e,!0,r)},o.prototype.writeFloatBE=function(t,e,r){return N(this,t,e,!1,r)},o.prototype.writeDoubleLE=function(t,e,r){return U(this,t,e,!0,r)},o.prototype.writeDoubleBE=function(t,e,r){return U(this,t,e,!1,r)},o.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(a<1e3||!o.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0);var a;if("number"==typeof t)for(a=e;a0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function r(){this.removeListener(t,r),i||(i=!0,e.apply(this,arguments))}if(!n(e))throw TypeError("listener must be a function");var i=!1;return r.listener=e,this.on(t,r),this},r.prototype.removeListener=function(t,e){var r,i,a,s;if(!n(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],a=r.length,i=-1,r===e||n(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(s=a;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){i=s;break}if(i<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],n(r))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){return this._events&&this._events[t]?n(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(n(e))return 1;if(e)return e.length}return 0},r.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,r){"use strict";(function(e){function r(t,r,n,i){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var o,a,s=arguments.length;switch(s){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick(function(){t.call(null,r)});case 3:return e.nextTick(function(){t.call(null,r,n)});case 4:return e.nextTick(function(){t.call(null,r,n,i)});default:for(o=new Array(s-1),a=0;a-1&&t%1==0&&t-1&&t%1==0&&t<=m}function g(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function v(t){return!!t&&"object"==typeof t}function y(t){return f(t)?i(t):a(t)}function b(t){return t}var m=9007199254740991,_="[object Arguments]",w="[object Function]",x="[object GeneratorFunction]",S=/^(?:0|[1-9]\d*)$/,j=Object.prototype,k=j.hasOwnProperty,E=j.toString,A=j.propertyIsEnumerable,T=function(t,e){return function(r){return t(e(r))}}(Object.keys,Object),O=function(t,e){return function(r,n){if(null==r)return r;if(!f(r))return t(r,n);for(var i=r.length,o=e?i:-1,a=Object(r);(e?o--:++o",GT:">",Gt:"≫",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",harrcir:"⥈",harr:"↔",hArr:"⇔",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",hfr:"𝔥",Hfr:"ℌ",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",hopf:"𝕙",Hopf:"ℍ",horbar:"―",HorizontalLine:"─",hscr:"𝒽",Hscr:"ℋ",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"Í",iacute:"í",ic:"⁣",Icirc:"Î",icirc:"î",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",ifr:"𝔦",Ifr:"ℑ",Igrave:"Ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",Im:"ℑ",imof:"⊷",imped:"Ƶ",Implies:"⇒",incare:"℅",in:"∈",infin:"∞",infintie:"⧝",inodot:"ı",intcal:"⊺",int:"∫",Int:"∬",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"⁣",InvisibleTimes:"⁢",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"𝕀",iopf:"𝕚",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",iscr:"𝒾",Iscr:"ℐ",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"Ï",iuml:"ï",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"𝔍",jfr:"𝔧",jmath:"ȷ",Jopf:"𝕁",jopf:"𝕛",Jscr:"𝒥",jscr:"𝒿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"𝔎",kfr:"𝔨",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"𝕂",kopf:"𝕜",Kscr:"𝒦",kscr:"𝓀",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",lang:"⟨",Lang:"⟪",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"«",larrb:"⇤",larrbfs:"⤟",larr:"←",Larr:"↞",lArr:"⇐",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",latail:"⤙",lAtail:"⤛",lat:"⪫",late:"⪭",lates:"⪭︀",lbarr:"⤌",lBarr:"⤎",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",le:"≤",lE:"≦",LeftAngleBracket:"⟨",LeftArrowBar:"⇤",leftarrow:"←",LeftArrow:"←",Leftarrow:"⇐",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVectorBar:"⥙",LeftDownVector:"⇃",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",leftrightarrow:"↔",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTeeArrow:"↤",LeftTee:"⊣",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangleBar:"⧏",LeftTriangle:"⊲",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVectorBar:"⥘",LeftUpVector:"↿",LeftVectorBar:"⥒",LeftVector:"↼",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",lescc:"⪨",les:"⩽",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"𝔏",lfr:"𝔩",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",llarr:"⇇",ll:"≪",Ll:"⋘",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoustache:"⎰",lmoust:"⎰",lnap:"⪉",lnapprox:"⪉",lne:"⪇",lnE:"≨",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",longleftarrow:"⟵",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftrightarrow:"⟷",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longmapsto:"⟼",longrightarrow:"⟶",LongRightArrow:"⟶",Longrightarrow:"⟹",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"𝕃",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",lscr:"𝓁",Lscr:"ℒ",lsh:"↰",Lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",ltcc:"⪦",ltcir:"⩹",lt:"<",LT:"<",Lt:"≪",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",mfr:"𝔪",mho:"℧",micro:"µ",midast:"*",midcir:"⫰",mid:"∣",middot:"·",minusb:"⊟",minus:"−",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"𝕄",mopf:"𝕞",mp:"∓",mscr:"𝓂",Mscr:"ℳ",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natural:"♮",naturals:"ℕ",natur:"♮",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",nearhk:"⤤",nearr:"↗",neArr:"⇗",nearrow:"↗",ne:"≠",nedot:"≐̸",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:"\n",nexist:"∄",nexists:"∄",Nfr:"𝔑",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nharr:"↮",nhArr:"⇎",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlarr:"↚",nlArr:"⇍",nldr:"‥",nlE:"≦̸",nle:"≰",nleftarrow:"↚",nLeftarrow:"⇍",nleftrightarrow:"↮",nLeftrightarrow:"⇎",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"⁠",NonBreakingSpace:" ",nopf:"𝕟",Nopf:"ℕ",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangleBar:"⧏̸",NotLeftTriangle:"⋪",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangleBar:"⧐̸",NotRightTriangle:"⋫",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",nparallel:"∦",npar:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",nprec:"⊀",npreceq:"⪯̸",npre:"⪯̸",nrarrc:"⤳̸",nrarr:"↛",nrArr:"⇏",nrarrw:"↝̸",nrightarrow:"↛",nRightarrow:"⇏",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"𝒩",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nvdash:"⊬",nvDash:"⊭",nVdash:"⊮",nVDash:"⊯",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwarr:"↖",nwArr:"⇖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",Ocirc:"Ô",ocirc:"ô",ocir:"⊚",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"𝔒",ofr:"𝔬",ogon:"˛",Ograve:"Ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"𝕆",oopf:"𝕠",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",orarr:"↻",Or:"⩔",or:"∨",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"𝒪",oscr:"ℴ",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",otimesas:"⨶",Otimes:"⨷",otimes:"⊗",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",para:"¶",parallel:"∥",par:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"𝔓",pfr:"𝔭",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plus:"+",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"ℌ",pointint:"⨕",popf:"𝕡",Popf:"ℙ",pound:"£",prap:"⪷",Pr:"⪻",pr:"≺",prcue:"≼",precapprox:"⪷",prec:"≺",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",pre:"⪯",prE:"⪳",precsim:"≾",prime:"′",Prime:"″",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportional:"∝",Proportion:"∷",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"𝒫",pscr:"𝓅",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"𝔔",qfr:"𝔮",qint:"⨌",qopf:"𝕢",Qopf:"ℚ",qprime:"⁗",Qscr:"𝒬",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",quot:'"',QUOT:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",rang:"⟩",Rang:"⟫",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarr:"→",Rarr:"↠",rArr:"⇒",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",ratail:"⤚",rAtail:"⤜",ratio:"∶",rationals:"ℚ",rbarr:"⤍",rBarr:"⤏",RBarr:"⤐",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",Re:"ℜ",rect:"▭",reg:"®",REG:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",rfr:"𝔯",Rfr:"ℜ",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrowBar:"⇥",rightarrow:"→",RightArrow:"→",Rightarrow:"⇒",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVectorBar:"⥕",RightDownVector:"⇂",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTeeArrow:"↦",RightTee:"⊢",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangleBar:"⧐",RightTriangle:"⊳",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVectorBar:"⥔",RightUpVector:"↾",RightVectorBar:"⥓",RightVector:"⇀",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoustache:"⎱",rmoust:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",ropf:"𝕣",Ropf:"ℝ",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",rscr:"𝓇",Rscr:"ℛ",rsh:"↱",Rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",scap:"⪸",Scaron:"Š",scaron:"š",Sc:"⪼",sc:"≻",sccue:"≽",sce:"⪰",scE:"⪴",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdotb:"⊡",sdot:"⋅",sdote:"⩦",searhk:"⤥",searr:"↘",seArr:"⇘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"𝔖",sfr:"𝔰",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"­",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",solbar:"⌿",solb:"⧄",sol:"/",Sopf:"𝕊",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",square:"□",Square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squ:"□",squf:"▪",srarr:"→",Sscr:"𝒮",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",sub:"⊂",Sub:"⋐",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",subset:"⊂",Subset:"⋐",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succapprox:"⪸",succ:"≻",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",sum:"∑",Sum:"∑",sung:"♪",sup1:"¹",sup2:"²",sup3:"³",sup:"⊃",Sup:"⋑",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",supset:"⊃",Supset:"⋑",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swarr:"↙",swArr:"⇙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:"\t",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"𝔗",tfr:"𝔱",there4:"∴",therefore:"∴",Therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:"  ",ThinSpace:" ",thinsp:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",tilde:"˜",Tilde:"∼",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",timesbar:"⨱",timesb:"⊠",times:"×",timesd:"⨰",tint:"∭",toea:"⤨",topbot:"⌶",topcir:"⫱",top:"⊤",Topf:"𝕋",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",trade:"™",TRADE:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"𝒯",tscr:"𝓉",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",uarr:"↑",Uarr:"↟",uArr:"⇑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"𝔘",ufr:"𝔲",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"¨",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"𝕌",uopf:"𝕦",UpArrowBar:"⤒",uparrow:"↑",UpArrow:"↑",Uparrow:"⇑",UpArrowDownArrow:"⇅",updownarrow:"↕",UpDownArrow:"↕",Updownarrow:"⇕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",upsi:"υ",Upsi:"ϒ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTeeArrow:"↥",UpTee:"⊥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"𝒰",uscr:"𝓊",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"Ü",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",varr:"↕",vArr:"⇕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",vBar:"⫨",Vbar:"⫫",vBarv:"⫩",Vcy:"В",vcy:"в",vdash:"⊢",vDash:"⊨",Vdash:"⊩",VDash:"⊫",Vdashl:"⫦",veebar:"⊻",vee:"∨",Vee:"⋁",veeeq:"≚",vellip:"⋮",verbar:"|",Verbar:"‖",vert:"|",Vert:"‖",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"𝕍",vopf:"𝕧",vprop:"∝",vrtri:"⊳",Vscr:"𝒱",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",wedge:"∧",Wedge:"⋀",wedgeq:"≙",weierp:"℘",Wfr:"𝔚",wfr:"𝔴",Wopf:"𝕎",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"𝒲",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"𝔛",xfr:"𝔵",xharr:"⟷",xhArr:"⟺",Xi:"Ξ",xi:"ξ",xlarr:"⟵",xlArr:"⟸",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"𝕏",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrarr:"⟶",xrArr:"⟹",Xscr:"𝒳",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",yuml:"ÿ",Yuml:"Ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"​",Zeta:"Ζ",zeta:"ζ",zfr:"𝔷",Zfr:"ℨ",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",zopf:"𝕫",Zopf:"ℤ",Zscr:"𝒵",zscr:"𝓏",zwj:"‍",zwnj:"‌"}},function(t,e){t.exports={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'}},function(t,e,r){e=t.exports=r(36),e.Stream=e,e.Readable=e,e.Writable=r(21),e.Duplex=r(2),e.Transform=r(39),e.PassThrough=r(69)},function(t,e,r){"use strict";(function(e,n,i){function o(t){var e=this;this.next=null,this.entry=null,this.finish=function(){A(e,t)}}function a(t){return q.from(t)}function s(t){return q.isBuffer(t)||t instanceof P}function u(){}function c(t,e){O=O||r(2),t=t||{};var n=e instanceof O;this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var i=t.highWaterMark,a=t.writableHighWaterMark,s=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n&&(a||0===a)?a:s,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var u=!1===t.decodeStrings;this.decodeStrings=!u,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){b(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function l(t){if(O=O||r(2),!(R.call(l,this)||this instanceof O))return new l(t);this._writableState=new c(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),D.call(this)}function f(t,e){var r=new Error("write after end");t.emit("error",r),T.nextTick(e,r)}function h(t,e,r,n){var i=!0,o=!1;return null===r?o=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||e.objectMode||(o=new TypeError("Invalid non-string/buffer chunk")),o&&(t.emit("error",o),T.nextTick(n,o),i=!1),i}function p(t,e,r){return t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=q.from(e,r)),e}function d(t,e,r,n,i,o){if(!r){var a=p(e,n,i);n!==a&&(r=!0,i="buffer",n=a)}var s=e.objectMode?1:n.length;e.length+=s;var u=e.length-1?n:T.nextTick;l.WritableState=c;var C=r(8);C.inherits=r(1);var B={deprecate:r(68)},D=r(37),q=r(15).Buffer,P=i.Uint8Array||function(){},M=r(38);C.inherits(l,D),c.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(c.prototype,"buffer",{get:B.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}();var R;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(R=Function.prototype[Symbol.hasInstance],Object.defineProperty(l,Symbol.hasInstance,{value:function(t){return!!R.call(this,t)||this===l&&(t&&t._writableState instanceof c)}})):R=function(t){return t instanceof this},l.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},l.prototype.write=function(t,e,r){var n=this._writableState,i=!1,o=!n.objectMode&&s(t);return o&&!q.isBuffer(t)&&(t=a(t)),"function"==typeof e&&(r=e,e=null),o?e="buffer":e||(e=n.defaultEncoding),"function"!=typeof r&&(r=u),n.ended?f(this,r):(o||h(this,n,t,r))&&(n.pendingcb++,i=d(this,n,o,t,e,r)),i},l.prototype.cork=function(){this._writableState.corked++},l.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||w(this,t))},l.prototype.setDefaultEncoding=function(t){if("string"==typeof t&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),l.prototype._write=function(t,e,r){r(new Error("_write() is not implemented"))},l.prototype._writev=null,l.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!==t&&void 0!==t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||E(this,n,r)},Object.defineProperty(l.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),l.prototype.destroy=M.destroy,l.prototype._undestroy=M.undestroy,l.prototype._destroy=function(t,e){this.end(),e(t)}}).call(e,r(7),r(66).setImmediate,r(0))},function(t,e,r){"use strict";function n(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function i(t){var e=n(t);if("string"!=typeof e&&(b.isEncoding===m||!m(t)))throw new Error("Unknown encoding: "+t);return e||t}function o(t){this.encoding=i(t);var e;switch(this.encoding){case"utf16le":this.text=h,this.end=p,e=4;break;case"utf8":this.fillLast=c,e=4;break;case"base64":this.text=d,this.end=g,e=3;break;default:return this.write=v,void(this.end=y)}this.lastNeed=0,this.lastTotal=0,this.lastChar=b.allocUnsafe(e)}function a(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function s(t,e,r){var n=e.length-1;if(n=0?(i>0&&(t.lastNeed=i-1),i):--n=0?(i>0&&(t.lastNeed=i-2),i):--n=0?(i>0&&(2===i?i=0:t.lastNeed=i-3),i):0)}function u(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}function c(t){var e=this.lastTotal-this.lastNeed,r=u(this,t,e);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function l(t,e){var r=s(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function f(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"�":e}function h(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function p(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function d(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function g(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function v(t){return t.toString(this.encoding)}function y(t){return t&&t.length?this.write(t):""}var b=r(15).Buffer,m=b.isEncoding||function(t){switch((t=""+t)&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};e.StringDecoder=o,o.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r",t.children&&(r+=d(t.children,e)),p[t.name]&&!e.xmlMode||(r+="")):r+="/>",r}function o(t){return"<"+t.data+">"}function a(t,e){var r=t.data||"";return!e.decodeEntities||t.parent&&t.parent.name in h||(r=l.encodeXML(r)),r}function s(t){return""}function u(t){return"\x3c!--"+t.data+"--\x3e"}var c=r(77),l=r(78),f={__proto__:null,allowfullscreen:!0,async:!0,autofocus:!0,autoplay:!0,checked:!0,controls:!0,default:!0,defer:!0,disabled:!0,hidden:!0,ismap:!0,loop:!0,multiple:!0,muted:!0,open:!0,readonly:!0,required:!0,reversed:!0,scoped:!0,seamless:!0,selected:!0,typemustmatch:!0},h={__proto__:null,style:!0,script:!0,xmp:!0,iframe:!0,noembed:!0,noframes:!0,plaintext:!0,noscript:!0},p={__proto__:null,area:!0,base:!0,basefont:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,isindex:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},d=t.exports=function(t,e){Array.isArray(t)||t.cheerio||(t=[t]),e=e||{};for(var r="",n=0;n-1}function o(t,e,r,n){for(var i=t.length,o=r+(n?1:-1);n?o--:++o1&&E.reverse(),p&&c1?"& ":"")+e[n],e=e.join(r>2?", ":" "),t.replace(ct,"{\n/* [wrapped with "+e+"] */\n")}function T(t,e){return!!(e=null==e?tt:e)&&("number"==typeof t||vt.test(t))&&t>-1&&t%1==0&&t2?t:void 0}(),Dt=Bt?function(t,e,r){var n=e+"";return Bt(t,"toString",{configurable:!0,enumerable:!1,value:U(A(n,B(E(n),r)))})}:F,qt=function(t,e){return e=Lt(void 0===e?t.length-1:e,0),function(){for(var n=arguments,i=-1,o=Lt(n.length-e,0),a=Array(o);++i1&&"scope"!==e)throw new SyntaxError("pseudo-selector :"+e+" requires an argument")}else if(1===t.length)throw new SyntaxError("pseudo-selector :"+e+" doesn't have any arguments")}var s=r(4),u=s.isTag,c=s.getText,l=s.getParent,f=s.getChildren,h=s.getSiblings,p=s.hasAttrib,d=s.getName,g=s.getAttributeValue,v=r(88),y=r(43).rules.equals,b=r(10),m=b.trueFunc,_=b.falseFunc,w={contains:function(t,e){return function(r){return t(r)&&c(r).indexOf(e)>=0}},icontains:function(t,e){var r=e.toLowerCase();return function(e){return t(e)&&c(e).toLowerCase().indexOf(r)>=0}},"nth-child":function(t,e){var r=v(e);return r===_?r:r===m?o(t):function(e){for(var n=h(e),i=0,o=0;i=0;o--)if(u(n[o])){if(n[o]===e)break;i++}return r(i)&&t(e)}},"nth-of-type":function(t,e){var r=v(e);return r===_?r:r===m?o(t):function(e){for(var n=h(e),i=0,o=0;o=0;o--)if(u(n[o])){if(n[o]===e)break;d(n[o])===d(e)&&i++}return r(i)&&t(e)}},root:function(t){return function(e){return!l(e)&&t(e)}},scope:function(t,e,r,n){return n&&0!==n.length?1===n.length?function(e){return n[0]===e&&t(e)}:function(e){return n.indexOf(e)>=0&&t(e)}:w.root(t)},checkbox:i("type","checkbox"),file:i("type","file"),password:i("type","password"),radio:i("type","radio"),reset:i("type","reset"),image:i("type","image"),submit:i("type","submit")},x={empty:function(t){return!f(t).some(function(t){return u(t)||"text"===t.type})},"first-child":function(t){return n(h(t))===t},"last-child":function(t){for(var e=h(t),r=e.length-1;r>=0;r--){if(e[r]===t)return!0;if(u(e[r]))break}return!1},"first-of-type":function(t){for(var e=h(t),r=0;r=0;r--)if(u(e[r])){if(e[r]===t)return!0;if(d(e[r])===d(t))break}return!1},"only-of-type":function(t){for(var e=h(t),r=0,n=e.length;r=0;a--)(e.fontFaces&&"font-face"===i[a].type||e.mediaQueries&&"media"===i[a].type)&&o.unshift(n.stringify({stylesheet:{rules:[i[a]]}},{comments:!1,indentation:" "})),i[a].position.start;return 0!==o.length&&"\n"+o.join("\n")+"\n"},e.normalizeLineEndings=function(t){return t.replace(/\r\n/g,"\n").replace(/\n/g,"\r\n")},e.compareFunc=function(t,e){for(var r=Math.min(t.length,e.length),n=0;ne[n]?1:-1;return t.length-e.length},e.compare=function(t,r){return 1==e.compareFunc(t,r)?t:r},e.extend=function(t,e){for(var r in e)i.call(e,r)&&(t[r]=e[r]);return t},e.getDefaultOptions=function(t){var r=e.extend({extraCss:"",insertPreservedExtraCss:!0,applyStyleTags:!0,removeStyleTags:!0,preserveMediaQueries:!0,preserveFontFaces:!0,applyWidthAttributes:!0,applyHeightAttributes:!0,applyAttributesTableElements:!0,url:""},t);return r.webResources=r.webResources||{},r}},function(t,e,r){(function(r){function n(t){return i.bind(null,t)}function i(t){var e=[].slice.call(arguments,1);e.unshift("["+t+"]"),r.stderr.write(e.join(" ")+"\n")}e=t.exports=n}).call(e,r(7))},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e,r){function n(t,e){this._options=e||{},this._cbs=t||{},this._tagname="",this._attribname="",this._attribvalue="",this._attribs=null,this._stack=[],this.startIndex=0,this.endIndex=null,this._lowerCaseTagNames="lowerCaseTags"in this._options?!!this._options.lowerCaseTags:!this._options.xmlMode,this._lowerCaseAttributeNames="lowerCaseAttributeNames"in this._options?!!this._options.lowerCaseAttributeNames:!this._options.xmlMode,this._options.Tokenizer&&(i=this._options.Tokenizer),this._tokenizer=new i(this._options,this),this._cbs.onparserinit&&this._cbs.onparserinit(this)}var i=r(31),o={input:!0,option:!0,optgroup:!0,select:!0,button:!0,datalist:!0,textarea:!0},a={tr:{tr:!0,th:!0,td:!0},th:{th:!0},td:{thead:!0,th:!0,td:!0},body:{head:!0,link:!0,script:!0},li:{li:!0},p:{p:!0},h1:{p:!0},h2:{p:!0},h3:{p:!0},h4:{p:!0},h5:{p:!0},h6:{p:!0},select:o,input:o,output:o,button:o,datalist:o,textarea:o,option:{option:!0},optgroup:{optgroup:!0}},s={__proto__:null,area:!0,base:!0,basefont:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,isindex:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,path:!0,circle:!0,ellipse:!0,line:!0,rect:!0,use:!0,stop:!0,polyline:!0,polygon:!0},u=/\s|\//;r(1)(n,r(13).EventEmitter),n.prototype._updatePosition=function(t){null===this.endIndex?this._tokenizer._sectionStart<=t?this.startIndex=0:this.startIndex=this._tokenizer._sectionStart-t:this.startIndex=this.endIndex+1,this.endIndex=this._tokenizer.getAbsoluteIndex()},n.prototype.ontext=function(t){this._updatePosition(1),this.endIndex--,this._cbs.ontext&&this._cbs.ontext(t)},n.prototype.onopentagname=function(t){if(this._lowerCaseTagNames&&(t=t.toLowerCase()),this._tagname=t,!this._options.xmlMode&&t in a)for(var e;(e=this._stack[this._stack.length-1])in a[t];this.onclosetag(e));!this._options.xmlMode&&t in s||this._stack.push(t),this._cbs.onopentagname&&this._cbs.onopentagname(t),this._cbs.onopentag&&(this._attribs={})},n.prototype.onopentagend=function(){this._updatePosition(1),this._attribs&&(this._cbs.onopentag&&this._cbs.onopentag(this._tagname,this._attribs),this._attribs=null),!this._options.xmlMode&&this._cbs.onclosetag&&this._tagname in s&&this._cbs.onclosetag(this._tagname),this._tagname=""},n.prototype.onclosetag=function(t){if(this._updatePosition(1),this._lowerCaseTagNames&&(t=t.toLowerCase()),!this._stack.length||t in s&&!this._options.xmlMode)this._options.xmlMode||"br"!==t&&"p"!==t||(this.onopentagname(t),this._closeCurrentTag());else{var e=this._stack.lastIndexOf(t);if(-1!==e)if(this._cbs.onclosetag)for(e=this._stack.length-e;e--;)this._cbs.onclosetag(this._stack.pop());else this._stack.length=e;else"p"!==t||this._options.xmlMode||(this.onopentagname(t),this._closeCurrentTag())}},n.prototype.onselfclosingtag=function(){this._options.xmlMode||this._options.recognizeSelfClosing?this._closeCurrentTag():this.onopentagend()},n.prototype._closeCurrentTag=function(){var t=this._tagname;this.onopentagend(),this._stack[this._stack.length-1]===t&&(this._cbs.onclosetag&&this._cbs.onclosetag(t),this._stack.pop())},n.prototype.onattribname=function(t){this._lowerCaseAttributeNames&&(t=t.toLowerCase()),this._attribname=t},n.prototype.onattribdata=function(t){this._attribvalue+=t},n.prototype.onattribend=function(){this._cbs.onattribute&&this._cbs.onattribute(this._attribname,this._attribvalue),this._attribs&&!Object.prototype.hasOwnProperty.call(this._attribs,this._attribname)&&(this._attribs[this._attribname]=this._attribvalue),this._attribname="",this._attribvalue=""},n.prototype._getInstructionName=function(t){var e=t.search(u),r=e<0?t:t.substr(0,e);return this._lowerCaseTagNames&&(r=r.toLowerCase()),r},n.prototype.ondeclaration=function(t){if(this._cbs.onprocessinginstruction){var e=this._getInstructionName(t);this._cbs.onprocessinginstruction("!"+e,"!"+t)}},n.prototype.onprocessinginstruction=function(t){if(this._cbs.onprocessinginstruction){var e=this._getInstructionName(t);this._cbs.onprocessinginstruction("?"+e,"?"+t)}},n.prototype.oncomment=function(t){this._updatePosition(4),this._cbs.oncomment&&this._cbs.oncomment(t),this._cbs.oncommentend&&this._cbs.oncommentend()},n.prototype.oncdata=function(t){this._updatePosition(1),this._options.xmlMode||this._options.recognizeCDATA?(this._cbs.oncdatastart&&this._cbs.oncdatastart(),this._cbs.ontext&&this._cbs.ontext(t),this._cbs.oncdataend&&this._cbs.oncdataend()):this.oncomment("[CDATA["+t+"]]")},n.prototype.onerror=function(t){this._cbs.onerror&&this._cbs.onerror(t)},n.prototype.onend=function(){if(this._cbs.onclosetag)for(var t=this._stack.length;t>0;this._cbs.onclosetag(this._stack[--t]));this._cbs.onend&&this._cbs.onend()},n.prototype.reset=function(){this._cbs.onreset&&this._cbs.onreset(),this._tokenizer.reset(),this._tagname="",this._attribname="",this._attribs=null,this._stack=[],this._cbs.onparserinit&&this._cbs.onparserinit(this)},n.prototype.parseComplete=function(t){this.reset(),this.end(t)},n.prototype.write=function(t){this._tokenizer.write(t)},n.prototype.end=function(t){this._tokenizer.end(t)},n.prototype.pause=function(){this._tokenizer.pause()},n.prototype.resume=function(){this._tokenizer.resume()},n.prototype.parseChunk=n.prototype.write,n.prototype.done=n.prototype.end,t.exports=n},function(t,e,r){function n(t){return" "===t||"\n"===t||"\t"===t||"\f"===t||"\r"===t}function i(t,e,r){var n=t.toLowerCase();return t===n?function(t){t===n?this._state=e:(this._state=r,this._index--)}:function(i){i===n||i===t?this._state=e:(this._state=r,this._index--)}}function o(t,e){var r=t.toLowerCase();return function(n){n===r||n===t?this._state=e:(this._state=d,this._index--)}}function a(t,e){this._state=h,this._buffer="",this._sectionStart=0,this._index=0,this._bufferOffset=0,this._baseState=h,this._special=dt,this._cbs=e,this._running=!0,this._ended=!1,this._xmlMode=!(!t||!t.xmlMode),this._decodeEntities=!(!t||!t.decodeEntities)}t.exports=a;var s=r(32),u=r(18),c=r(33),l=r(19),f=0,h=f++,p=f++,d=f++,g=f++,v=f++,y=f++,b=f++,m=f++,_=f++,w=f++,x=f++,S=f++,j=f++,k=f++,E=f++,A=f++,T=f++,O=f++,L=f++,C=f++,B=f++,D=f++,q=f++,P=f++,M=f++,R=f++,I=f++,N=f++,U=f++,F=f++,z=f++,V=f++,$=f++,H=f++,W=f++,G=f++,Y=f++,J=f++,Q=f++,X=f++,Z=f++,K=f++,tt=f++,et=f++,rt=f++,nt=f++,it=f++,ot=f++,at=f++,st=f++,ut=f++,ct=f++,lt=f++,ft=f++,ht=f++,pt=0,dt=pt++,gt=pt++,vt=pt++;a.prototype._stateText=function(t){"<"===t?(this._index>this._sectionStart&&this._cbs.ontext(this._getSection()),this._state=p,this._sectionStart=this._index):this._decodeEntities&&this._special===dt&&"&"===t&&(this._index>this._sectionStart&&this._cbs.ontext(this._getSection()),this._baseState=h,this._state=ut,this._sectionStart=this._index)},a.prototype._stateBeforeTagName=function(t){"/"===t?this._state=v:"<"===t?(this._cbs.ontext(this._getSection()),this._sectionStart=this._index):">"===t||this._special!==dt||n(t)?this._state=h:"!"===t?(this._state=E,this._sectionStart=this._index+1):"?"===t?(this._state=T,this._sectionStart=this._index+1):(this._state=this._xmlMode||"s"!==t&&"S"!==t?d:z,this._sectionStart=this._index)},a.prototype._stateInTagName=function(t){("/"===t||">"===t||n(t))&&(this._emitToken("onopentagname"),this._state=m,this._index--)},a.prototype._stateBeforeCloseingTagName=function(t){n(t)||(">"===t?this._state=h:this._special!==dt?"s"===t||"S"===t?this._state=V:(this._state=h,this._index--):(this._state=y,this._sectionStart=this._index))},a.prototype._stateInCloseingTagName=function(t){(">"===t||n(t))&&(this._emitToken("onclosetag"),this._state=b,this._index--)},a.prototype._stateAfterCloseingTagName=function(t){">"===t&&(this._state=h,this._sectionStart=this._index+1)},a.prototype._stateBeforeAttributeName=function(t){">"===t?(this._cbs.onopentagend(),this._state=h,this._sectionStart=this._index+1):"/"===t?this._state=g:n(t)||(this._state=_,this._sectionStart=this._index)},a.prototype._stateInSelfClosingTag=function(t){">"===t?(this._cbs.onselfclosingtag(),this._state=h,this._sectionStart=this._index+1):n(t)||(this._state=m,this._index--)},a.prototype._stateInAttributeName=function(t){("="===t||"/"===t||">"===t||n(t))&&(this._cbs.onattribname(this._getSection()),this._sectionStart=-1,this._state=w,this._index--)},a.prototype._stateAfterAttributeName=function(t){"="===t?this._state=x:"/"===t||">"===t?(this._cbs.onattribend(),this._state=m,this._index--):n(t)||(this._cbs.onattribend(),this._state=_,this._sectionStart=this._index)},a.prototype._stateBeforeAttributeValue=function(t){'"'===t?(this._state=S,this._sectionStart=this._index+1):"'"===t?(this._state=j,this._sectionStart=this._index+1):n(t)||(this._state=k,this._sectionStart=this._index,this._index--)},a.prototype._stateInAttributeValueDoubleQuotes=function(t){'"'===t?(this._emitToken("onattribdata"),this._cbs.onattribend(),this._state=m):this._decodeEntities&&"&"===t&&(this._emitToken("onattribdata"),this._baseState=this._state,this._state=ut,this._sectionStart=this._index)},a.prototype._stateInAttributeValueSingleQuotes=function(t){"'"===t?(this._emitToken("onattribdata"),this._cbs.onattribend(),this._state=m):this._decodeEntities&&"&"===t&&(this._emitToken("onattribdata"),this._baseState=this._state,this._state=ut,this._sectionStart=this._index)},a.prototype._stateInAttributeValueNoQuotes=function(t){n(t)||">"===t?(this._emitToken("onattribdata"),this._cbs.onattribend(),this._state=m,this._index--):this._decodeEntities&&"&"===t&&(this._emitToken("onattribdata"),this._baseState=this._state,this._state=ut,this._sectionStart=this._index)},a.prototype._stateBeforeDeclaration=function(t){this._state="["===t?D:"-"===t?O:A},a.prototype._stateInDeclaration=function(t){">"===t&&(this._cbs.ondeclaration(this._getSection()),this._state=h,this._sectionStart=this._index+1)},a.prototype._stateInProcessingInstruction=function(t){">"===t&&(this._cbs.onprocessinginstruction(this._getSection()),this._state=h,this._sectionStart=this._index+1)},a.prototype._stateBeforeComment=function(t){"-"===t?(this._state=L,this._sectionStart=this._index+1):this._state=A},a.prototype._stateInComment=function(t){"-"===t&&(this._state=C)},a.prototype._stateAfterComment1=function(t){this._state="-"===t?B:L},a.prototype._stateAfterComment2=function(t){">"===t?(this._cbs.oncomment(this._buffer.substring(this._sectionStart,this._index-2)),this._state=h,this._sectionStart=this._index+1):"-"!==t&&(this._state=L)},a.prototype._stateBeforeCdata1=i("C",q,A),a.prototype._stateBeforeCdata2=i("D",P,A),a.prototype._stateBeforeCdata3=i("A",M,A),a.prototype._stateBeforeCdata4=i("T",R,A),a.prototype._stateBeforeCdata5=i("A",I,A),a.prototype._stateBeforeCdata6=function(t){"["===t?(this._state=N,this._sectionStart=this._index+1):(this._state=A,this._index--)},a.prototype._stateInCdata=function(t){"]"===t&&(this._state=U)},a.prototype._stateAfterCdata1=function(t,e){return function(r){r===t&&(this._state=e)}}("]",F),a.prototype._stateAfterCdata2=function(t){">"===t?(this._cbs.oncdata(this._buffer.substring(this._sectionStart,this._index-2)),this._state=h,this._sectionStart=this._index+1):"]"!==t&&(this._state=N)},a.prototype._stateBeforeSpecial=function(t){"c"===t||"C"===t?this._state=$:"t"===t||"T"===t?this._state=tt:(this._state=d,this._index--)},a.prototype._stateBeforeSpecialEnd=function(t){this._special!==gt||"c"!==t&&"C"!==t?this._special!==vt||"t"!==t&&"T"!==t?this._state=h:this._state=it:this._state=J},a.prototype._stateBeforeScript1=o("R",H),a.prototype._stateBeforeScript2=o("I",W),a.prototype._stateBeforeScript3=o("P",G),a.prototype._stateBeforeScript4=o("T",Y),a.prototype._stateBeforeScript5=function(t){("/"===t||">"===t||n(t))&&(this._special=gt),this._state=d,this._index--},a.prototype._stateAfterScript1=i("R",Q,h),a.prototype._stateAfterScript2=i("I",X,h),a.prototype._stateAfterScript3=i("P",Z,h),a.prototype._stateAfterScript4=i("T",K,h),a.prototype._stateAfterScript5=function(t){">"===t||n(t)?(this._special=dt,this._state=y,this._sectionStart=this._index-6,this._index--):this._state=h},a.prototype._stateBeforeStyle1=o("Y",et),a.prototype._stateBeforeStyle2=o("L",rt),a.prototype._stateBeforeStyle3=o("E",nt),a.prototype._stateBeforeStyle4=function(t){("/"===t||">"===t||n(t))&&(this._special=vt),this._state=d,this._index--},a.prototype._stateAfterStyle1=i("Y",ot,h),a.prototype._stateAfterStyle2=i("L",at,h),a.prototype._stateAfterStyle3=i("E",st,h),a.prototype._stateAfterStyle4=function(t){">"===t||n(t)?(this._special=dt,this._state=y,this._sectionStart=this._index-5,this._index--):this._state=h},a.prototype._stateBeforeEntity=i("#",ct,lt),a.prototype._stateBeforeNumericEntity=i("X",ht,ft),a.prototype._parseNamedEntityStrict=function(){if(this._sectionStart+16&&(e=6);e>=2;){var r=this._buffer.substr(t,e);if(c.hasOwnProperty(r))return this._emitPartial(c[r]),void(this._sectionStart+=e+1);e--}},a.prototype._stateInNamedEntity=function(t){";"===t?(this._parseNamedEntityStrict(),this._sectionStart+1"z")&&(t<"A"||t>"Z")&&(t<"0"||t>"9")&&(this._xmlMode||this._sectionStart+1===this._index||(this._baseState!==h?"="!==t&&this._parseNamedEntityStrict():this._parseLegacyEntity()),this._state=this._baseState,this._index--)},a.prototype._decodeNumericEntity=function(t,e){var r=this._sectionStart+t;if(r!==this._index){var n=this._buffer.substring(r,this._index),i=parseInt(n,e);this._emitPartial(s(i)),this._sectionStart=this._index}else this._sectionStart--;this._state=this._baseState},a.prototype._stateInNumericEntity=function(t){";"===t?(this._decodeNumericEntity(2,10),this._sectionStart++):(t<"0"||t>"9")&&(this._xmlMode?this._state=this._baseState:this._decodeNumericEntity(2,10),this._index--)},a.prototype._stateInHexEntity=function(t){";"===t?(this._decodeNumericEntity(3,16),this._sectionStart++):(t<"a"||t>"f")&&(t<"A"||t>"F")&&(t<"0"||t>"9")&&(this._xmlMode?this._state=this._baseState:this._decodeNumericEntity(3,16),this._index--)},a.prototype._cleanup=function(){this._sectionStart<0?(this._buffer="",this._bufferOffset+=this._index,this._index=0):this._running&&(this._state===h?(this._sectionStart!==this._index&&this._cbs.ontext(this._buffer.substr(this._sectionStart)),this._buffer="",this._bufferOffset+=this._index,this._index=0):this._sectionStart===this._index?(this._buffer="",this._bufferOffset+=this._index,this._index=0):(this._buffer=this._buffer.substr(this._sectionStart),this._index-=this._sectionStart,this._bufferOffset+=this._sectionStart),this._sectionStart=0)},a.prototype.write=function(t){this._ended&&this._cbs.onerror(Error(".write() after done!")),this._buffer+=t,this._parse()},a.prototype._parse=function(){for(;this._index=55296&&t<=57343||t>1114111)return"�";t in i&&(t=i[t]);var e="";return t>65535&&(t-=65536,e+=String.fromCharCode(t>>>10&1023|55296),t=56320|1023&t),e+=String.fromCharCode(t)}var i=r(57);t.exports=n},function(t,e){t.exports={Aacute:"Á",aacute:"á",Acirc:"Â",acirc:"â",acute:"´",AElig:"Æ",aelig:"æ",Agrave:"À",agrave:"à",amp:"&",AMP:"&",Aring:"Å",aring:"å",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",brvbar:"¦",Ccedil:"Ç",ccedil:"ç",cedil:"¸",cent:"¢",copy:"©",COPY:"©",curren:"¤",deg:"°",divide:"÷",Eacute:"É",eacute:"é",Ecirc:"Ê",ecirc:"ê",Egrave:"È",egrave:"è",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",frac12:"½",frac14:"¼",frac34:"¾",gt:">",GT:">",Iacute:"Í",iacute:"í",Icirc:"Î",icirc:"î",iexcl:"¡",Igrave:"Ì",igrave:"ì",iquest:"¿",Iuml:"Ï",iuml:"ï",laquo:"«",lt:"<",LT:"<",macr:"¯",micro:"µ",middot:"·",nbsp:" ",not:"¬",Ntilde:"Ñ",ntilde:"ñ",Oacute:"Ó",oacute:"ó",Ocirc:"Ô",ocirc:"ô",Ograve:"Ò",ograve:"ò",ordf:"ª",ordm:"º",Oslash:"Ø",oslash:"ø",Otilde:"Õ",otilde:"õ",Ouml:"Ö",ouml:"ö",para:"¶",plusmn:"±",pound:"£",quot:'"',QUOT:'"',raquo:"»",reg:"®",REG:"®",sect:"§",shy:"­",sup1:"¹",sup2:"²",sup3:"³",szlig:"ß",THORN:"Þ",thorn:"þ",times:"×",Uacute:"Ú",uacute:"ú",Ucirc:"Û",ucirc:"û",Ugrave:"Ù",ugrave:"ù",uml:"¨",Uuml:"Ü",uuml:"ü",Yacute:"Ý",yacute:"ý",yen:"¥",yuml:"ÿ"}},function(t,e){var r=t.exports={get firstChild(){var t=this.children;return t&&t[0]||null},get lastChild(){var t=this.children;return t&&t[t.length-1]||null},get nodeType(){return i[this.type]||i.element}},n={tagName:"name",childNodes:"children",parentNode:"parent",previousSibling:"prev",nextSibling:"next",nodeValue:"data"},i={element:1,text:3,cdata:4,comment:8};Object.keys(n).forEach(function(t){var e=n[t];Object.defineProperty(r,t,{get:function(){return this[e]||null},set:function(t){return this[e]=t,t}})})},function(t,e,r){function n(t,e){var r=this._parser=new i(t,e),n=this._decoder=new a;o.call(this,{decodeStrings:!1}),this.once("finish",function(){r.end(n.end())})}t.exports=n;var i=r(30),o=r(62).Writable||r(74).Writable,a=r(22).StringDecoder,s=r(12).Buffer;r(1)(n,o),o.prototype._write=function(t,e,r){t instanceof s&&(t=this._decoder.write(t)),this._parser.write(t),r()}},function(t,e,r){"use strict";(function(e,n){function i(t){return R.from(t)}function o(t){return R.isBuffer(t)||t instanceof I}function a(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?q(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}function s(t,e){D=D||r(2),t=t||{};var n=e instanceof D;this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var i=t.highWaterMark,o=t.readableHighWaterMark,a=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n&&(o||0===o)?o:a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new V,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(z||(z=r(22).StringDecoder),this.decoder=new z(t.encoding),this.encoding=t.encoding)}function u(t){if(D=D||r(2),!(this instanceof u))return new u(t);this._readableState=new s(t,this),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),M.call(this)}function c(t,e,r,n,o){var a=t._readableState;if(null===e)a.reading=!1,g(t,a);else{var s;o||(s=f(a,e)),s?t.emit("error",s):a.objectMode||e&&e.length>0?("string"==typeof e||a.objectMode||Object.getPrototypeOf(e)===R.prototype||(e=i(e)),n?a.endEmitted?t.emit("error",new Error("stream.unshift() after end event")):l(t,a,e,!0):a.ended?t.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!r?(e=a.decoder.write(e),a.objectMode||0!==e.length?l(t,a,e,!1):b(t,a)):l(t,a,e,!1))):n||(a.reading=!1)}return h(a)}function l(t,e,r,n){e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,n?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&v(t)),b(t,e)}function f(t,e){var r;return o(e)||"string"==typeof e||void 0===e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function h(t){return!t.ended&&(t.needReadable||t.length=W?t=W:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function d(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=p(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function g(t,e){if(!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,v(t)}}function v(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(F("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?B.nextTick(y,t):y(t))}function y(t){F("emit readable"),t.emit("readable"),j(t)}function b(t,e){e.readingMore||(e.readingMore=!0,B.nextTick(m,t,e))}function m(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=E(t,e.buffer,e.decoder),r}function E(t,e,r){var n;return to.length?o.length:t;if(a===o.length?i+=o:i+=o.slice(0,t),0===(t-=a)){a===o.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(a));break}++n}return e.length-=n,i}function T(t,e){var r=R.allocUnsafe(t),n=e.head,i=1;for(n.data.copy(r),t-=n.data.length;n=n.next;){var o=n.data,a=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,a),0===(t-=a)){a===o.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=o.slice(a));break}++i}return e.length-=i,r}function O(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,B.nextTick(L,e,t))}function L(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function C(t,e){for(var r=0,n=t.length;r=e.highWaterMark||e.ended))return F("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?O(this):v(this),null;if(0===(t=d(t,e))&&e.ended)return 0===e.length&&O(this),null;var n=e.needReadable;F("need readable",n),(0===e.length||e.length-t0?k(t,e):null,null===i?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&O(this)),null!==i&&this.emit("data",i),i},u.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},u.prototype.pipe=function(t,e){function r(t,e){F("onunpipe"),t===h&&e&&!1===e.hasUnpiped&&(e.hasUnpiped=!0,o())}function i(){F("onend"),t.end()}function o(){F("cleanup"),t.removeListener("close",c),t.removeListener("finish",l),t.removeListener("drain",v),t.removeListener("error",u),t.removeListener("unpipe",r),h.removeListener("end",i),h.removeListener("end",f),h.removeListener("data",s),y=!0,!p.awaitDrain||t._writableState&&!t._writableState.needDrain||v()}function s(e){F("ondata"),b=!1,!1!==t.write(e)||b||((1===p.pipesCount&&p.pipes===t||p.pipesCount>1&&-1!==C(p.pipes,t))&&!y&&(F("false write response, pause",h._readableState.awaitDrain),h._readableState.awaitDrain++,b=!0),h.pause())}function u(e){F("onerror",e),f(),t.removeListener("error",u),0===P(t,"error")&&t.emit("error",e)}function c(){t.removeListener("finish",l),f()}function l(){F("onfinish"),t.removeListener("close",c),f()}function f(){F("unpipe"),h.unpipe(t)}var h=this,p=this._readableState;switch(p.pipesCount){case 0:p.pipes=t;break;case 1:p.pipes=[p.pipes,t];break;default:p.pipes.push(t)}p.pipesCount+=1,F("pipe count=%d opts=%j",p.pipesCount,e);var d=(!e||!1!==e.end)&&t!==n.stdout&&t!==n.stderr,g=d?i:f;p.endEmitted?B.nextTick(g):h.once("end",g),t.on("unpipe",r);var v=_(h);t.on("drain",v);var y=!1,b=!1;return h.on("data",s),a(t,"error",u),t.once("close",c),t.once("finish",l),t.emit("pipe",h),p.flowing||(F("pipe resume"),h.resume()),t},u.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o-1&&t%1==0&&t-1&&t%1==0&&t<=x}function m(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function _(t){return!!t&&"object"==typeof t}function w(t){return g(t)?i(t,!0):a(t)}var x=9007199254740991,S="[object Arguments]",j="[object Function]",k="[object GeneratorFunction]",E=/^(?:0|[1-9]\d*)$/,A=Object.prototype,T=A.hasOwnProperty,O=A.toString,L=A.propertyIsEnumerable,C=Math.max,B=Array.isArray,D=function(t){return s(function(e,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=t.length>3&&"function"==typeof o?(i--,o):void 0,a&&l(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),e=Object(e);++n-1&&t%1==0&&t-1&&t%1==0&&t<=S}function _(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function w(t){return!!t&&"object"==typeof t}function x(t){return v(t)?i(t,!0):s(t)}var S=9007199254740991,j="[object Arguments]",k="[object Function]",E="[object GeneratorFunction]",A=/^(?:0|[1-9]\d*)$/,T=Object.prototype,O=T.hasOwnProperty,L=T.toString,C=T.propertyIsEnumerable,B=Math.max,D=Array.isArray,q=function(t){return u(function(e,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=t.length>3&&"function"==typeof o?(i--,o):void 0,a&&f(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),e=Object(e);++n=0&&t(e)}},not:function(t,e){var r=e.name,n=e.value;return""===n?function(e){return!!o(e,r)&&t(e)}:e.ignoreCase?(n=n.toLowerCase(),function(e){var i=o(e,r);return null!=i&&i.toLowerCase()!==n&&t(e)}):function(e){return o(e,r)!==n&&t(e)}}};t.exports={compile:function(t,e,r){if(r&&r.strict&&(e.ignoreCase||"not"===e.action))throw SyntaxError("Unsupported attribute selector");return u[e.action](t,e)},rules:u}},function(t,e){t.exports={universal:50,tag:30,attribute:1,pseudo:0,descendant:-1,child:-1,parent:-1,sibling:-1,adjacent:-1}},function(t,e,r){function n(t){function e(t){return t?w[w.length-1-t]:_}function r(t){return t===n(1)}function n(e){return t[y+(e||1)]}function s(){var t=w.pop();return _=w[w.length-1],t}function u(t){return _=t,w.push(_),w.length}function c(t){var e=_;return w[w.length-1]=_=t,e}function l(e){if(1==(e||1))"\n"==t[y]?(m++,v=1):v++,y++;else{var r=t.slice(y,y+e).split("\n");r.length>1&&(m+=r.length-1,v=1),v+=r[r.length-1].length,y+=e}}function f(){x.end={line:m,col:v},i&&a("addToken:",JSON.stringify(x,null,2)),S.push(x),g="",x={}}function h(t){x={type:t,start:{line:m,col:v}}}var p,d,g="",v=0,y=-1,b=0,m=1,_="before-selector",w=[_],x={},S=[],j=["media","keyframes",{name:"-webkit-keyframes",type:"keyframes",prefix:"-webkit-"},{name:"-moz-keyframes",type:"keyframes",prefix:"-moz-"},{name:"-ms-keyframes",type:"keyframes",prefix:"-ms-"},{name:"-o-keyframes",type:"keyframes",prefix:"-o-"},"font-face",{name:"import",state:"before-at-value"},{name:"charset",state:"before-at-value"},"supports","viewport",{name:"namespace",state:"before-at-value"},"document",{name:"-moz-document",type:"document",prefix:"-moz-"},"page"];for(o&&(p=Date.now());d=function(){return l(),t[y]}();)switch(i&&a(d,e()),d){case" ":switch(e()){case"selector":case"value":case"value-paren":case"at-group":case"at-value":case"comment":case"double-string":case"single-string":g+=d}break;case"\n":case"\t":case"\r":case"\f":switch(e()){case"value":case"value-paren":case"at-group":case"comment":case"single-string":case"double-string":case"selector":g+=d;break;case"at-value":"\n"===d&&(x.value=g.trim(),f(),s())}break;case":":switch(e()){case"name":x.name=g.trim(),g="",c("before-value");break;case"before-selector":g+=d,h("selector"),u("selector");break;case"before-value":c("value"),g+=d;break;default:g+=d}break;case";":switch(e()){case"name":case"before-value":case"value":g.trim().length>0&&(x.value=g.trim(),f()),c("before-name");break;case"value-paren":g+=d;break;case"at-value":x.value=g.trim(),f(),s();break;case"before-name":break;default:g+=d}break;case"{":switch(e()){case"selector":if("\\"===n(-1)){g+=d;break}x.text=g.trim(),f(),c("before-name"),b+=1;break;case"at-group":switch(x.name=g.trim(),x.type){case"font-face":case"viewport":case"page":u("before-name");break;default:u("before-selector")}f(),b+=1;break;case"name":case"at-rule":x.name=g.trim(),f(),u("before-name"),b+=1;break;case"comment":case"double-string":case"single-string":g+=d;break;case"before-value":c("value"),g+=d}break;case"}":switch(e()){case"before-name":case"name":case"before-value":case"value":g&&(x.value=g.trim()),x.name&&x.value&&f(),h("end"),f(),s(),"at-group"===e()&&(h("at-group-end"),f(),s()),b>0&&(b-=1);break;case"at-group":case"before-selector":case"selector":if("\\"===n(-1)){g+=d;break}b>0&&"at-group"===e(1)&&(h("at-group-end"),f()),b>1&&s(),b>0&&(b-=1);break;case"double-string":case"single-string":case"comment":g+=d}break;case'"':case"'":switch(e()){case"double-string":'"'===d&&"\\"!==n(-1)&&s();break;case"single-string":"'"===d&&"\\"!==n(-1)&&s();break;case"before-at-value":c("at-value"),u('"'===d?"double-string":"single-string");break;case"before-value":c("value"),u('"'===d?"double-string":"single-string");break;case"comment":break;default:"\\"!==n(-1)&&u('"'===d?"double-string":"single-string")}g+=d;break;case"/":switch(e()){case"comment":case"double-string":case"single-string":g+=d;break;case"before-value":case"selector":case"name":case"value":if(r("*")){var k=function(e){var r=t.slice(y).indexOf(e);return r>0&&r}("*/");k&&l(k+1)}else"before-value"==e()&&c("value"),g+=d;break;default:r("*")?(h("comment"),u("comment"),l()):g+=d}break;case"*":switch(e()){case"comment":r("/")?(x.text=g,l(),f(),s()):g+=d;break;case"before-selector":g+=d,h("selector"),u("selector");break;case"before-value":c("value"),g+=d;break;default:g+=d}break;case"@":switch(e()){case"comment":case"double-string":case"single-string":g+=d;break;case"before-value":c("value"),g+=d;break;default:for(var E,A,T=!1,O=0,L=j.length;!T&&O0&&void 0!==arguments[0]?arguments[0]:{},e=t.editor,n=e.Commands,i=r(50),a=r(51);n.add(t.cmdOpenImport,i(t)),n.add(t.cmdTglImages,(0,o.default)(t)),e.on("load",function(){n.add("export-template",a(t))}),n.add("undo",{run:function(t,e){e.set("active",0),t.UndoManager.undo(1)}}),n.add("redo",{run:function(t,e){e.set("active",0),t.UndoManager.redo(1)}}),n.add("set-device-desktop",{run:function(t){t.setDevice("Desktop")}}),n.add("set-device-tablet",{run:function(t){t.setDevice("Tablet")}}),n.add("set-device-mobile",{run:function(t){t.setDevice("Mobile portrait")}})}}.call(e,r,e,t))&&(t.exports=n)},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(){var t=function t(e,r){e.each(function(e){if("image"===e.get("type")){var n=e.get("src");r?"##"===n&&e.set("src",e.get("src_bkp")):"##"!==n&&(e.set("src_bkp",e.get("src")),e.set("src","##"))}t(e.get("components"),r)})};return{run:function(e){var r=e.getComponents();t(r)},stop:function(e){var r=e.getComponents();t(r,1)}}}},function(t,e,r){"use strict";var n;void 0!==(n=function(){return function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.editor,r=e&&e.CodeManager.getViewer("CodeMirror").clone(),n=document.createElement("button"),i=document.createElement("div"),o=t.pfx||"";return n.innerHTML=t.modalBtnImport,n.className=o+"btn-prim "+o+"btn-import",n.onclick=function(){var t=r.editor.getValue();e.DomComponents.getWrapper().set("content",""),e.setComponents(t),e.Modal.close()},r.set({codeName:"htmlmixed",theme:t.codeViewerTheme,readOnly:0}),{run:function(e,a){var s=e.Modal,u=(s.getContentEl(),r.editor);if(s.setTitle(t.modalTitleImport),!u){var c=document.createElement("textarea");if(t.modalLabelImport){var l=document.createElement("div");l.className=o+"import-label",l.innerHTML=t.modalLabelImport,i.appendChild(l)}i.appendChild(c),i.appendChild(n),r.init(c),u=r.editor}s.setContent(""),s.setContent(i),r.setContent(t.importPlaceholder||""),s.open(),u.refresh(),a&&a.set("active",0)}}}}.call(e,r,e,t))&&(t.exports=n)},function(t,e,r){"use strict";var n;void 0!==(n=function(){var t=r(52);return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.editor,n=r&&r.CodeManager.getViewer("CodeMirror").clone(),i=document.createElement("div"),o=e.pfx||"",a=r.Commands,s=e.juiceOpts||{};return n.set({codeName:"htmlmixed",theme:e.codeViewerTheme}),a.add(e.cmdInlineHtml,{run:function(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=e.getHtml()+"";return t(i,n)}}),{run:function(r,a){var u=r.Modal,c=(u.getContentEl(),n.editor);if(u.setTitle(e.modalTitleExport),!c){var l=document.createElement("textarea");if(e.modalLabelExport){var f=document.createElement("div");f.className=o+"export-label",f.innerHTML=e.modalLabelExport,i.appendChild(f)}i.appendChild(l),n.init(l),c=n.editor,c.setOption("lineWrapping",1)}u.setContent(i);var h=r.getHtml()+"";n.setContent(e.inlineCss?t(h,s):h),u.open(),c.refresh(),a&&a.set&&a.set("active",0)}}}}.call(e,r,e,t))&&(t.exports=n)},function(t,e,r){"use strict";var n=r(53),i=r(114),o=i(function(t,e){return n(t,{xmlMode:e&&e.xmlMode},a,[e])}),a=function(t,e){return o.juiceDocument(t,e)};o.inlineContent=function(t,e,r){return n(t,{xmlMode:r&&r.xmlMode},o.inlineDocument,[e,r])},t.exports=o},function(t,e,r){"use strict";var n=r(54),i=r(27),o=function(t,e,r){return e=i.extend({decodeEntities:!1},e||{}),t=r(t),n.load(t,e)},a=function(){var e=[];return{encodeEntities:function(r){var n=t.exports.codeBlocks;return Object.keys(n).forEach(function(t){var i=new RegExp(n[t].start+"([\\S\\s]*?)"+n[t].end,"g");r=r.replace(i,function(t,r){return e.push(t),"JUICE_CODE_BLOCK_"+(e.length-1)+"_"})}),r},decodeEntities:function(t){for(var r=0;r"},HBS:{start:"{{",end:"}}"}}},function(t,e,r){e=t.exports=r(17),e.version=r(107).version},function(t,e,r){"use strict";function n(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function i(t){var e=n(t),r=e[0],i=e[1];return 3*(r+i)/4-i}function o(t,e,r){return 3*(e+r)/4-r}function a(t){for(var e,r=n(t),i=r[0],a=r[1],s=new h(o(t,i,a)),u=0,c=a>0?i-4:i,l=0;l>16&255,s[u++]=e>>8&255,s[u++]=255&e;return 2===a&&(e=f[t.charCodeAt(l)]<<2|f[t.charCodeAt(l+1)]>>4,s[u++]=255&e),1===a&&(e=f[t.charCodeAt(l)]<<10|f[t.charCodeAt(l+1)]<<4|f[t.charCodeAt(l+2)]>>2,s[u++]=e>>8&255,s[u++]=255&e),s}function s(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function u(t,e,r){for(var n,i=[],o=e;oa?a:o+16383));return 1===n?(e=t[r-1],i.push(l[e>>2]+l[e<<4&63]+"==")):2===n&&(e=(t[r-2]<<8)+t[r-1],i.push(l[e>>10]+l[e>>4&63]+l[e<<2&63]+"=")),i.join("")}e.byteLength=i,e.toByteArray=a,e.fromByteArray=c;for(var l=[],f=[],h="undefined"!=typeof Uint8Array?Uint8Array:Array,p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,g=p.length;d>1,l=-7,f=r?i-1:0,h=r?-1:1,p=t[e+f];for(f+=h,o=p&(1<<-l)-1,p>>=-l,l+=s;l>0;o=256*o+t[e+f],f+=h,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=n;l>0;a=256*a+t[e+f],f+=h,l-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,n),o-=c}return(p?-1:1)*a*Math.pow(2,o-n)},e.write=function(t,e,r,n,i,o){var a,s,u,c=8*o-i-1,l=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,a=l):(a=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-a))<1&&(a--,u*=2),e+=a+f>=1?h/u:h*Math.pow(2,1-f),e*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(e*u-1)*Math.pow(2,i),a+=f):(s=e*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;t[r+p]=255&s,p+=d,s/=256,i-=8);for(a=a<0;t[r+p]=255&a,p+=d,a/=256,c-=8);t[r+p-d]|=128*g}},function(t,e){t.exports={0:65533,128:8364,130:8218,131:402,132:8222,133:8230,134:8224,135:8225,136:710,137:8240,138:352,139:8249,140:338,142:381,145:8216,146:8217,147:8220,148:8221,149:8226,150:8211,151:8212,152:732,153:8482,154:353,155:8250,156:339,158:382,159:376}},function(t,e,r){function n(t,e,r){"object"==typeof t?(r=e,e=t,t=null):"function"==typeof e&&(r=e,e=u),this._callback=t,this._options=e||u,this._elementCB=r,this.dom=[],this._done=!1,this._tagStack=[],this._parser=this._parser||null}var i=r(6),o=/\s+/g,a=r(34),s=r(59),u={normalizeWhitespace:!1,withStartIndices:!1,withEndIndices:!1};n.prototype.onparserinit=function(t){this._parser=t},n.prototype.onreset=function(){n.call(this,this._callback,this._options,this._elementCB)},n.prototype.onend=function(){this._done||(this._done=!0,this._parser=null,this._handleCallback(null))},n.prototype._handleCallback=n.prototype.onerror=function(t){if("function"==typeof this._callback)this._callback(t,this.dom);else if(t)throw t},n.prototype.onclosetag=function(){var t=this._tagStack.pop();this._options.withEndIndices&&t&&(t.endIndex=this._parser.endIndex),this._elementCB&&this._elementCB(t)},n.prototype._createDomElement=function(t){if(!this._options.withDomLvl1)return t;var e;e="tag"===t.type?Object.create(s):Object.create(a);for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e},n.prototype._addDomElement=function(t){var e=this._tagStack[this._tagStack.length-1],r=e?e.children:this.dom,n=r[r.length-1];t.next=null,this._options.withStartIndices&&(t.startIndex=this._parser.startIndex),this._options.withEndIndices&&(t.endIndex=this._parser.endIndex),n?(t.prev=n,n.next=t):t.prev=null,r.push(t),t.parent=e||null},n.prototype.onopentag=function(t,e){var r={type:"script"===t?i.Script:"style"===t?i.Style:i.Tag,name:t,attribs:e,children:[]},n=this._createDomElement(r);this._addDomElement(n),this._tagStack.push(n)},n.prototype.ontext=function(t){var e,r=this._options.normalizeWhitespace||this._options.ignoreWhitespace;if(!this._tagStack.length&&this.dom.length&&(e=this.dom[this.dom.length-1]).type===i.Text)r?e.data=(e.data+t).replace(o," "):e.data+=t;else if(this._tagStack.length&&(e=this._tagStack[this._tagStack.length-1])&&(e=e.children[e.children.length-1])&&e.type===i.Text)r?e.data=(e.data+t).replace(o," "):e.data+=t;else{r&&(t=t.replace(o," "));var n=this._createDomElement({data:t,type:i.Text});this._addDomElement(n)}},n.prototype.oncomment=function(t){var e=this._tagStack[this._tagStack.length-1];if(e&&e.type===i.Comment)return void(e.data+=t);var r={data:t,type:i.Comment},n=this._createDomElement(r);this._addDomElement(n),this._tagStack.push(n)},n.prototype.oncdatastart=function(){var t={children:[{data:"",type:i.Text}],type:i.CDATA},e=this._createDomElement(t);this._addDomElement(e),this._tagStack.push(e)},n.prototype.oncommentend=n.prototype.oncdataend=function(){this._tagStack.pop()},n.prototype.onprocessinginstruction=function(t,e){var r=this._createDomElement({name:t,data:e,type:i.Directive});this._addDomElement(r)},t.exports=n},function(t,e,r){var n=r(34),i=t.exports=Object.create(n),o={tagName:"name"};Object.keys(o).forEach(function(t){var e=o[t];Object.defineProperty(i,t,{get:function(){return this[e]||null},set:function(t){return this[e]=t,t}})})},function(t,e,r){function n(t,e){this.init(t,e)}function i(t,e){return l.getElementsByTagName(t,e,!0)}function o(t,e){return l.getElementsByTagName(t,e,!0,1)[0]}function a(t,e,r){return l.getText(l.getElementsByTagName(t,e,r,1)).trim()}function s(t,e,r,n,i){var o=a(r,n,i);o&&(t[e]=o)}var u=r(3),c=u.DomHandler,l=u.DomUtils;r(1)(n,c),n.prototype.init=c;var f=function(t){return"rss"===t||"feed"===t||"rdf:RDF"===t};n.prototype.onend=function(){var t,e,r={},n=o(f,this.dom);n&&("feed"===n.name?(e=n.children,r.type="atom",s(r,"id","id",e),s(r,"title","title",e),(t=o("link",e))&&(t=t.attribs)&&(t=t.href)&&(r.link=t),s(r,"description","subtitle",e),(t=a("updated",e))&&(r.updated=new Date(t)),s(r,"author","email",e,!0),r.items=i("entry",e).map(function(t){var e,r={};return t=t.children,s(r,"id","id",t),s(r,"title","title",t),(e=o("link",t))&&(e=e.attribs)&&(e=e.href)&&(r.link=e),(e=a("summary",t)||a("content",t))&&(r.description=e),(e=a("updated",t))&&(r.pubDate=new Date(e)),r})):(e=o("channel",n.children).children,r.type=n.name.substr(0,3),r.id="",s(r,"title","title",e),s(r,"link","link",e),s(r,"description","description",e),(t=a("lastBuildDate",e))&&(r.updated=new Date(t)),s(r,"author","managingEditor",e,!0),r.items=i("item",n.children).map(function(t){var e,r={};return t=t.children,s(r,"id","guid",t),s(r,"title","title",t),s(r,"link","link",t),s(r,"description","description",t),(e=a("pubDate",t))&&(r.pubDate=new Date(e)),r}))),this.dom=r,c.prototype._handleCallback.call(this,n?null:Error("couldn't find root of feed"))},t.exports=n},function(t,e,r){function n(t){o.call(this,new i(this),t)}function i(t){this.scope=t}t.exports=n;var o=r(35);r(1)(n,o),n.prototype.readable=!0;var a=r(3).EVENTS;Object.keys(a).forEach(function(t){if(0===a[t])i.prototype["on"+t]=function(){this.scope.emit(t)};else if(1===a[t])i.prototype["on"+t]=function(e){this.scope.emit(t,e)};else{if(2!==a[t])throw Error("wrong number of arguments!");i.prototype["on"+t]=function(e,r){this.scope.emit(t,e,r)}}})},function(t,e,r){function n(){i.call(this)}t.exports=n;var i=r(13).EventEmitter;r(1)(n,i),n.Readable=r(20),n.Writable=r(70),n.Duplex=r(71),n.Transform=r(72),n.PassThrough=r(73),n.Stream=n,n.prototype.pipe=function(t,e){function r(e){t.writable&&!1===t.write(e)&&c.pause&&c.pause()}function n(){c.readable&&c.resume&&c.resume()}function o(){l||(l=!0,t.end())}function a(){l||(l=!0,"function"==typeof t.destroy&&t.destroy())}function s(t){if(u(),0===i.listenerCount(this,"error"))throw t}function u(){c.removeListener("data",r),t.removeListener("drain",n),c.removeListener("end",o),c.removeListener("close",a),c.removeListener("error",s),t.removeListener("error",s),c.removeListener("end",u),c.removeListener("close",u),t.removeListener("close",u)}var c=this;c.on("data",r),t.on("drain",n),t._isStdio||e&&!1===e.end||(c.on("end",o),c.on("close",a));var l=!1;return c.on("error",s),t.on("error",s),c.on("end",u),c.on("close",u),t.on("close",u),t.emit("pipe",c),t}},function(t,e){},function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e,r){t.copy(e,r)}var o=r(15).Buffer,a=r(65);t.exports=function(){function t(){n(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},t.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},t.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},t.prototype.clear=function(){this.head=this.tail=null,this.length=0},t.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},t.prototype.concat=function(t){if(0===this.length)return o.alloc(0);if(1===this.length)return this.head.data;for(var e=o.allocUnsafe(t>>>0),r=this.head,n=0;r;)i(r.data,e,n),n+=r.data.length,r=r.next;return e},t}(),a&&a.inspect&&a.inspect.custom&&(t.exports.prototype[a.inspect.custom]=function(){var t=a.inspect({length:this.length});return this.constructor.name+" "+t})},function(t,e){},function(t,e,r){(function(t){function n(t,e){this._id=t,this._clearFn=e}var i=void 0!==t&&t||"undefined"!=typeof self&&self||window,o=Function.prototype.apply;e.setTimeout=function(){return new n(o.call(setTimeout,i,arguments),clearTimeout)},e.setInterval=function(){return new n(o.call(setInterval,i,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},n.prototype.unref=n.prototype.ref=function(){},n.prototype.close=function(){this._clearFn.call(i,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function(){t._onTimeout&&t._onTimeout()},e))},r(67),e.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==t&&t.setImmediate||this&&this.setImmediate,e.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==t&&t.clearImmediate||this&&this.clearImmediate}).call(e,r(0))},function(t,e,r){(function(t,e){!function(t,r){"use strict";function n(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),r=0;r0&&(o=i(t,o,r,n),a=a.concat(o),(n-=o.length)<=0)));s++);return a}function o(t,e){for(var r=0,n=e.length;r0&&(r=a(t,e[n].children)));return r}function s(t,e){for(var r=0,n=e.length;r0&&s(t,e[r].children)))return!0;return!1}function u(t,e){for(var r=[],n=0,i=e.length;n0&&(r=r.concat(u(t,e[n].children))));return r}var c=r(6).isTag;t.exports={filter:n,find:i,findOneChild:o,findOne:a,existsOne:s,findAll:u}},function(t,e,r){function n(t,e){return"function"==typeof e?function(r){return r.attribs&&e(r.attribs[t])}:function(r){return r.attribs&&r.attribs[t]===e}}function i(t,e){return function(r){return t(r)||e(r)}}var o=r(6),a=e.isTag=o.isTag;e.testElement=function(t,e){for(var r in t)if(t.hasOwnProperty(r)){if("tag_name"===r){if(!a(e)||!t.tag_name(e.name))return!1}else if("tag_type"===r){if(!t.tag_type(e.type))return!1}else if("tag_contains"===r){if(a(e)||!t.tag_contains(e.data))return!1}else if(!e.attribs||!t[r](e.attribs[r]))return!1}else;return!0};var s={tag_name:function(t){return"function"==typeof t?function(e){return a(e)&&t(e.name)}:"*"===t?a:function(e){return a(e)&&e.name===t}},tag_type:function(t){return"function"==typeof t?function(e){return t(e.type)}:function(e){return e.type===t}},tag_contains:function(t){return"function"==typeof t?function(e){return!a(e)&&t(e.data)}:function(e){return!a(e)&&e.data===t}}};e.getElements=function(t,e,r,o){var a=Object.keys(t).map(function(e){var r=t[e];return e in s?s[e](r):n(e,r)});return 0===a.length?[]:this.filter(a.reduce(i),e,r,o)},e.getElementById=function(t,e,r){return Array.isArray(e)||(e=[e]),this.findOne(n("id",t),e,!1!==r)},e.getElementsByTagName=function(t,e,r,n){return this.filter(s.tag_name(t),e,r,n)},e.getElementsByTagType=function(t,e,r,n){return this.filter(s.tag_type(t),e,r,n)}},function(t,e){e.removeSubsets=function(t){for(var e,r,n,i=t.length;--i>-1;){for(e=r=t[i],t[i]=null,n=!0;r;){if(t.indexOf(r)>-1){n=!1,t.splice(i,1);break}r=r.parent}n&&(t[i]=e)}return t};var r={DISCONNECTED:1,PRECEDING:2,FOLLOWING:4,CONTAINS:8,CONTAINED_BY:16},n=e.compareDocumentPosition=function(t,e){var n,i,o,a,s,u,c=[],l=[];if(t===e)return 0;for(n=t;n;)c.unshift(n),n=n.parent;for(n=e;n;)l.unshift(n),n=n.parent;for(u=0;c[u]===l[u];)u++;return 0===u?r.DISCONNECTED:(i=c[u-1],o=i.children,a=c[u],s=l[u],o.indexOf(a)>o.indexOf(s)?i===e?r.FOLLOWING|r.CONTAINED_BY:r.FOLLOWING:i===t?r.PRECEDING|r.CONTAINS:r.PRECEDING)};e.uniqueSort=function(t){var e,i,o=t.length;for(t=t.slice();--o>-1;)e=t[o],(i=t.indexOf(e))>-1&&i-1;)if(r=o+t.length,(0===o||l.test(i[o-1]))&&(r===i.length||l.test(i[r])))return!0})},e.addClass=function(t){if("function"==typeof t)return a(this,function(r,n){var i=n.attribs.class||"";e.addClass.call([n],t.call(n,r,i))});if(!t||"string"!=typeof t)return this;for(var r=t.split(l),n=this.length,i=0;i=0&&(u.splice(a,1),s=!0,c--);s&&(e.attribs.class=u.join(" "))}}))},e.toggleClass=function(t,r){if("function"==typeof t)return a(this,function(n,i){e.toggleClass.call([i],t.call(i,n,i.attribs.class||"",r),r)});if(!t||"string"!=typeof t)return this;for(var n,i,s=t.split(l),u=s.length,c="boolean"==typeof r?r?1:-1:0,f=this.length,h=0;h=0&&i<0?n.push(s[p]):c<=0&&i>=0&&n.splice(i,1);this[h].attribs.class=n.join(" ")}return this},e.is=function(t){return!!t&&this.filter(t).length>0}},function(t,e,r){var n=r(89),i=r(90);t.exports=function(t){return i(n(t))},t.exports.parse=n,t.exports.compile=i},function(t,e){function r(t){if("even"===(t=t.trim().toLowerCase()))return[2,0];if("odd"===t)return[2,1];var e=t.match(n);if(!e)throw new SyntaxError("n-th rule couldn't be parsed ('"+t+"')");var r;return e[1]?(r=parseInt(e[1],10),isNaN(r)&&(r="-"===e[1].charAt(0)?-1:1)):r=0,[r,e[3]?parseInt((e[2]||"")+e[3],10):0]}t.exports=r;var n=/^([+\-]?\d*n)?\s*(?:([+\-]?)\s*(\d+))?$/},function(t,e,r){function n(t){var e=t[0],r=t[1]-1;if(r<0&&e<=0)return a;if(-1===e)return function(t){return t<=r};if(0===e)return function(t){return t===r};if(1===e)return r<0?o:function(t){return t>=r};var n=r%e;return n<0&&(n+=e),e>1?function(t){return t>=r&&t%e===n}:(e*=-1,function(t){return t<=r&&t%e===n})}t.exports=n;var i=r(10),o=i.trueFunc,a=i.falseFunc},function(t,e,r){function n(t,e,r){return i(o(t,e,r))}function i(t){return function(e){return g(e)&&t(e)}}function o(t,e,r){return u(p(t,e),e,r)}function a(t){return"pseudo"===t.type&&("scope"===t.name||Array.isArray(t.data)&&t.data.some(function(t){return t.some(a)}))}function s(t,e){var r=!!e&&!!e.length&&e.every(function(t){return t===j||!!k(t)});t.forEach(function(t){if(t.length>0&&c(t[0])&&"descendant"!==t[0].type);else{if(!r||a(t))return;t.unshift(x)}t.unshift(S)})}function u(t,e,r){t=t.filter(function(t){return t.length>0}),t.forEach(y);var n=Array.isArray(r);return r=e&&e.context||r,r&&!n&&(r=[r]),s(t,r),t.map(function(t){return l(t,e,r,n)}).reduce(f,_)}function c(t){return w[t.type]<0}function l(t,e,r,n){var i=n&&"scope"===t[0].name&&"descendant"===t[1].type;return t.reduce(function(t,n,o){return t===_?t:v[n.type](t,n,e,r,i&&1===o)},e&&e.rootFunc||m)}function f(t,e){return e===_||t===m?t:t===_||e===m?e:function(r){return t(r)||e(r)}}function h(t){return t.some(c)}t.exports=n,t.exports.compileUnsafe=o,t.exports.compileToken=u;var p=r(92),d=r(4),g=d.isTag,v=r(93),y=r(94),b=r(10),m=b.trueFunc,_=b.falseFunc,w=r(44),x={type:"descendant"},S={type:"pseudo",name:"scope"},j={},k=d.getParent,E=r(26),A=E.filters,T=d.existsOne,g=d.isTag,O=d.getChildren;A.not=function(t,e,r,n){var i={xmlMode:!(!r||!r.xmlMode),strict:!(!r||!r.strict)};if(i.strict&&(e.length>1||e.some(h)))throw new SyntaxError("complex selectors in :not aren't allowed in strict mode");var o=u(e,i,n);return o===_?t:o===m?_:function(e){return!o(e)&&t(e)}},A.has=function(t,e,r){var n={xmlMode:!(!r||!r.xmlMode),strict:!(!r||!r.strict)},o=e.some(h)?[j]:null,a=u(e,n,o);return a===_?_:a===m?function(e){return O(e).some(g)&&t(e)}:(a=i(a),o?function(e){return t(e)&&(o[0]=e,T(a,O(e)))}:function(e){return t(e)&&T(a,O(e))})},A.matches=function(t,e,r,n){return u(e,{xmlMode:!(!r||!r.xmlMode),strict:!(!r||!r.strict),rootFunc:t},n)}},function(t,e,r){"use strict";function n(t,e,r){var n="0x"+e-65536;return n!==n||r?e:n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320)}function i(t){return t.replace(l,n)}function o(t){return" "===t||"\n"===t||"\t"===t||"\f"===t||"\r"===t}function a(t,e){var r=[];if(""!==(t=s(r,t+"",e)))throw new SyntaxError("Unmatched selector: "+t);return r}function s(t,e,r){function n(){var t=e.match(c)[0];return e=e.substr(t.length),i(t)}function a(t){for(;o(e.charAt(t));)t++;e=e.substr(t)}var l,b,m,_,w=[],x=!1;for(a(0);""!==e;)if(b=e.charAt(0),o(b))x=!0,a(1);else if(b in p)w.push({type:p[b]}),x=!1,a(1);else if(","===b){if(0===w.length)throw new SyntaxError("empty sub-selector");t.push(w),w=[],x=!1,a(1)}else if(x&&(w.length>0&&w.push({type:"descendant"}),x=!1),"*"===b)e=e.substr(1),w.push({type:"universal"});else if(b in d)e=e.substr(1),w.push({type:"attribute",name:d[b][0],action:d[b][1],value:n(),ignoreCase:!1});else if("["===b){if(e=e.substr(1),!(l=e.match(f)))throw new SyntaxError("Malformed attribute selector: "+e);e=e.substr(l[0].length),m=i(l[1]),r&&("lowerCaseAttributeNames"in r?!r.lowerCaseAttributeNames:r.xmlMode)||(m=m.toLowerCase()),w.push({type:"attribute",name:m,action:h[l[2]],value:i(l[4]||l[5]||""),ignoreCase:!!l[6]})}else if(":"===b){if(":"===e.charAt(1)){e=e.substr(2),w.push({type:"pseudo-element",name:n().toLowerCase()});continue}if(e=e.substr(1),m=n().toLowerCase(),l=null,"("===e.charAt(0))if(m in g){_=e.charAt(1);var S=_ in y;if(e=e.substr(S+1),l=[],e=s(l,e,r),S){if(e.charAt(0)!==_)throw new SyntaxError("unmatched quotes in :"+m);e=e.substr(1)}if(")"!==e.charAt(0))throw new SyntaxError("missing closing parenthesis in :"+m+" "+e);e=e.substr(1)}else{for(var j=1,k=1;k>0&&j0&&0===e.length)throw new SyntaxError("empty sub-selector");t.push(e)}t.exports=a;var c=/^(?:\\.|[\w\-\u00c0-\uFFFF])+/,l=/\\([\da-f]{1,6}\s?|(\s)|.)/gi,f=/^\s*((?:\\.|[\w\u00c0-\uFFFF\-])+)\s*(?:(\S?)=\s*(?:(['"])(.*?)\3|(#?(?:\\.|[\w\u00c0-\uFFFF\-])*)|)|)\s*(i)?\]/,h={__proto__:null,undefined:"exists","":"equals","~":"element","^":"start",$:"end","*":"any","!":"not","|":"hyphen"},p={__proto__:null,">":"child","<":"parent","~":"sibling","+":"adjacent"},d={__proto__:null,"#":["id","equals"],".":["class","element"]},g={__proto__:null,has:!0,not:!0,matches:!0},v={__proto__:null,contains:!0,icontains:!0},y={__proto__:null,'"':!0,"'":!0}},function(t,e,r){var n=r(4),i=n.isTag,o=n.getParent,a=n.getChildren,s=n.getSiblings,u=n.getName;t.exports={__proto__:null,attribute:r(43).compile,pseudo:r(26).compile,tag:function(t,e){var r=e.name;return function(e){return u(e)===r&&t(e)}},descendant:function(t,e,r,n,i){return function(e){if(i&&t(e))return!0;for(var r=!1;!r&&(e=o(e));)r=t(e);return r}},parent:function(t,e,r){function n(e){return i(e)&&t(e)}if(r&&r.strict)throw SyntaxError("Parent selector isn't part of CSS3");return function(t){return a(t).some(n)}},child:function(t){return function(e){var r=o(e);return!!r&&t(r)}},sibling:function(t){return function(e){for(var r=s(e),n=0;n=0&&n>=1);else if(e===o.pseudo)if(t.data)if("has"===t.name||"contains"===t.name)e=0;else if("matches"===t.name||"not"===t.name){e=0;for(var r=0;re&&(e=n)}t.data.length>1&&e>0&&(e-=1)}else e=1;else e=3;return e}t.exports=n;var o=r(44),a={__proto__:null,exists:10,equals:8,not:7,start:6,end:6,any:5,hyphen:4,element:4}},function(t,e,r){(function(t,r){function n(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}function i(t,e){for(var r=-1,n=Array(t);++r-1}function b(t,e){var r=this.__data__,n=q(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}function m(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t-1&&t%1==0&&t<=kt}function pt(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function dt(t){return null!=t&&"object"==typeof t}function gt(t){if(!dt(t)||M(t)!=Ct)return!1;var e=se(t);if(null===e)return!0;var r=Zt.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&Xt.call(r)==ee}function vt(t){return Y(t,yt(t))}function yt(t){return ct(t)?C(t,!0):U(t)}function bt(t){return function(){return t}}function mt(t){return t}function _t(){return!1}var wt=200,xt="__lodash_hash_undefined__",St=800,jt=16,kt=9007199254740991,Et="[object Arguments]",At="[object AsyncFunction]",Tt="[object Function]",Ot="[object GeneratorFunction]",Lt="[object Null]",Ct="[object Object]",Bt="[object Proxy]",Dt="[object Undefined]",qt=/[\\^$.*+?()[\]{}|]/g,Pt=/^\[object .+?Constructor\]$/,Mt=/^(?:0|[1-9]\d*)$/,Rt={};Rt["[object Float32Array]"]=Rt["[object Float64Array]"]=Rt["[object Int8Array]"]=Rt["[object Int16Array]"]=Rt["[object Int32Array]"]=Rt["[object Uint8Array]"]=Rt["[object Uint8ClampedArray]"]=Rt["[object Uint16Array]"]=Rt["[object Uint32Array]"]=!0,Rt[Et]=Rt["[object Array]"]=Rt["[object ArrayBuffer]"]=Rt["[object Boolean]"]=Rt["[object DataView]"]=Rt["[object Date]"]=Rt["[object Error]"]=Rt[Tt]=Rt["[object Map]"]=Rt["[object Number]"]=Rt[Ct]=Rt["[object RegExp]"]=Rt["[object Set]"]=Rt["[object String]"]=Rt["[object WeakMap]"]=!1;var It="object"==typeof t&&t&&t.Object===Object&&t,Nt="object"==typeof self&&self&&self.Object===Object&&self,Ut=It||Nt||Function("return this")(),Ft="object"==typeof e&&e&&!e.nodeType&&e,zt=Ft&&"object"==typeof r&&r&&!r.nodeType&&r,Vt=zt&&zt.exports===Ft,$t=Vt&&It.process,Ht=function(){try{return $t&&$t.binding&&$t.binding("util")}catch(t){}}(),Wt=Ht&&Ht.isTypedArray,Gt=Array.prototype,Yt=Function.prototype,Jt=Object.prototype,Qt=Ut["__core-js_shared__"],Xt=Yt.toString,Zt=Jt.hasOwnProperty,Kt=function(){var t=/[^.]+$/.exec(Qt&&Qt.keys&&Qt.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),te=Jt.toString,ee=Xt.call(Object),re=RegExp("^"+Xt.call(Zt).replace(qt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ne=Vt?Ut.Buffer:void 0,ie=Ut.Symbol,oe=Ut.Uint8Array,ae=ne?ne.allocUnsafe:void 0,se=function(t,e){return function(r){return t(e(r))}}(Object.getPrototypeOf,Object),ue=Object.create,ce=Jt.propertyIsEnumerable,le=Gt.splice,fe=ie?ie.toStringTag:void 0,he=function(){try{var t=Q(Object,"defineProperty");return t({},"",{}),t}catch(t){}}(),pe=ne?ne.isBuffer:void 0,de=Math.max,ge=Date.now,ve=Q(Ut,"Map"),ye=Q(Object,"create"),be=function(){function t(){}return function(e){if(!pt(e))return{};if(ue)return ue(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();s.prototype.clear=u,s.prototype.delete=c,s.prototype.get=l,s.prototype.has=f,s.prototype.set=h,p.prototype.clear=d,p.prototype.delete=g,p.prototype.get=v,p.prototype.has=y,p.prototype.set=b,m.prototype.clear=_,m.prototype.delete=w,m.prototype.get=x,m.prototype.has=S,m.prototype.set=j,k.prototype.clear=E,k.prototype.delete=A,k.prototype.get=T,k.prototype.has=O,k.prototype.set=L;var me=function(t){return function(e,r,n){for(var i=-1,o=Object(e),a=n(e),s=a.length;s--;){var u=a[t?s:++i];if(!1===r(o[u],u,o))break}return e}}(),_e=he?function(t,e){return he(t,"toString",{configurable:!0,enumerable:!1,value:bt(e),writable:!0})}:mt,we=function(t){var e=0,r=0;return function(){var n=ge(),i=jt-(n-r);if(r=n,i>0){if(++e>=St)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(_e),xe=R(function(){return arguments}())?R:function(t){return dt(t)&&Zt.call(t,"callee")&&!ce.call(t,"callee")},Se=Array.isArray,je=pe||_t,ke=Wt?function(t){return function(e){return t(e)}}(Wt):N,Ee=function(t){return V(function(e,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=t.length>3&&"function"==typeof o?(i--,o):void 0,a&&tt(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),e=Object(e);++n-1}function w(t,e){var r=this.__data__,n=I(r,t);return n<0?r.push([t,e]):r[n][1]=e,this}function x(t){var e=-1,r=t?t.length:0;for(this.clear();++eu))return!1;var l=a.get(t);if(l&&a.get(e))return l==e;var f=-1,h=!0,p=o&Nt?new T:void 0;for(a.set(t,e),a.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=zt}function At(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function Tt(t){return!!t&&"object"==typeof t}function Ot(t){return"symbol"==typeof t||Tt(t)&&Le.call(t)==re}function Lt(t){return null==t?"":tt(t)}function Ct(t,e,r){var n=null==t?void 0:U(t,e);return void 0===n?r:n}function Bt(t,e){return null!=t&&ut(t,e,z)}function Dt(t){return St(t)?R(t):J(t)}function qt(t){return t}function Pt(t){return ft(t)?i(yt(t)):Z(t)}var Mt=200,Rt="Expected a function",It="__lodash_hash_undefined__",Nt=1,Ut=2,Ft=1/0,zt=9007199254740991,Vt="[object Arguments]",$t="[object Array]",Ht="[object Boolean]",Wt="[object Date]",Gt="[object Error]",Yt="[object Function]",Jt="[object GeneratorFunction]",Qt="[object Map]",Xt="[object Number]",Zt="[object Object]",Kt="[object RegExp]",te="[object Set]",ee="[object String]",re="[object Symbol]",ne="[object ArrayBuffer]",ie="[object DataView]",oe=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ae=/^\w*$/,se=/^\./,ue=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ce=/[\\^$.*+?()[\]{}|]/g,le=/\\(\\)?/g,fe=/^\[object .+?Constructor\]$/,he=/^(?:0|[1-9]\d*)$/,pe={};pe["[object Float32Array]"]=pe["[object Float64Array]"]=pe["[object Int8Array]"]=pe["[object Int16Array]"]=pe["[object Int32Array]"]=pe["[object Uint8Array]"]=pe["[object Uint8ClampedArray]"]=pe["[object Uint16Array]"]=pe["[object Uint32Array]"]=!0,pe[Vt]=pe[$t]=pe[ne]=pe[Ht]=pe[ie]=pe[Wt]=pe[Gt]=pe[Yt]=pe[Qt]=pe[Xt]=pe[Zt]=pe[Kt]=pe[te]=pe[ee]=pe["[object WeakMap]"]=!1;var de="object"==typeof t&&t&&t.Object===Object&&t,ge="object"==typeof self&&self&&self.Object===Object&&self,ve=de||ge||Function("return this")(),ye="object"==typeof e&&e&&!e.nodeType&&e,be=ye&&"object"==typeof r&&r&&!r.nodeType&&r,me=be&&be.exports===ye,_e=me&&de.process,we=function(){try{return _e&&_e.binding("util")}catch(t){}}(),xe=we&&we.isTypedArray,Se=Array.prototype,je=Function.prototype,ke=Object.prototype,Ee=ve["__core-js_shared__"],Ae=function(){var t=/[^.]+$/.exec(Ee&&Ee.keys&&Ee.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Te=je.toString,Oe=ke.hasOwnProperty,Le=ke.toString,Ce=RegExp("^"+Te.call(Oe).replace(ce,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Be=ve.Symbol,De=ve.Uint8Array,qe=ke.propertyIsEnumerable,Pe=Se.splice,Me=function(t,e){return function(r){return t(e(r))}}(Object.keys,Object),Re=st(ve,"DataView"),Ie=st(ve,"Map"),Ne=st(ve,"Promise"),Ue=st(ve,"Set"),Fe=st(ve,"WeakMap"),ze=st(Object,"create"),Ve=bt(Re),$e=bt(Ie),He=bt(Ne),We=bt(Ue),Ge=bt(Fe),Ye=Be?Be.prototype:void 0,Je=Ye?Ye.valueOf:void 0,Qe=Ye?Ye.toString:void 0;l.prototype.clear=f,l.prototype.delete=h,l.prototype.get=p,l.prototype.has=d,l.prototype.set=g,v.prototype.clear=y,v.prototype.delete=b,v.prototype.get=m,v.prototype.has=_,v.prototype.set=w,x.prototype.clear=S,x.prototype.delete=j,x.prototype.get=k,x.prototype.has=E,x.prototype.set=A,T.prototype.add=T.prototype.push=O,T.prototype.has=L,C.prototype.clear=B,C.prototype.delete=D,C.prototype.get=q,C.prototype.has=P,C.prototype.set=M;var Xe=function(t,e){return function(r,n){if(null==r)return r;if(!St(r))return t(r,n);for(var i=r.length,o=e?i:-1,a=Object(r);(e?o--:++o0})},e.first=function(){return this.length>1?this._make(this[0]):this},e.last=function(){return this.length>1?this._make(this[this.length-1]):this},e.eq=function(t){return 0===(t=+t)&&this.length<=1?this:(t<0&&(t=this.length+t),this[t]?this._make(this[t]):this._make([]))},e.get=function(t){return null==t?Array.prototype.slice.call(this):this[t<0?this.length+t:t]},e.index=function(t){var e,r;return 0===arguments.length?(e=this.parent().children(),r=this[0]):"string"==typeof t?(e=this._make(t),r=this[0]):(e=this,r=t.cheerio?t[0]:t),e.get().indexOf(r)},e.slice=function(){return this._make([].slice.apply(this,arguments))},e.end=function(){return this.prevObject||this._make([])},e.add=function(t,e){for(var r=this._make(t,e),n=s(r.get().concat(this.get())),i=0;i-1}function x(t,e){var r=this.__data__,n=N(r,t);return n<0?r.push([t,e]):r[n][1]=e,this}function S(t){var e=-1,r=t?t.length:0;for(this.clear();++eu))return!1;var l=a.get(t);if(l&&a.get(e))return l==e;var f=-1,h=!0,p=o&Ut?new O:void 0;for(a.set(t,e),a.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=Vt}function Tt(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function Ot(t){return!!t&&"object"==typeof t}function Lt(t){return"symbol"==typeof t||Ot(t)&&Ce.call(t)==ne}function Ct(t){return null==t?"":et(t)}function Bt(t,e,r){var n=null==t?void 0:z(t,e);return void 0===n?r:n}function Dt(t,e){return null!=t&&ct(t,e,$)}function qt(t){return jt(t)?I(t):X(t)}function Pt(t){return t}function Mt(t){return ft(t)?o(yt(t)):tt(t)}var Rt=200,It="Expected a function",Nt="__lodash_hash_undefined__",Ut=1,Ft=2,zt=1/0,Vt=9007199254740991,$t="[object Arguments]",Ht="[object Array]",Wt="[object Boolean]",Gt="[object Date]",Yt="[object Error]",Jt="[object Function]",Qt="[object GeneratorFunction]",Xt="[object Map]",Zt="[object Number]",Kt="[object Object]",te="[object RegExp]",ee="[object Set]",re="[object String]",ne="[object Symbol]",ie="[object ArrayBuffer]",oe="[object DataView]",ae=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,se=/^\w*$/,ue=/^\./,ce=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,le=/[\\^$.*+?()[\]{}|]/g,fe=/\\(\\)?/g,he=/^\[object .+?Constructor\]$/,pe=/^(?:0|[1-9]\d*)$/,de={};de["[object Float32Array]"]=de["[object Float64Array]"]=de["[object Int8Array]"]=de["[object Int16Array]"]=de["[object Int32Array]"]=de["[object Uint8Array]"]=de["[object Uint8ClampedArray]"]=de["[object Uint16Array]"]=de["[object Uint32Array]"]=!0,de[$t]=de[Ht]=de[ie]=de[Wt]=de[oe]=de[Gt]=de[Yt]=de[Jt]=de[Xt]=de[Zt]=de[Kt]=de[te]=de[ee]=de[re]=de["[object WeakMap]"]=!1;var ge="object"==typeof t&&t&&t.Object===Object&&t,ve="object"==typeof self&&self&&self.Object===Object&&self,ye=ge||ve||Function("return this")(),be="object"==typeof e&&e&&!e.nodeType&&e,me=be&&"object"==typeof r&&r&&!r.nodeType&&r,_e=me&&me.exports===be,we=_e&&ge.process,xe=function(){try{return we&&we.binding("util")}catch(t){}}(),Se=xe&&xe.isTypedArray,je=Array.prototype,ke=Function.prototype,Ee=Object.prototype,Ae=ye["__core-js_shared__"],Te=function(){var t=/[^.]+$/.exec(Ae&&Ae.keys&&Ae.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Oe=ke.toString,Le=Ee.hasOwnProperty,Ce=Ee.toString,Be=RegExp("^"+Oe.call(Le).replace(le,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),De=ye.Symbol,qe=ye.Uint8Array,Pe=Ee.propertyIsEnumerable,Me=je.splice,Re=function(t,e){return function(r){return t(e(r))}}(Object.keys,Object),Ie=ut(ye,"DataView"),Ne=ut(ye,"Map"),Ue=ut(ye,"Promise"),Fe=ut(ye,"Set"),ze=ut(ye,"WeakMap"),Ve=ut(Object,"create"),$e=bt(Ie),He=bt(Ne),We=bt(Ue),Ge=bt(Fe),Ye=bt(ze),Je=De?De.prototype:void 0,Qe=Je?Je.valueOf:void 0,Xe=Je?Je.toString:void 0;f.prototype.clear=h,f.prototype.delete=p,f.prototype.get=d,f.prototype.has=g,f.prototype.set=v,y.prototype.clear=b,y.prototype.delete=m,y.prototype.get=_,y.prototype.has=w,y.prototype.set=x,S.prototype.clear=j,S.prototype.delete=k,S.prototype.get=E,S.prototype.has=A,S.prototype.set=T,O.prototype.add=O.prototype.push=L,O.prototype.has=C,B.prototype.clear=D,B.prototype.delete=q,B.prototype.get=P,B.prototype.has=M,B.prototype.set=R;var Ze=function(t,e){return function(r,n){if(null==r)return r;if(!jt(r))return t(r,n);for(var i=r.length,o=e?i:-1,a=Object(r);(e?o--:++o-1}function x(t,e){var r=this.__data__,n=N(r,t);return n<0?r.push([t,e]):r[n][1]=e,this}function S(t){var e=-1,r=t?t.length:0;for(this.clear();++eu))return!1;var l=a.get(t);if(l&&a.get(e))return l==e;var f=-1,h=!0,p=o&Nt?new O:void 0;for(a.set(t,e),a.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=zt}function At(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function Tt(t){return!!t&&"object"==typeof t}function Ot(t){return"symbol"==typeof t||Tt(t)&&Le.call(t)==re}function Lt(t){return null==t?"":et(t)}function Ct(t,e,r){var n=null==t?void 0:z(t,e);return void 0===n?r:n}function Bt(t,e){return null!=t&&ct(t,e,$)}function Dt(t){return St(t)?I(t):X(t)}function qt(t){return t}function Pt(t){return ft(t)?o(yt(t)):tt(t)}var Mt=200,Rt="Expected a function",It="__lodash_hash_undefined__",Nt=1,Ut=2,Ft=1/0,zt=9007199254740991,Vt="[object Arguments]",$t="[object Array]",Ht="[object Boolean]",Wt="[object Date]",Gt="[object Error]",Yt="[object Function]",Jt="[object GeneratorFunction]",Qt="[object Map]",Xt="[object Number]",Zt="[object Object]",Kt="[object RegExp]",te="[object Set]",ee="[object String]",re="[object Symbol]",ne="[object ArrayBuffer]",ie="[object DataView]",oe=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ae=/^\w*$/,se=/^\./,ue=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ce=/[\\^$.*+?()[\]{}|]/g,le=/\\(\\)?/g,fe=/^\[object .+?Constructor\]$/,he=/^(?:0|[1-9]\d*)$/,pe={};pe["[object Float32Array]"]=pe["[object Float64Array]"]=pe["[object Int8Array]"]=pe["[object Int16Array]"]=pe["[object Int32Array]"]=pe["[object Uint8Array]"]=pe["[object Uint8ClampedArray]"]=pe["[object Uint16Array]"]=pe["[object Uint32Array]"]=!0,pe[Vt]=pe[$t]=pe[ne]=pe[Ht]=pe[ie]=pe[Wt]=pe[Gt]=pe[Yt]=pe[Qt]=pe[Xt]=pe[Zt]=pe[Kt]=pe[te]=pe[ee]=pe["[object WeakMap]"]=!1;var de="object"==typeof t&&t&&t.Object===Object&&t,ge="object"==typeof self&&self&&self.Object===Object&&self,ve=de||ge||Function("return this")(),ye="object"==typeof e&&e&&!e.nodeType&&e,be=ye&&"object"==typeof r&&r&&!r.nodeType&&r,me=be&&be.exports===ye,_e=me&&de.process,we=function(){try{return _e&&_e.binding("util")}catch(t){}}(),xe=we&&we.isTypedArray,Se=Array.prototype,je=Function.prototype,ke=Object.prototype,Ee=ve["__core-js_shared__"],Ae=function(){var t=/[^.]+$/.exec(Ee&&Ee.keys&&Ee.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Te=je.toString,Oe=ke.hasOwnProperty,Le=ke.toString,Ce=RegExp("^"+Te.call(Oe).replace(ce,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Be=ve.Symbol,De=ve.Uint8Array,qe=ke.propertyIsEnumerable,Pe=Se.splice,Me=function(t,e){return function(r){return t(e(r))}}(Object.keys,Object),Re=ut(ve,"DataView"),Ie=ut(ve,"Map"),Ne=ut(ve,"Promise"),Ue=ut(ve,"Set"),Fe=ut(ve,"WeakMap"),ze=ut(Object,"create"),Ve=bt(Re),$e=bt(Ie),He=bt(Ne),We=bt(Ue),Ge=bt(Fe),Ye=Be?Be.prototype:void 0,Je=Ye?Ye.valueOf:void 0,Qe=Ye?Ye.toString:void 0;f.prototype.clear=h,f.prototype.delete=p,f.prototype.get=d,f.prototype.has=g,f.prototype.set=v,y.prototype.clear=b,y.prototype.delete=m,y.prototype.get=_,y.prototype.has=w,y.prototype.set=x,S.prototype.clear=j,S.prototype.delete=k,S.prototype.get=E,S.prototype.has=A,S.prototype.set=T,O.prototype.add=O.prototype.push=L,O.prototype.has=C,B.prototype.clear=D,B.prototype.delete=q,B.prototype.get=P,B.prototype.has=M,B.prototype.set=R;var Xe=function(t,e){return function(r,n){if(null==r)return r;if(!St(r))return t(r,n);for(var i=r.length,o=e?i:-1,a=Object(r);(e?o--:++o-1}function S(t,e){var r=this.__data__,n=U(r,t);return n<0?r.push([t,e]):r[n][1]=e,this}function j(t){var e=-1,r=t?t.length:0;for(this.clear();++eu))return!1;var l=a.get(t);if(l&&a.get(e))return l==e;var f=-1,h=!0,p=o&Nt?new L:void 0;for(a.set(t,e),a.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=zt}function At(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function Tt(t){return!!t&&"object"==typeof t}function Ot(t){return"symbol"==typeof t||Tt(t)&&Le.call(t)==re}function Lt(t){return null==t?"":et(t)}function Ct(t,e,r){var n=null==t?void 0:z(t,e);return void 0===n?r:n}function Bt(t,e){return null!=t&&ct(t,e,$)}function Dt(t){return St(t)?N(t):X(t)}function qt(t){return t}function Pt(t){return ft(t)?o(yt(t)):tt(t)}var Mt=200,Rt="Expected a function",It="__lodash_hash_undefined__",Nt=1,Ut=2,Ft=1/0,zt=9007199254740991,Vt="[object Arguments]",$t="[object Array]",Ht="[object Boolean]",Wt="[object Date]",Gt="[object Error]",Yt="[object Function]",Jt="[object GeneratorFunction]",Qt="[object Map]",Xt="[object Number]",Zt="[object Object]",Kt="[object RegExp]",te="[object Set]",ee="[object String]",re="[object Symbol]",ne="[object ArrayBuffer]",ie="[object DataView]",oe=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ae=/^\w*$/,se=/^\./,ue=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ce=/[\\^$.*+?()[\]{}|]/g,le=/\\(\\)?/g,fe=/^\[object .+?Constructor\]$/,he=/^(?:0|[1-9]\d*)$/,pe={};pe["[object Float32Array]"]=pe["[object Float64Array]"]=pe["[object Int8Array]"]=pe["[object Int16Array]"]=pe["[object Int32Array]"]=pe["[object Uint8Array]"]=pe["[object Uint8ClampedArray]"]=pe["[object Uint16Array]"]=pe["[object Uint32Array]"]=!0,pe[Vt]=pe[$t]=pe[ne]=pe[Ht]=pe[ie]=pe[Wt]=pe[Gt]=pe[Yt]=pe[Qt]=pe[Xt]=pe[Zt]=pe[Kt]=pe[te]=pe[ee]=pe["[object WeakMap]"]=!1;var de="object"==typeof t&&t&&t.Object===Object&&t,ge="object"==typeof self&&self&&self.Object===Object&&self,ve=de||ge||Function("return this")(),ye="object"==typeof e&&e&&!e.nodeType&&e,be=ye&&"object"==typeof r&&r&&!r.nodeType&&r,me=be&&be.exports===ye,_e=me&&de.process,we=function(){try{return _e&&_e.binding("util")}catch(t){}}(),xe=we&&we.isTypedArray,Se=Array.prototype,je=Function.prototype,ke=Object.prototype,Ee=ve["__core-js_shared__"],Ae=function(){var t=/[^.]+$/.exec(Ee&&Ee.keys&&Ee.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Te=je.toString,Oe=ke.hasOwnProperty,Le=ke.toString,Ce=RegExp("^"+Te.call(Oe).replace(ce,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Be=ve.Symbol,De=ve.Uint8Array,qe=ke.propertyIsEnumerable,Pe=Se.splice,Me=function(t,e){return function(r){return t(e(r))}}(Object.keys,Object),Re=ut(ve,"DataView"),Ie=ut(ve,"Map"),Ne=ut(ve,"Promise"),Ue=ut(ve,"Set"),Fe=ut(ve,"WeakMap"),ze=ut(Object,"create"),Ve=bt(Re),$e=bt(Ie),He=bt(Ne),We=bt(Ue),Ge=bt(Fe),Ye=Be?Be.prototype:void 0,Je=Ye?Ye.valueOf:void 0,Qe=Ye?Ye.toString:void 0;h.prototype.clear=p,h.prototype.delete=d,h.prototype.get=g,h.prototype.has=v,h.prototype.set=y,b.prototype.clear=m,b.prototype.delete=_,b.prototype.get=w,b.prototype.has=x,b.prototype.set=S,j.prototype.clear=k,j.prototype.delete=E,j.prototype.get=A,j.prototype.has=T,j.prototype.set=O,L.prototype.add=L.prototype.push=C,L.prototype.has=B,D.prototype.clear=q,D.prototype.delete=P,D.prototype.get=M,D.prototype.has=R,D.prototype.set=I;var Xe=function(t,e){return function(r,n){if(null==r)return r;if(!St(r))return t(r,n);for(var i=r.length,o=e?i:-1,a=Object(r);(e?o--:++o-1&&(c.children.splice(s,1),i===c&&e>s&&l[0]--),u.root=null,u.parent=i,u.prev&&(u.prev.next=u.next||null),u.next&&(u.next.prev=u.prev||null),u.prev=n[o-1]||f,u.next=n[o+1]||h;return f&&(f.next=n[0]),h&&(h.prev=n[n.length-1]),t.splice.apply(t,l)};e.appendTo=function(t){return t.cheerio||(t=this.constructor.call(this.constructor,t,null,this._originalRoot)),t.append(this),this},e.prependTo=function(t){return t.cheerio||(t=this.constructor.call(this.constructor,t,null,this._originalRoot)),t.prepend(this),this},e.append=p(function(t,e,r){d(e,e.length,0,t,r)}),e.prepend=p(function(t,e,r){d(e,0,0,t,r)}),e.wrap=function(t){var e="function"==typeof t&&t,r=this.length-1;return h.forEach(this,h.bind(function(n,i){var a,s,u=n.parent||n.root,c=u.children;u&&(e&&(t=e.call(n,i)),"string"!=typeof t||l(t)||(t=this.parents().last().find(t).clone()),a=this._makeDomArray(t,i0&&o(l)?e>1?n(l,e-1,o,a,s):r(s,l):a||(s[s.length]=l)}return s}function i(t){return E(t)||a(t)||!!(k&&t&&t[k])}function o(t){return(t?t.length:0)?n(t,1):[]}function a(t){return u(t)&&w.call(t,"callee")&&(!j.call(t,"callee")||x.call(t)==d)}function s(t){return null!=t&&l(t.length)&&!c(t)}function u(t){return h(t)&&s(t)}function c(t){var e=f(t)?x.call(t):"";return e==g||e==v}function l(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=p}function f(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function h(t){return!!t&&"object"==typeof t}var p=9007199254740991,d="[object Arguments]",g="[object Function]",v="[object GeneratorFunction]",y="object"==typeof e&&e&&e.Object===Object&&e,b="object"==typeof self&&self&&self.Object===Object&&self,m=y||b||Function("return this")(),_=Object.prototype,w=_.hasOwnProperty,x=_.toString,S=m.Symbol,j=_.propertyIsEnumerable,k=S?S.isConcatSpreadable:void 0,E=Array.isArray;t.exports=o}).call(e,r(0))},function(t,e,r){function n(t,e,r,a){if("string"==typeof e){var s=i(t);"function"==typeof r&&(r=r.call(t,a,s[e])),""===r?delete s[e]:null!=r&&(s[e]=r),t.attribs.style=o(s)}else"object"==typeof e&&Object.keys(e).forEach(function(r){n(t,r,e[r])})}function i(t,e){var r=a(t.attribs.style);return"string"==typeof e?r[e]:Array.isArray(e)?u.pick(r,e):r}function o(t){return Object.keys(t||{}).reduce(function(e,r){return e+=(e?" ":"")+r+": "+t[r]+";"},"")}function a(t){return t=(t||"").trim(),t?t.split(";").reduce(function(t,e){var r=e.indexOf(":");return r<1||r===e.length-1?t:(t[e.slice(0,r).trim()]=e.slice(r+1).trim(),t)},{}):{}}var s=r(9).domEach,u={pick:r(104)},c=Object.prototype.toString;e.css=function(t,e){return 2===arguments.length||"[object Object]"===c.call(t)?s(this,function(r,i){n(i,t,e,r)}):i(this[0],t)}},function(t,e,r){(function(e){function r(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}function n(t,e){for(var r=-1,n=t?t.length:0,i=Array(n);++r0&&r(l)?e>1?o(l,e-1,r,n,a):i(a,l):n||(a[a.length]=l)}return a}function a(t,e){return t=Object(t),s(t,e,function(e,r){return r in t})}function s(t,e,r){for(var n=-1,i=e.length,o={};++n-1&&t%1==0&&t<=m}function g(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function v(t){return!!t&&"object"==typeof t}function y(t){return"symbol"==typeof t||v(t)&&O.call(t)==S}var b=1/0,m=9007199254740991,_="[object Arguments]",w="[object Function]",x="[object GeneratorFunction]",S="[object Symbol]",j="object"==typeof e&&e&&e.Object===Object&&e,k="object"==typeof self&&self&&self.Object===Object&&self,E=j||k||Function("return this")(),A=Object.prototype,T=A.hasOwnProperty,O=A.toString,L=E.Symbol,C=A.propertyIsEnumerable,B=L?L.isConcatSpreadable:void 0,D=Math.max,q=Array.isArray,P=function(t,e){return e=D(void 0===e?t.length-1:e,0),function(){for(var n=arguments,i=-1,o=D(n.length-e,0),a=Array(o);++i-1}function x(t,e){var r=this.__data__,n=N(r,t);return n<0?r.push([t,e]):r[n][1]=e,this}function S(t){var e=-1,r=t?t.length:0;for(this.clear();++eu))return!1;var l=a.get(t);if(l&&a.get(e))return l==e;var f=-1,h=!0,p=o&Nt?new O:void 0;for(a.set(t,e),a.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=zt}function At(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function Tt(t){return!!t&&"object"==typeof t}function Ot(t){return"symbol"==typeof t||Tt(t)&&Le.call(t)==re}function Lt(t){return null==t?"":et(t)}function Ct(t,e,r){var n=null==t?void 0:F(t,e);return void 0===n?r:n}function Bt(t,e){return null!=t&&ct(t,e,V)}function Dt(t){return St(t)?I(t):Q(t)}function qt(t){return t}function Pt(t){return ft(t)?o(yt(t)):tt(t)}var Mt=200,Rt="Expected a function",It="__lodash_hash_undefined__",Nt=1,Ut=2,Ft=1/0,zt=9007199254740991,Vt="[object Arguments]",$t="[object Array]",Ht="[object Boolean]",Wt="[object Date]",Gt="[object Error]",Yt="[object Function]",Jt="[object GeneratorFunction]",Qt="[object Map]",Xt="[object Number]",Zt="[object Object]",Kt="[object RegExp]",te="[object Set]",ee="[object String]",re="[object Symbol]",ne="[object ArrayBuffer]",ie="[object DataView]",oe=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ae=/^\w*$/,se=/^\./,ue=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ce=/[\\^$.*+?()[\]{}|]/g,le=/\\(\\)?/g,fe=/^\[object .+?Constructor\]$/,he=/^(?:0|[1-9]\d*)$/,pe={};pe["[object Float32Array]"]=pe["[object Float64Array]"]=pe["[object Int8Array]"]=pe["[object Int16Array]"]=pe["[object Int32Array]"]=pe["[object Uint8Array]"]=pe["[object Uint8ClampedArray]"]=pe["[object Uint16Array]"]=pe["[object Uint32Array]"]=!0,pe[Vt]=pe[$t]=pe[ne]=pe[Ht]=pe[ie]=pe[Wt]=pe[Gt]=pe[Yt]=pe[Qt]=pe[Xt]=pe[Zt]=pe[Kt]=pe[te]=pe[ee]=pe["[object WeakMap]"]=!1;var de="object"==typeof t&&t&&t.Object===Object&&t,ge="object"==typeof self&&self&&self.Object===Object&&self,ve=de||ge||Function("return this")(),ye="object"==typeof e&&e&&!e.nodeType&&e,be=ye&&"object"==typeof r&&r&&!r.nodeType&&r,me=be&&be.exports===ye,_e=me&&de.process,we=function(){try{return _e&&_e.binding("util")}catch(t){}}(),xe=we&&we.isTypedArray,Se=Array.prototype,je=Function.prototype,ke=Object.prototype,Ee=ve["__core-js_shared__"],Ae=function(){var t=/[^.]+$/.exec(Ee&&Ee.keys&&Ee.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Te=je.toString,Oe=ke.hasOwnProperty,Le=ke.toString,Ce=RegExp("^"+Te.call(Oe).replace(ce,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Be=ve.Symbol,De=ve.Uint8Array,qe=ke.propertyIsEnumerable,Pe=Se.splice,Me=function(t,e){return function(r){return t(e(r))}}(Object.keys,Object),Re=ut(ve,"DataView"),Ie=ut(ve,"Map"),Ne=ut(ve,"Promise"),Ue=ut(ve,"Set"),Fe=ut(ve,"WeakMap"),ze=ut(Object,"create"),Ve=bt(Re),$e=bt(Ie),He=bt(Ne),We=bt(Ue),Ge=bt(Fe),Ye=Be?Be.prototype:void 0,Je=Ye?Ye.valueOf:void 0,Qe=Ye?Ye.toString:void 0;f.prototype.clear=h,f.prototype.delete=p,f.prototype.get=d,f.prototype.has=g,f.prototype.set=v,y.prototype.clear=b,y.prototype.delete=m,y.prototype.get=_,y.prototype.has=w,y.prototype.set=x,S.prototype.clear=j,S.prototype.delete=k,S.prototype.get=E,S.prototype.has=A,S.prototype.set=T,O.prototype.add=O.prototype.push=L,O.prototype.has=C,B.prototype.clear=D,B.prototype.delete=q,B.prototype.get=P,B.prototype.has=M,B.prototype.set=R;var Xe=function(t,e){return function(r,n){if(null==r)return r;if(!St(r))return t(r,n);for(var i=r.length,o=e?i:-1,a=Object(r);(e?o--:++o= 0.6"},files:["index.js","lib"],homepage:"https://github.com/cheeriojs/cheerio#readme",keywords:["htmlparser","jquery","selector","scraper","parser","html"],license:"MIT",main:"./index.js",name:"cheerio",repository:{type:"git",url:"git://github.com/cheeriojs/cheerio.git"},scripts:{test:"make test"},version:"0.22.0"}},function(t,e,r){t.exports={lex:r(45),parse:r(109),stringify:r(110)}},function(t,e,r){function n(t,e){var r;e||(e={}),w=!!e.comments,S=!!e.position,x=0,j=Array.isArray(t)?t.slice():_(t);var n,i,a=[];for(b&&(r=Date.now());i=o();)(n=p(i))&&a.push(n);return b&&m("ran in",Date.now()-r+"ms"),{type:"stylesheet",stylesheet:{rules:a}}}function i(t,e){e||(e={});for(var r,n=["type","name","value"],i={},o=0;o+)\\s*|(\\s+)|(+|\\*)|\\#(+)|\\.(+)|\\[\\s*(+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)".replace(//,"["+o(">+~`!@$%^&={}\\;/g,"(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])").replace(//g,"(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])")),u=function(t){this.combinator=t||" ",this.tag="*"};u.prototype.toString=function(){if(!this.raw){var t,e,r="";if(r+=this.tag||"*",this.id&&(r+="#"+this.id),this.classes&&(r+="."+this.classList.join(".")),this.attributes)for(t=0;e=this.attributes[t++];)r+="["+e.name+(e.operator?e.operator+'"'+e.value+'"':"")+"]";if(this.pseudos)for(t=0;e=this.pseudos[t++];)r+=":"+e.name,e.value&&(r+="("+e.value+")");this.raw=r}return this.raw};var c=function(){this.length=0};c.prototype.toString=function(){if(!this.raw){for(var t,e="",r=0;t=this[r++];)1!==r&&(e+=" ")," "!==t.combinator&&(e+=t.combinator+" "),e+=t;this.raw=e}return this.raw};var l=function(t,e,r,n,i,s,l,f,h,p,d,g,v,y,b,m){var _,w;if((e||!this.length)&&(_=this[this.length++]=new c,e))return"";if(_||(_=this[this.length-1]),(r||n||!_.length)&&(w=_[_.length++]=new u(r)),w||(w=_[_.length-1]),i)w.tag=a(i);else if(s)w.id=a(s);else if(l){var x=a(l),S=w.classes||(w.classes={});if(!S[x]){S[x]=o(l);var j=w.classList||(w.classList=[]);j.push(x),j.sort()}}else v?(m=m||b,(w.pseudos||(w.pseudos=[])).push({type:1==g.length?"class":"element",name:a(v),escapedName:o(v),value:m?a(m):null,escapedValue:m?o(m):null})):f&&(d=d?o(d):null,(w.attributes||(w.attributes=[])).push({operator:h,name:a(f),escapedName:o(f),value:d?a(d):null,escapedValue:d?o(d):null}));return""},f=function(t){this.length=0;for(var e,r=this,n=t;t;){if((e=t.replace(s,function(){return l.apply(r,arguments)}))===t)throw new Error(n+" is an invalid expression");t=e}};f.prototype.toString=function(){if(!this.raw){for(var t,e=[],r=0;t=this[r++];)e.push(t);this.raw=e.join(", ")}return this.raw};var h={},p=function(t){return null==t?null:(t=(""+t).replace(/^\s+|\s+$/g,""),h[t]||(h[t]=new f(t)))};t.exports=p},function(t,e,r){"use strict";function n(t,e,r,n,i){this.prop=t,this.value=e,this.selector=r,this.priority=n||0,this.additionalPriority=i||[]}t.exports=n;var i=r(27);n.prototype.compareFunc=function(t){var e=[];e.push.apply(e,this.selector.specificity()),e.push.apply(e,this.additionalPriority),e[0]+=this.priority;var r=[];return r.push.apply(r,t.selector.specificity()),r.push.apply(r,t.additionalPriority),r[0]+=t.priority,i.compareFunc(e,r)},n.prototype.compare=function(t){return 1===this.compareFunc(t)?this:t},n.prototype.toString=function(){return this.prop+": "+this.value.replace(/['"]+/g,"")+";"}},function(t,e,r){"use strict";var n=r(27);t.exports=function(t){function e(e,o,s){function u(r){for(var o=r[0],u=r[1],c=new n.Selector(o),l=c.parsed(),f=i(l),h=0;h=0)return}}if(f){var b=l[l.length-1],m=b.pseudos;b.pseudos=a(b.pseudos),o=l.toString(),b.pseudos=m}var _;try{_=e(o)}catch(t){return}_.each(function(){function r(e,r){for(var o=0,a=e.length;o=0)){if(f){var o="pseudo"+f,a=i[o];a||(a=i[o]=e("").get(0),a.pseudoElementType=f,a.pseudoElementParent=i,i[o]=a),i=a}if(!i.styleProps){if(i.styleProps={},e(i).attr(v)){var l="* { "+e(i).attr(v)+" } ";r(n.parseCSS(l)[0][1],new n.Selector("")}}}function r(t){if("none"===t||"normal"===t)return"";var e=t.match(/^\s*url\s*\(\s*(.*?)\s*\)\s*$/i);if(e){return{img:e[1].replace(/^['"]|['"]$/g,"")}}return t=t.slice(1,t.length-1),t=t.replace(/\\/g,"")}function i(t){if(0!==t.length){var e=t[t.length-1].pseudos;if(e)for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},e="",r="",n=t.editor,i=t.tableStyle||{},o=t.cellStyle||{},a=n.BlockManager;for(var s in i)e+=s+": "+i[s]+"; ";for(var u in o)r+=u+": "+o[u]+"; ";a.getAll().reset(),a.add("sect100",{label:t.sect100BlkLabel,category:t.categoryLabel,attributes:{class:"gjs-fonts gjs-f-b1"},content:'\n \n \n \n
'}),a.add("sect50",{label:t.sect50BlkLabel,category:t.categoryLabel,attributes:{class:"gjs-fonts gjs-f-b2"},content:'\n \n \n \n \n
'}),a.add("sect30",{label:t.sect30BlkLabel,category:t.categoryLabel,attributes:{class:"gjs-fonts gjs-f-b3"},content:'\n \n \n \n \n \n
'}),a.add("sect37",{label:t.sect37BlkLabel,category:t.categoryLabel,attributes:{class:"gjs-fonts gjs-f-b37"},content:'\n \n \n \n \n
'}),a.add("button",{label:t.buttonBlkLabel,category:t.categoryLabel,content:'Button',attributes:{class:"gjs-fonts gjs-f-button"}}),a.add("divider",{label:t.dividerBlkLabel,category:t.categoryLabel,content:'\n \n \n \n
\n ',attributes:{class:"gjs-fonts gjs-f-divider"}}),a.add("text",{label:t.textBlkLabel,category:t.categoryLabel,attributes:{class:"gjs-fonts gjs-f-text"},content:{type:"text",content:"Insert your text here",style:{padding:"10px"},activeOnRender:1}}),a.add("text-sect",{label:t.textSectionBlkLabel,category:t.categoryLabel,content:'

Insert title here

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua

',attributes:{class:"gjs-fonts gjs-f-h1p"}}),a.add("image",{label:t.imageBlkLabel,category:t.categoryLabel,attributes:{class:"gjs-fonts gjs-f-image"},content:{type:"image",style:{color:"black"},activeOnRender:1}}),a.add("quote",{label:t.quoteBlkLabel,category:t.categoryLabel,content:'
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore ipsum dolor sit
',attributes:{class:"fa fa-quote-right"}}),a.add("link",{label:t.linkBlkLabel,category:t.categoryLabel,attributes:{class:"fa fa-link"},content:{type:"link",content:"Link",style:{color:"#3b97e3"}}}),a.add("link-block",{label:t.linkBlockBlkLabel,category:t.categoryLabel,attributes:{class:"fa fa-link"},content:{type:"link",editable:!1,droppable:!0,style:{display:"inline-block",padding:"5px","min-height":"50px","min-width":"50px"}}});var c='\n \n \n \n
\n Image\n \n \n \n \n
\n

Title here

\n

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt

\n
\n
';a.add("grid-items",{label:t.gridItemsBlkLabel,category:t.categoryLabel,content:'\n \n \n \n \n
'+c+''+c+"
",attributes:{class:"fa fa-th"}});var l='\n \n \n \n
\n \n \n \n \n \n
\n Image\n \n

Title here

\n

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt

\n
\n
';a.add("list-items",{label:t.listItemsBlkLabel,category:t.categoryLabel,content:l+l,attributes:{class:"fa fa-th-list"}})}}.call(e,r,e,t))&&(t.exports=n)},function(t,e,r){"use strict";function n(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}var i;void 0!==(i=function(){var t=function(t){t.each(function(t){var e=t.get("attributes");e["data-tooltip-pos"]="bottom",t.set("attributes",e)})};return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.editor,i=r.Panels,o=i.getPanel("options");if(i.addButton("options",{id:e.cmdOpenImport,className:"fa fa-download",command:e.cmdOpenImport,attributes:n({},"title",e.modalTitleImport)}),i.addButton("options",{id:e.cmdTglImages,className:"fa fa-warning",command:e.cmdTglImages,attributes:n({},"title",e.cmtTglImagesLabel)}),o){var a=o.get("buttons");a.each(function(t){var e=t.get("attributes");e["data-tooltip-pos"]="bottom",t.set("attributes",e)});var s=i.addButton("options","preview");s&&a.remove(s)}var u=i.getPanel("commands");if(u){var c=u.get("buttons");c.reset(),c.add([{id:"undo",className:"fa fa-undo",command:"undo",attributes:n({},"title",e.cmdBtnUndoLabel)},{id:"redo",className:"fa fa-repeat",command:"redo",attributes:n({},"title",e.cmdBtnRedoLabel)}]),t(c)}r.getConfig().showDevices=0;var l=i.addPanel({id:"devices-c"}),f=l.get("buttons");l.get("buttons").add([{id:"deviceDesktop",command:"set-device-desktop",className:"fa fa-desktop",attributes:n({},"title",e.cmdBtnDesktopLabel),active:1},{id:"deviceTablet",command:"set-device-tablet",className:"fa fa-tablet",attributes:n({},"title",e.cmdBtnTabletLabel)},{id:"deviceMobile",command:"set-device-mobile",className:"fa fa-mobile",attributes:n({},"title",e.cmdBtnMobileLabel)}]),t(f)}}.call(e,r,e,t))&&(t.exports=i)},function(t,e,r){"use strict";var n;void 0!==(n=function(){return function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.editor,r=e.StyleManager.getSectors();e.on("load",function(){r.reset(),r.add(t.styleManagerSectors)})}}.call(e,r,e,t))&&(t.exports=n)}])}); \ No newline at end of file diff --git a/public/vendor/grapesjs/.keep b/public/vendor/grapesjs/.keep new file mode 100644 index 0000000..7c888a6 --- /dev/null +++ b/public/vendor/grapesjs/.keep @@ -0,0 +1 @@ +Place vendor files here (grapesjs, grapesjs-preset-newsletter). \ No newline at end of file diff --git a/public/vendor/grapesjs/grapes.min.css b/public/vendor/grapesjs/grapes.min.css new file mode 100644 index 0000000..62009a2 --- /dev/null +++ b/public/vendor/grapesjs/grapes.min.css @@ -0,0 +1 @@ +.CodeMirror{font-family:monospace;height:300px;color:black;direction:ltr}.CodeMirror-lines{padding:4px 0}.CodeMirror pre.CodeMirror-line,.CodeMirror pre.CodeMirror-line-like{padding:0 4px}.CodeMirror-scrollbar-filler,.CodeMirror-gutter-filler{background-color:white}.CodeMirror-gutters{border-right:1px solid #ddd;background-color:#f7f7f7;white-space:nowrap}.CodeMirror-linenumber{padding:0 3px 0 5px;min-width:20px;text-align:right;color:#999;white-space:nowrap}.CodeMirror-guttermarker{color:black}.CodeMirror-guttermarker-subtle{color:#999}.CodeMirror-cursor{border-left:1px solid black;border-right:none;width:0}.CodeMirror div.CodeMirror-secondarycursor{border-left:1px solid silver}.cm-fat-cursor .CodeMirror-cursor{width:auto;border:0 !important;background:#7e7}.cm-fat-cursor div.CodeMirror-cursors{z-index:1}.cm-fat-cursor-mark{background-color:rgba(20, 255, 20, 0.5);-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite}.cm-animate-fat-cursor{width:auto;-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite;background-color:#7e7}@-moz-keyframes blink{50%{background-color:transparent}}@-webkit-keyframes blink{50%{background-color:transparent}}@keyframes blink{50%{background-color:transparent}}.cm-tab{display:inline-block;text-decoration:inherit}.CodeMirror-rulers{position:absolute;left:0;right:0;top:-50px;bottom:0;overflow:hidden}.CodeMirror-ruler{border-left:1px solid #ccc;top:0;bottom:0;position:absolute}.cm-s-default .cm-header{color:blue}.cm-s-default .cm-quote{color:#090}.cm-negative{color:#d44}.cm-positive{color:#292}.cm-header,.cm-strong{font-weight:bold}.cm-em{font-style:italic}.cm-link{text-decoration:underline}.cm-strikethrough{text-decoration:line-through}.cm-s-default .cm-keyword{color:#708}.cm-s-default .cm-atom{color:#219}.cm-s-default .cm-number{color:#164}.cm-s-default .cm-def{color:blue}.cm-s-default .cm-variable-2{color:#05a}.cm-s-default .cm-variable-3,.cm-s-default .cm-type{color:#085}.cm-s-default .cm-comment{color:#a50}.cm-s-default .cm-string{color:#a11}.cm-s-default .cm-string-2{color:#f50}.cm-s-default .cm-meta{color:#555}.cm-s-default .cm-qualifier{color:#555}.cm-s-default .cm-builtin{color:#30a}.cm-s-default .cm-bracket{color:#997}.cm-s-default .cm-tag{color:#170}.cm-s-default .cm-attribute{color:#00c}.cm-s-default .cm-hr{color:#999}.cm-s-default .cm-link{color:#00c}.cm-s-default .cm-error{color:red}.cm-invalidchar{color:red}.CodeMirror-composing{border-bottom:2px solid}div.CodeMirror span.CodeMirror-matchingbracket{color:#0b0}div.CodeMirror span.CodeMirror-nonmatchingbracket{color:#a22}.CodeMirror-matchingtag{background:rgba(255, 150, 0, 0.3)}.CodeMirror-activeline-background{background:#e8f2ff}.CodeMirror{position:relative;overflow:hidden;background:white}.CodeMirror-scroll{overflow:scroll !important;margin-bottom:-50px;margin-right:-50px;padding-bottom:50px;height:100%;outline:none;position:relative}.CodeMirror-sizer{position:relative;border-right:50px solid transparent}.CodeMirror-vscrollbar,.CodeMirror-hscrollbar,.CodeMirror-scrollbar-filler,.CodeMirror-gutter-filler{position:absolute;z-index:6;display:none;outline:none}.CodeMirror-vscrollbar{right:0;top:0;overflow-x:hidden;overflow-y:scroll}.CodeMirror-hscrollbar{bottom:0;left:0;overflow-y:hidden;overflow-x:scroll}.CodeMirror-scrollbar-filler{right:0;bottom:0}.CodeMirror-gutter-filler{left:0;bottom:0}.CodeMirror-gutters{position:absolute;left:0;top:0;min-height:100%;z-index:3}.CodeMirror-gutter{white-space:normal;height:100%;display:inline-block;vertical-align:top;margin-bottom:-50px}.CodeMirror-gutter-wrapper{position:absolute;z-index:4;background:none !important;border:none !important}.CodeMirror-gutter-background{position:absolute;top:0;bottom:0;z-index:4}.CodeMirror-gutter-elt{position:absolute;cursor:default;z-index:4}.CodeMirror-gutter-wrapper ::selection{background-color:transparent}.CodeMirror-gutter-wrapper ::-moz-selection{background-color:transparent}.CodeMirror-lines{cursor:text;min-height:1px}.CodeMirror pre.CodeMirror-line,.CodeMirror pre.CodeMirror-line-like{-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;border-width:0;background:transparent;font-family:inherit;font-size:inherit;margin:0;white-space:pre;word-wrap:normal;line-height:inherit;color:inherit;z-index:2;position:relative;overflow:visible;-webkit-tap-highlight-color:transparent;-webkit-font-variant-ligatures:contextual;font-variant-ligatures:contextual}.CodeMirror-wrap pre.CodeMirror-line,.CodeMirror-wrap pre.CodeMirror-line-like{word-wrap:break-word;white-space:pre-wrap;word-break:normal}.CodeMirror-linebackground{position:absolute;left:0;right:0;top:0;bottom:0;z-index:0}.CodeMirror-linewidget{position:relative;z-index:2;padding:.1px}.CodeMirror-rtl pre{direction:rtl}.CodeMirror-code{outline:none}.CodeMirror-scroll,.CodeMirror-sizer,.CodeMirror-gutter,.CodeMirror-gutters,.CodeMirror-linenumber{-moz-box-sizing:content-box;box-sizing:content-box}.CodeMirror-measure{position:absolute;width:100%;height:0;overflow:hidden;visibility:hidden}.CodeMirror-cursor{position:absolute;pointer-events:none}.CodeMirror-measure pre{position:static}div.CodeMirror-cursors{visibility:hidden;position:relative;z-index:3}div.CodeMirror-dragcursors{visibility:visible}.CodeMirror-focused div.CodeMirror-cursors{visibility:visible}.CodeMirror-selected{background:#d9d9d9}.CodeMirror-focused .CodeMirror-selected{background:#d7d4f0}.CodeMirror-crosshair{cursor:crosshair}.CodeMirror-line::selection,.CodeMirror-line>span::selection,.CodeMirror-line>span>span::selection{background:#d7d4f0}.CodeMirror-line::-moz-selection,.CodeMirror-line>span::-moz-selection,.CodeMirror-line>span>span::-moz-selection{background:#d7d4f0}.cm-searching{background-color:#ffa;background-color:rgba(255, 255, 0, 0.4)}.cm-force-border{padding-right:.1px}@media print{.CodeMirror div.CodeMirror-cursors{visibility:hidden}}.cm-tab-wrap-hack:after{content:""}span.CodeMirror-selectedtext{background:none}.cm-s-hopscotch.CodeMirror{background:#322931;color:#d5d3d5}.cm-s-hopscotch div.CodeMirror-selected{background:#433b42 !important}.cm-s-hopscotch .CodeMirror-gutters{background:#322931;border-right:0px}.cm-s-hopscotch .CodeMirror-linenumber{color:#797379}.cm-s-hopscotch .CodeMirror-cursor{border-left:1px solid #989498 !important}.cm-s-hopscotch span.cm-comment{color:#b33508}.cm-s-hopscotch span.cm-atom{color:#c85e7c}.cm-s-hopscotch span.cm-number{color:#c85e7c}.cm-s-hopscotch span.cm-property,.cm-s-hopscotch span.cm-attribute{color:#8fc13e}.cm-s-hopscotch span.cm-keyword{color:#dd464c}.cm-s-hopscotch span.cm-string{color:#fdcc59}.cm-s-hopscotch span.cm-variable{color:#8fc13e}.cm-s-hopscotch span.cm-variable-2{color:#1290bf}.cm-s-hopscotch span.cm-def{color:#fd8b19}.cm-s-hopscotch span.cm-error{background:#dd464c;color:#989498}.cm-s-hopscotch span.cm-bracket{color:#d5d3d5}.cm-s-hopscotch span.cm-tag{color:#dd464c}.cm-s-hopscotch span.cm-link{color:#c85e7c}.cm-s-hopscotch .CodeMirror-matchingbracket{text-decoration:underline;color:white !important}.cm-s-hopscotch .CodeMirror-activeline-background{background:#302020}.gjs-is__grab,.gjs-is__grab *{cursor:grab !important}.gjs-is__grabbing,.gjs-is__grabbing *{-moz-user-select:none;-khtml-user-select:none;-webkit-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;cursor:grabbing !important}:root{--gjs-main-color: #444;--gjs-primary-color: #444;--gjs-secondary-color: #ddd;--gjs-tertiary-color: #804f7b;--gjs-quaternary-color: #d278c9;--gjs-font-color: #ddd;--gjs-font-color-active: #f8f8f8;--gjs-main-dark-color: rgba(0, 0, 0, 0.2);--gjs-secondary-dark-color: rgba(0, 0, 0, 0.1);--gjs-main-light-color: rgba(255, 255, 255, 0.1);--gjs-secondary-light-color: rgba(255, 255, 255, 0.7);--gjs-soft-light-color: rgba(255, 255, 255, 0.015);--gjs-color-blue: #3b97e3;--gjs-color-red: #dd3636;--gjs-color-yellow: #ffca6f;--gjs-color-green: #62c462;--gjs-left-width: 15%;--gjs-color-highlight: #71b7f1;--gjs-color-warn: #ffca6f;--gjs-handle-margin: -5px;--gjs-light-border: rgba(255, 255, 255, 0.05);--gjs-arrow-color: rgba(255, 255, 255, 0.7);--gjs-dark-text-shadow: rgba(0, 0, 0, 0.2);--gjs-color-input-padding: 22px;--gjs-input-padding: 5px;--gjs-padding-elem-classmanager: 5px 6px;--gjs-upload-padding: 150px 10px;--gjs-animation-duration: 0.2s;--gjs-main-font: Helvetica, sans-serif;--gjs-font-size: 0.75rem;--gjs-placeholder-background-color: var(--gjs-color-green);--gjs-canvas-top: 40px;--gjs-flex-item-gap: 5px}.gjs-bg-main,.gjs-off-prv,.gjs-sm-colorp-c{background-color:var(--gjs-main-color)}.gjs-color-main,.gjs-off-prv,.gjs-sm-stack #gjs-sm-add{color:var(--gjs-font-color);fill:var(--gjs-font-color)}.gjs-color-active{color:var(--gjs-font-color-active);fill:var(--gjs-font-color-active)}.gjs-color-warn{color:var(--gjs-color-warn);fill:var(--gjs-color-warn)}.gjs-color-hl{color:var(--gjs-color-highlight);fill:var(--gjs-color-highlight)}.gjs-invis-invis,.gjs-clm-tags #gjs-clm-new,.gjs-no-app{background-color:rgba(0,0,0,0);border:none;color:inherit}.gjs-no-app{height:10px}.opac50{opacity:.5;filter:alpha(opacity=50)}.gjs-checker-bg,.gjs-field-colorp-c,.checker-bg,.gjs-sm-layer-preview{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==")}.gjs-no-user-select,.gjs-grabbing,.gjs-grabbing *,.gjs-rte-toolbar,.gjs-layer-name{-moz-user-select:none;-khtml-user-select:none;-webkit-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none}.gjs-no-pointer-events,.gjs-resizer-c,.gjs-margin-v-el,.gjs-padding-v-el,.gjs-fixedmargin-v-el,.gjs-fixedpadding-v-el{pointer-events:none}.no-select,.gjs-clm-tags #gjs-clm-close,.gjs-com-no-select,.gjs-com-no-select img,.gjs-category-title,.gjs-layer-title,.gjs-block-category .gjs-title,.gjs-sm-sector-title,.gjs-trait-category .gjs-title{-moz-user-select:none;-khtml-user-select:none;-webkit-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none}.clear{clear:both}.gjs-category-open,.gjs-block-category.gjs-open,.gjs-sm-sector.gjs-sm-open,.gjs-trait-category.gjs-open{border-bottom:1px solid rgba(0,0,0,.25)}.gjs-category-title,.gjs-layer-title,.gjs-block-category .gjs-title,.gjs-sm-sector-title,.gjs-trait-category .gjs-title{font-weight:lighter;background-color:var(--gjs-secondary-dark-color);letter-spacing:1px;padding:9px 10px 9px 20px;border-bottom:1px solid rgba(0,0,0,.25);text-align:left;position:relative;cursor:pointer}.btn-cl,.gjs-am-close,.gjs-mdl-btn-close{opacity:.3;filter:alpha(opacity=30);font-size:25px;cursor:pointer}.btn-cl:hover,.gjs-am-close:hover,.gjs-mdl-btn-close:hover{opacity:.7;filter:alpha(opacity=70)}.gjs-traits-label{border-bottom:1px solid var(--gjs-main-dark-color);font-weight:lighter;margin-bottom:5px;padding:10px;text-align:left}.gjs-label-wrp{width:30%;min-width:30%}.gjs-field-wrp{flex-grow:1}.gjs-traits-c,.gjs-traits-cs{display:flex;flex-direction:column}.gjs-trait-categories{display:flex;flex-direction:column}.gjs-trait-category{width:100%}.gjs-trait-category .gjs-caret-icon{margin-right:5px}.gjs-trt-header{font-weight:lighter;padding:10px}.gjs-trt-trait{display:flex;justify-content:flex-start;padding:5px 10px;font-weight:lighter;align-items:center;text-align:left;gap:5px}.gjs-trt-traits{font-size:var(--gjs-font-size)}.gjs-trt-trait .gjs-label{text-align:left;text-overflow:ellipsis;overflow:hidden}.gjs-guide-info{position:absolute}.gjs-guide-info__content{position:absolute;height:100%;display:flex;width:100%;padding:5px}.gjs-guide-info__line{position:relative;margin:auto}.gjs-guide-info__line::before,.gjs-guide-info__line::after{content:"";display:block;position:absolute;background-color:inherit}.gjs-guide-info__y{padding:0 5px}.gjs-guide-info__y .gjs-guide-info__content{justify-content:center}.gjs-guide-info__y .gjs-guide-info__line{width:100%;height:1px}.gjs-guide-info__y .gjs-guide-info__line::before,.gjs-guide-info__y .gjs-guide-info__line::after{width:1px;height:10px;top:0;bottom:0;left:0;margin:auto}.gjs-guide-info__y .gjs-guide-info__line::after{left:auto;right:0}.gjs-guide-info__x{padding:5px 0}.gjs-guide-info__x .gjs-guide-info__content{align-items:center}.gjs-guide-info__x .gjs-guide-info__line{height:100%;width:1px}.gjs-guide-info__x .gjs-guide-info__line::before,.gjs-guide-info__x .gjs-guide-info__line::after{width:10px;height:1px;left:0;right:0;top:0;margin:auto;transform:translateX(-50%)}.gjs-guide-info__x .gjs-guide-info__line::after{top:auto;bottom:0}.gjs-badge{white-space:nowrap}.gjs-badge__icon{vertical-align:middle;display:inline-block;width:15px;height:15px}.gjs-badge__icon svg{fill:currentColor}.gjs-badge__name{display:inline-block;vertical-align:middle}.gjs-frame-wrapper{position:absolute;width:100%;height:100%;left:0;right:0;margin:auto}.gjs-frame-wrapper--anim{transition:width .35s ease,height .35s ease}.gjs-frame-wrapper__top{transform:translateY(-100%) translateX(-50%);display:flex;padding:5px 0;position:absolute;width:100%;left:50%;top:0}.gjs-frame-wrapper__top-r{margin-left:auto}.gjs-frame-wrapper__left{position:absolute;left:0;transform:translateX(-100%) translateY(-50%);height:100%;top:50%}.gjs-frame-wrapper__bottom{position:absolute;bottom:0;transform:translateY(100%) translateX(-50%);width:100%;left:50%}.gjs-frame-wrapper__right{position:absolute;right:0;transform:translateX(100%) translateY(-50%);height:100%;top:50%}.gjs-frame-wrapper__icon{width:24px;cursor:pointer}.gjs-frame-wrapper__icon>svg{fill:currentColor}.gjs-padding-v-top,.gjs-fixedpadding-v-top{width:100%;top:0;left:0}.gjs-padding-v-right,.gjs-fixedpadding-v-right{right:0}.gjs-padding-v-bottom,.gjs-fixedpadding-v-bottom{width:100%;left:0;bottom:0}.gjs-padding-v-left,.gjs-fixedpadding-v-left{left:0}.gjs-cv-canvas{box-sizing:border-box;width:calc(100% - var(--gjs-left-width));height:calc(100% - var(--gjs-canvas-top));bottom:0;overflow:hidden;z-index:1;position:absolute;left:0;top:var(--gjs-canvas-top)}.gjs-cv-canvas-bg{background-color:rgba(0,0,0,.15)}.gjs-cv-canvas.gjs-cui{width:100%;height:100%;top:0}.gjs-cv-canvas.gjs-is__grab .gjs-cv-canvas__frames,.gjs-cv-canvas.gjs-is__grabbing .gjs-cv-canvas__frames{pointer-events:none}.gjs-cv-canvas__frames{position:absolute;top:0;left:0;width:100%;height:100%}.gjs-cv-canvas__spots{position:absolute;pointer-events:none;z-index:1}.gjs-cv-canvas .gjs-ghost{display:none;pointer-events:none;background-color:#5b5b5b;border:2px dashed #ccc;position:absolute;z-index:10;opacity:.55;filter:alpha(opacity=55)}.gjs-cv-canvas .gjs-highlighter,.gjs-cv-canvas .gjs-highlighter-sel{position:absolute;outline:1px solid var(--gjs-color-blue);outline-offset:-1px;pointer-events:none;width:100%;height:100%}.gjs-cv-canvas .gjs-highlighter-warning{outline:3px solid var(--gjs-color-yellow)}.gjs-cv-canvas .gjs-highlighter-sel{outline:2px solid var(--gjs-color-blue);outline-offset:-2px}.gjs-cv-canvas #gjs-tools,.gjs-cv-canvas .gjs-tools{width:100%;height:100%;position:absolute;top:0;left:0;outline:none;z-index:1}.gjs-cv-canvas #gjs-tools{z-index:2}.gjs-cv-canvas *{box-sizing:border-box}.gjs-frame{outline:medium none;height:100%;width:100%;border:none;margin:auto;display:block;transition:width .35s ease,height .35s ease;position:absolute;top:0;bottom:0;left:0;right:0}.gjs-toolbar{position:absolute;background-color:var(--gjs-color-blue);white-space:nowrap;color:#fff;z-index:10;top:0;left:0}.gjs-toolbar-item{width:26px;padding:5px;cursor:pointer;display:inline-block}.gjs-toolbar-item svg{fill:currentColor;vertical-align:middle}.gjs-resizer-c{position:absolute;left:0;top:0;width:100%;height:100%;z-index:9}.gjs-margin-v-el,.gjs-padding-v-el,.gjs-fixedmargin-v-el,.gjs-fixedpadding-v-el{opacity:.1;filter:alpha(opacity=10);position:absolute;background-color:#ff0}.gjs-fixedmargin-v-el,.gjs-fixedpadding-v-el{opacity:.2;filter:alpha(opacity=20)}.gjs-padding-v-el,.gjs-fixedpadding-v-el{background-color:navy}.gjs-resizer-h{pointer-events:all;position:absolute;border:3px solid var(--gjs-color-blue);width:10px;height:10px;background-color:#fff;margin:var(--gjs-handle-margin)}.gjs-resizer-h-tl{top:0;left:0;cursor:nwse-resize}.gjs-resizer-h-tr{top:0;right:0;cursor:nesw-resize}.gjs-resizer-h-tc{top:0;margin:var(--gjs-handle-margin) auto;left:0;right:0;cursor:ns-resize}.gjs-resizer-h-cl{left:0;margin:auto var(--gjs-handle-margin);top:0;bottom:0;cursor:ew-resize}.gjs-resizer-h-cr{margin:auto var(--gjs-handle-margin);top:0;bottom:0;right:0;cursor:ew-resize}.gjs-resizer-h-bl{bottom:0;left:0;cursor:nesw-resize}.gjs-resizer-h-bc{bottom:0;margin:var(--gjs-handle-margin) auto;left:0;right:0;cursor:ns-resize}.gjs-resizer-h-br{bottom:0;right:0;cursor:nwse-resize}.gjs-pn-panel .gjs-resizer-h{background-color:rgba(0,0,0,.2);border:none;opacity:0;transition:opacity .25s}.gjs-pn-panel .gjs-resizer-h:hover{opacity:1}.gjs-pn-panel .gjs-resizer-h-tc,.gjs-pn-panel .gjs-resizer-h-bc{margin:0 auto;width:100%}.gjs-pn-panel .gjs-resizer-h-cr,.gjs-pn-panel .gjs-resizer-h-cl{margin:auto 0;height:100%}.gjs-resizing .gjs-highlighter,.gjs-resizing .gjs-badge{display:none !important}.gjs-resizing-tl *{cursor:nwse-resize !important}.gjs-resizing-tr *{cursor:nesw-resize !important}.gjs-resizing-tc *{cursor:ns-resize !important}.gjs-resizing-cl *{cursor:ew-resize !important}.gjs-resizing-cr *{cursor:ew-resize !important}.gjs-resizing-bl *{cursor:nesw-resize !important}.gjs-resizing-bc *{cursor:ns-resize !important}.gjs-resizing-br *{cursor:nwse-resize !important}.no-dots,.ui-resizable-handle{border:none !important;margin:0 !important;outline:none !important}.gjs-com-dashed *{outline:1px dashed #888;outline-offset:-2px;box-sizing:border-box}.gjs-com-badge,.gjs-badge{pointer-events:none;background-color:var(--gjs-color-blue);color:#fff;padding:2px 5px;position:absolute;z-index:1;font-size:12px;outline:none;display:none}.gjs-badge-warning{background-color:var(--gjs-color-yellow)}.gjs-placeholder,.gjs-com-placeholder,.gjs-placeholder{position:absolute;z-index:10;pointer-events:none;display:none}.gjs-placeholder,.gjs-placeholder{border-style:solid !important;outline:none;box-sizing:border-box;transition:top var(--gjs-animation-duration),left var(--gjs-animation-duration),width var(--gjs-animation-duration),height var(--gjs-animation-duration)}.gjs-placeholder.horizontal,.gjs-com-placeholder.horizontal,.gjs-placeholder.horizontal{border-color:rgba(0,0,0,0) var(--gjs-placeholder-background-color);border-width:3px 5px;margin:-3px 0 0}.gjs-placeholder.vertical,.gjs-com-placeholder.vertical,.gjs-placeholder.vertical{border-color:var(--gjs-placeholder-background-color) rgba(0,0,0,0);border-width:5px 3px;margin:0 0 0 -3px}.gjs-placeholder-int,.gjs-com-placeholder-int,.gjs-placeholder-int{background-color:var(--gjs-placeholder-background-color);box-shadow:0 0 3px rgba(0,0,0,.2);height:100%;width:100%;pointer-events:none;padding:1.5px;outline:none}.gjs-pn-panel{display:inline-block;position:absolute;box-sizing:border-box;text-align:center;padding:5px;z-index:3}.gjs-pn-panel .icon-undo,.gjs-pn-panel .icon-redo{font-size:20px;height:30px;width:25px}.gjs-pn-commands{width:calc(100% - var(--gjs-left-width));left:0;top:0;box-shadow:0 0 5px var(--gjs-main-dark-color)}.gjs-pn-options{right:var(--gjs-left-width);top:0}.gjs-pn-views{border-bottom:2px solid var(--gjs-main-dark-color);right:0;width:var(--gjs-left-width);z-index:4}.gjs-pn-views-container{height:100%;padding:42px 0 0;right:0;width:var(--gjs-left-width);overflow:auto;box-shadow:0 0 5px var(--gjs-main-dark-color)}.gjs-pn-buttons{align-items:center;display:flex;justify-content:space-between}.gjs-pn-btn{box-sizing:border-box;min-height:30px;min-width:30px;line-height:21px;background-color:rgba(0,0,0,0);border:none;font-size:18px;margin-right:5px;border-radius:2px;padding:4px;position:relative;cursor:pointer}.gjs-pn-btn.gjs-pn-active{background-color:rgba(0,0,0,.15);box-shadow:0 0 3px rgba(0,0,0,.25) inset}.gjs-pn-btn svg{fill:currentColor}.gjs-label{line-height:18px}.gjs-fields{display:flex}.gjs-select{padding:0;width:100%}.gjs-select select{padding-right:10px}.gjs-select:-moz-focusring,.gjs-select select:-moz-focusring{color:rgba(0,0,0,0);text-shadow:0 0 0 var(--gjs-secondary-light-color)}.gjs-input:focus,.gjs-button:focus,.gjs-btn-prim:focus,.gjs-select:focus,.gjs-select select:focus{outline:none}.gjs-field input,.gjs-field select,.gjs-field textarea{-webkit-appearance:none;-moz-appearance:none;appearance:none;color:inherit;border:none;background-color:rgba(0,0,0,0);box-sizing:border-box;width:100%;position:relative;padding:var(--gjs-input-padding);z-index:1}.gjs-field input:focus,.gjs-field select:focus,.gjs-field textarea:focus{outline:none}.gjs-field input[type=number]{-moz-appearance:textfield}.gjs-field input[type=number]::-webkit-outer-spin-button,.gjs-field input[type=number]::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}.gjs-field-range{flex:9 1 auto}.gjs-field-integer input{padding-right:30px}.gjs-select option,.gjs-field-select option,.gjs-clm-select option,.gjs-sm-select option,.gjs-fields option,.gjs-sm-unit option{background-color:var(--gjs-main-color);color:var(--gjs-font-color)}.gjs-field{background-color:var(--gjs-main-dark-color);border:none;box-shadow:none;border-radius:2px;box-sizing:border-box;padding:0;position:relative}.gjs-field textarea{resize:vertical}.gjs-field .gjs-sel-arrow{height:100%;width:9px;position:absolute;right:0;top:0;z-index:0}.gjs-field .gjs-d-s-arrow{bottom:0;top:0;margin:auto;right:var(--gjs-input-padding);border-top:4px solid var(--gjs-arrow-color);position:absolute;height:0;width:0;border-left:3px solid rgba(0,0,0,0);border-right:4px solid rgba(0,0,0,0);cursor:pointer}.gjs-field-arrows{position:absolute;cursor:ns-resize;margin:auto;height:20px;width:9px;z-index:10;bottom:0;right:calc(var(--gjs-input-padding) - 2px);top:0}.gjs-field-color,.gjs-field-radio{width:100%}.gjs-field-color input{padding-right:var(--gjs-color-input-padding);box-sizing:border-box}.gjs-field-colorp{border-left:1px solid var(--gjs-main-dark-color);box-sizing:border-box;height:100%;padding:2px;position:absolute;right:0;top:0;width:var(--gjs-color-input-padding);z-index:10}.gjs-field-colorp .gjs-checker-bg,.gjs-field-colorp .gjs-field-colorp-c{height:100%;width:100%;border-radius:1px}.gjs-field-colorp-c{height:100%;position:relative;width:100%}.gjs-field-color-picker{background-color:var(--gjs-font-color);cursor:pointer;height:100%;width:100%;box-shadow:0 0 1px var(--gjs-main-dark-color);border-radius:1px;position:absolute;top:0}.gjs-field-checkbox{padding:0;width:17px;height:17px;display:block;cursor:pointer}.gjs-field-checkbox input{display:none}.gjs-field-checkbox input:checked+.gjs-chk-icon{border-color:hsla(0,0%,100%,.5);border-width:0 2px 2px 0;border-style:solid}.gjs-radio-item{flex:1 1 auto;text-align:center;border-left:1px solid var(--gjs-dark-text-shadow)}.gjs-radio-item:first-child{border:none}.gjs-radio-item:hover{background:var(--gjs-main-dark-color)}.gjs-radio-item input{display:none}.gjs-radio-item input:checked+.gjs-radio-item-label{background-color:hsla(0,0%,100%,.2)}.gjs-radio-items{display:flex}.gjs-radio-item-label{cursor:pointer;display:block;padding:var(--gjs-input-padding)}.gjs-field-units{position:absolute;margin:auto;right:10px;bottom:0;top:0}.gjs-field-unit{position:absolute;right:10px;top:3px;font-size:10px;color:var(--gjs-arrow-color);cursor:pointer}.gjs-input-unit{text-align:center}.gjs-field-arrow-u,.gjs-field-arrow-d{position:absolute;height:0;width:0;border-left:3px solid rgba(0,0,0,0);border-right:4px solid rgba(0,0,0,0);border-top:4px solid var(--gjs-arrow-color);bottom:4px;cursor:pointer}.gjs-field-arrow-u{border-bottom:4px solid var(--gjs-arrow-color);border-top:none;top:4px}.gjs-field-select{padding:0}.gjs-field-range{background-color:rgba(0,0,0,0);border:none;box-shadow:none;padding:0}.gjs-field-range input{margin:0;height:100%}.gjs-field-range input:focus{outline:none}.gjs-field-range input::-webkit-slider-thumb{-webkit-appearance:none;margin-top:-4px;height:10px;width:10px;border:1px solid var(--gjs-main-dark-color);border-radius:100%;background-color:var(--gjs-font-color);cursor:pointer}.gjs-field-range input::-moz-range-thumb{height:10px;width:10px;border:1px solid var(--gjs-main-dark-color);border-radius:100%;background-color:var(--gjs-font-color);cursor:pointer}.gjs-field-range input::-ms-thumb{height:10px;width:10px;border:1px solid var(--gjs-main-dark-color);border-radius:100%;background-color:var(--gjs-font-color);cursor:pointer}.gjs-field-range input::-moz-range-track{background-color:var(--gjs-main-dark-color);border-radius:1px;margin-top:3px;height:3px}.gjs-field-range input::-webkit-slider-runnable-track{background-color:var(--gjs-main-dark-color);border-radius:1px;margin-top:3px;height:3px}.gjs-field-range input::-ms-track{background-color:var(--gjs-main-dark-color);border-radius:1px;margin-top:3px;height:3px}.gjs-btn-prim{color:inherit;background-color:var(--gjs-main-light-color);border-radius:2px;padding:3px 6px;padding:var(--gjs-input-padding);cursor:pointer;border:none}.gjs-btn-prim:active{background-color:var(--gjs-main-light-color)}.gjs-btn--full{width:100%}.gjs-chk-icon{-ms-transform:rotate(45deg);-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);transform:rotate(45deg);box-sizing:border-box;display:block;height:14px;margin:0 5px;width:6px}.gjs-add-trasp{background:none;border:none;color:var(--gjs-font-color);cursor:pointer;font-size:1em;border-radius:2px;opacity:.75;filter:alpha(opacity=75)}.gjs-add-trasp:hover{opacity:1;filter:alpha(opacity=100)}.gjs-add-trasp:active{background-color:rgba(0,0,0,.2)}.gjs-devices-c{display:flex;align-items:center;padding:2px 3px 3px 3px}.gjs-devices-c .gjs-device-label{flex-grow:2;text-align:left;margin-right:10px}.gjs-devices-c .gjs-select{flex-grow:20}.gjs-devices-c .gjs-add-trasp{flex-grow:1;margin-left:5px}.gjs-sm-clear{cursor:pointer;width:14px;min-width:14px;height:14px;margin-left:3px}.gjs-sm-header{font-weight:lighter;padding:10px}.gjs-sm-sector{clear:both;font-weight:lighter;text-align:left}.gjs-sm-sector-title{display:flex;align-items:center}.gjs-sm-sector-caret{width:17px;height:17px;min-width:17px;transform:rotate(-90deg)}.gjs-sm-sector-label{margin-left:5px}.gjs-sm-sector.gjs-sm-open .gjs-sm-sector-caret{transform:none}.gjs-sm-properties{font-size:var(--gjs-font-size);padding:10px 5px;display:flex;flex-wrap:wrap;align-items:flex-end;box-sizing:border-box;width:100%}.gjs-sm-label{margin:5px 5px 3px 0;display:flex;align-items:center}.gjs-sm-close-btn,.gjs-sm-preview-file-close{display:block;font-size:23px;position:absolute;cursor:pointer;right:5px;top:0;opacity:.7;filter:alpha(opacity=70)}.gjs-sm-close-btn:hover,.gjs-sm-preview-file-close:hover{opacity:.9;filter:alpha(opacity=90)}.gjs-sm-field,.gjs-clm-field,.gjs-clm-select{width:100%;position:relative}.gjs-sm-field input,.gjs-clm-field input,.gjs-clm-select input,.gjs-sm-field select,.gjs-clm-field select,.gjs-clm-select select{background-color:rgba(0,0,0,0);color:hsla(0,0%,100%,.7);border:none;width:100%}.gjs-sm-field input,.gjs-clm-field input,.gjs-clm-select input{box-sizing:border-box}.gjs-sm-field select,.gjs-clm-field select,.gjs-clm-select select{position:relative;z-index:1;-webkit-appearance:none;-moz-appearance:none;appearance:none}.gjs-sm-field select::-ms-expand,.gjs-clm-field select::-ms-expand,.gjs-clm-select select::-ms-expand{display:none}.gjs-sm-field select:-moz-focusring,.gjs-clm-field select:-moz-focusring,.gjs-clm-select select:-moz-focusring{color:rgba(0,0,0,0);text-shadow:0 0 0 var(--gjs-secondary-light-color)}.gjs-sm-field input:focus,.gjs-clm-field input:focus,.gjs-clm-select input:focus,.gjs-sm-field select:focus,.gjs-clm-field select:focus,.gjs-clm-select select:focus{outline:none}.gjs-sm-field .gjs-sm-unit,.gjs-clm-field .gjs-sm-unit,.gjs-clm-select .gjs-sm-unit{position:absolute;right:10px;top:3px;font-size:10px;color:var(--gjs-secondary-light-color);cursor:pointer}.gjs-sm-field .gjs-clm-sel-arrow,.gjs-clm-field .gjs-clm-sel-arrow,.gjs-clm-select .gjs-clm-sel-arrow,.gjs-sm-field .gjs-sm-int-arrows,.gjs-clm-field .gjs-sm-int-arrows,.gjs-clm-select .gjs-sm-int-arrows,.gjs-sm-field .gjs-sm-sel-arrow,.gjs-clm-field .gjs-sm-sel-arrow,.gjs-clm-select .gjs-sm-sel-arrow{height:100%;width:9px;position:absolute;right:0;top:0;cursor:ns-resize}.gjs-sm-field .gjs-sm-sel-arrow,.gjs-clm-field .gjs-sm-sel-arrow,.gjs-clm-select .gjs-sm-sel-arrow{cursor:pointer}.gjs-sm-field .gjs-clm-d-s-arrow,.gjs-clm-field .gjs-clm-d-s-arrow,.gjs-clm-select .gjs-clm-d-s-arrow,.gjs-sm-field .gjs-sm-d-arrow,.gjs-clm-field .gjs-sm-d-arrow,.gjs-clm-select .gjs-sm-d-arrow,.gjs-sm-field .gjs-sm-d-s-arrow,.gjs-clm-field .gjs-sm-d-s-arrow,.gjs-clm-select .gjs-sm-d-s-arrow,.gjs-sm-field .gjs-sm-u-arrow,.gjs-clm-field .gjs-sm-u-arrow,.gjs-clm-select .gjs-sm-u-arrow{position:absolute;height:0;width:0;border-left:3px solid rgba(0,0,0,0);border-right:4px solid rgba(0,0,0,0);cursor:pointer}.gjs-sm-field .gjs-sm-u-arrow,.gjs-clm-field .gjs-sm-u-arrow,.gjs-clm-select .gjs-sm-u-arrow{border-bottom:4px solid var(--gjs-secondary-light-color);top:4px}.gjs-sm-field .gjs-clm-d-s-arrow,.gjs-clm-field .gjs-clm-d-s-arrow,.gjs-clm-select .gjs-clm-d-s-arrow,.gjs-sm-field .gjs-sm-d-arrow,.gjs-clm-field .gjs-sm-d-arrow,.gjs-clm-select .gjs-sm-d-arrow,.gjs-sm-field .gjs-sm-d-s-arrow,.gjs-clm-field .gjs-sm-d-s-arrow,.gjs-clm-select .gjs-sm-d-s-arrow{border-top:4px solid var(--gjs-secondary-light-color);bottom:4px}.gjs-sm-field .gjs-clm-d-s-arrow,.gjs-clm-field .gjs-clm-d-s-arrow,.gjs-clm-select .gjs-clm-d-s-arrow,.gjs-sm-field .gjs-sm-d-s-arrow,.gjs-clm-field .gjs-sm-d-s-arrow,.gjs-clm-select .gjs-sm-d-s-arrow{bottom:7px}.gjs-sm-field.gjs-sm-color,.gjs-sm-color.gjs-clm-field,.gjs-sm-field.gjs-sm-input,.gjs-sm-input.gjs-clm-field,.gjs-sm-field.gjs-sm-integer,.gjs-sm-integer.gjs-clm-field,.gjs-sm-field.gjs-sm-list,.gjs-sm-list.gjs-clm-field,.gjs-sm-field.gjs-sm-select,.gjs-sm-select.gjs-clm-field,.gjs-clm-select{background-color:var(--gjs-main-dark-color);border:1px solid rgba(0,0,0,.1);box-shadow:1px 1px 0 var(--gjs-main-light-color);color:var(--gjs-secondary-light-color);border-radius:2px;box-sizing:border-box;padding:0 5px}.gjs-sm-field.gjs-sm-composite,.gjs-sm-composite.gjs-clm-field,.gjs-sm-composite.gjs-clm-select{border-radius:2px}.gjs-sm-field.gjs-sm-select,.gjs-sm-select.gjs-clm-field,.gjs-clm-select{padding:0}.gjs-sm-field.gjs-sm-select select,.gjs-sm-select.gjs-clm-field select,.gjs-clm-select select{height:20px}.gjs-sm-field.gjs-sm-select option,.gjs-sm-select.gjs-clm-field option,.gjs-clm-select option{padding:3px 0}.gjs-sm-field.gjs-sm-composite,.gjs-sm-composite.gjs-clm-field,.gjs-sm-composite.gjs-clm-select{background-color:var(--gjs-secondary-dark-color);border:1px solid rgba(0,0,0,.25)}.gjs-sm-field.gjs-sm-list,.gjs-sm-list.gjs-clm-field,.gjs-sm-list.gjs-clm-select{width:auto;padding:0;overflow:hidden;float:left}.gjs-sm-field.gjs-sm-list input,.gjs-sm-list.gjs-clm-field input,.gjs-sm-list.gjs-clm-select input{display:none}.gjs-sm-field.gjs-sm-list label,.gjs-sm-list.gjs-clm-field label,.gjs-sm-list.gjs-clm-select label{cursor:pointer;padding:5px;display:block}.gjs-sm-field.gjs-sm-list .gjs-sm-radio:checked+label,.gjs-sm-list.gjs-clm-field .gjs-sm-radio:checked+label,.gjs-sm-list.gjs-clm-select .gjs-sm-radio:checked+label{background-color:hsla(0,0%,100%,.2)}.gjs-sm-field.gjs-sm-list .gjs-sm-icon,.gjs-sm-list.gjs-clm-field .gjs-sm-icon,.gjs-sm-list.gjs-clm-select .gjs-sm-icon{background-repeat:no-repeat;background-position:center;text-shadow:none;line-height:normal}.gjs-sm-field.gjs-sm-integer select,.gjs-sm-integer.gjs-clm-field select,.gjs-sm-integer.gjs-clm-select select{width:auto;padding:0}.gjs-sm-list .gjs-sm-el{float:left;border-left:1px solid var(--gjs-main-dark-color)}.gjs-sm-list .gjs-sm-el:first-child{border:none}.gjs-sm-list .gjs-sm-el:hover{background:var(--gjs-main-dark-color)}.gjs-sm-slider .gjs-field-integer{flex:1 1 65px}.gjs-sm-property{box-sizing:border-box;float:left;width:50%;margin-bottom:5px;padding:0 5px}.gjs-sm-property--full,.gjs-sm-property.gjs-sm-composite,.gjs-sm-property.gjs-sm-file,.gjs-sm-property.gjs-sm-list,.gjs-sm-property.gjs-sm-stack,.gjs-sm-property.gjs-sm-slider,.gjs-sm-property.gjs-sm-color{width:100%}.gjs-sm-property .gjs-sm-btn{background-color:color-mix(in srgb, var(--gjs-main-dark-color), white 13%);border-radius:2px;box-shadow:1px 1px 0 color-mix(in srgb, var(--gjs-main-dark-color), white 2%),1px 1px 0 color-mix(in srgb, var(--gjs-main-dark-color), white 17%) inset;padding:5px;position:relative;text-align:center;height:auto;width:100%;cursor:pointer;color:var(--gjs-font-color);box-sizing:border-box;text-shadow:-1px -1px 0 var(--gjs-main-dark-color);border:none;opacity:.85;filter:alpha(opacity=85)}.gjs-sm-property .gjs-sm-btn-c{box-sizing:border-box;float:left;width:100%}.gjs-sm-property__text-shadow .gjs-sm-layer-preview-cnt::after{color:#000;content:"T";font-weight:900;line-height:17px;padding:0 4px}.gjs-sm-preview-file{background-color:var(--gjs-light-border);border-radius:2px;margin-top:5px;position:relative;overflow:hidden;border:1px solid color-mix(in srgb, var(--gjs-light-border), black 1%);padding:3px 20px}.gjs-sm-preview-file-cnt{background-size:auto 100%;background-repeat:no-repeat;background-position:center center;height:50px}.gjs-sm-preview-file-close{top:-5px;width:14px;height:14px}.gjs-sm-layers{margin-top:5px;padding:1px 3px;min-height:30px}.gjs-sm-layer{background-color:hsla(0,0%,100%,.055);border-radius:2px;margin:2px 0;padding:7px;position:relative}.gjs-sm-layer.gjs-sm-active{background-color:hsla(0,0%,100%,.12)}.gjs-sm-layer .gjs-sm-label-wrp{display:flex;align-items:center}.gjs-sm-layer #gjs-sm-move{height:14px;width:14px;min-width:14px;cursor:grab}.gjs-sm-layer #gjs-sm-label{flex-grow:1;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;margin:0 5px}.gjs-sm-layer-preview{height:15px;width:15px;min-width:15px;margin-right:5px;border-radius:2px}.gjs-sm-layer-preview-cnt{border-radius:2px;background-color:#fff;height:100%;width:100%;background-size:cover !important}.gjs-sm-layer #gjs-sm-close-layer{display:block;cursor:pointer;height:14px;width:14px;min-width:14px;opacity:.5;filter:alpha(opacity=50)}.gjs-sm-layer #gjs-sm-close-layer:hover{opacity:.8;filter:alpha(opacity=80)}.gjs-sm-stack .gjs-sm-properties{padding:5px 0 0}.gjs-sm-stack #gjs-sm-add{background:none;border:none;cursor:pointer;outline:none;position:absolute;right:0;top:-17px;opacity:.75;padding:0;width:18px;height:18px}.gjs-sm-stack #gjs-sm-add:hover{opacity:1;filter:alpha(opacity=100)}.gjs-sm-colorp-c{height:100%;width:20px;position:absolute;right:0;top:0;box-sizing:border-box;border-radius:2px;padding:2px}.gjs-sm-colorp-c .gjs-field-colorp-c,.gjs-sm-colorp-c .gjs-checker-bg{height:100%;width:100%;border-radius:1px}.gjs-sm-color-picker{background-color:var(--gjs-font-color);cursor:pointer;height:16px;width:100%;margin-top:-16px;box-shadow:0 0 1px var(--gjs-main-dark-color);border-radius:1px}.gjs-sm-btn-upload #gjs-sm-upload{left:0;top:0;position:absolute;width:100%;opacity:0;cursor:pointer}.gjs-sm-btn-upload #gjs-sm-label{padding:2px 0}.gjs-sm-layer>#gjs-sm-move{opacity:.7;filter:alpha(opacity=70);cursor:move;font-size:12px;float:left;margin:0 5px 0 0}.gjs-sm-layer>#gjs-sm-move:hover{opacity:.9;filter:alpha(opacity=90)}.gjs-blocks-c{display:flex;flex-wrap:wrap;justify-content:flex-start}.gjs-block-categories{display:flex;flex-direction:column}.gjs-block-category{width:100%}.gjs-block-category .gjs-caret-icon{margin-right:5px}.gjs-block{-moz-user-select:none;-khtml-user-select:none;-webkit-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;width:45%;min-width:45px;padding:1em;box-sizing:border-box;min-height:90px;cursor:all-scroll;font-size:11px;font-weight:lighter;text-align:center;display:flex;flex-direction:column;justify-content:space-between;border:1px solid rgba(0,0,0,.2);border-radius:3px;margin:10px 2.5% 5px;box-shadow:0 1px 0 0 rgba(0,0,0,.15);transition:all .2s ease 0s;transition-property:box-shadow,color}.gjs-block:hover{box-shadow:0 3px 4px 0 rgba(0,0,0,.15)}.gjs-block svg{fill:currentColor}.gjs-block__media{margin-bottom:10px;pointer-events:none}.gjs-block-svg{width:54px;fill:currentColor}.gjs-block-svg-path{fill:currentColor}.gjs-block.fa{font-size:2em;line-height:2em;padding:11px}.gjs-block-label{line-height:normal;font-size:.65rem;font-weight:normal;font-family:Helvetica,sans-serif;overflow:hidden;text-overflow:ellipsis;pointer-events:none}.gjs-block.gjs-bdrag{width:auto;padding:0}.gjs-selected-parent{border:1px solid var(--gjs-color-yellow)}.gjs-opac50{opacity:.5;filter:alpha(opacity=50)}.gjs-layer{font-weight:lighter;text-align:left;position:relative;font-size:var(--gjs-font-size);display:grid}.gjs-layer-item{display:flex;align-items:center;justify-content:space-between;padding:5px 10px;border-bottom:1px solid var(--gjs-main-dark-color);background-color:var(--gjs-secondary-dark-color);gap:var(--gjs-flex-item-gap);cursor:pointer}.gjs-layer-item-left,.gjs-layer-item-right{display:flex;align-items:center;gap:var(--gjs-flex-item-gap)}.gjs-layer-item-left{width:100%}.gjs-layer-hidden{opacity:.55;filter:alpha(opacity=55)}.gjs-layer-vis{box-sizing:content-box;cursor:pointer;z-index:1}.gjs-layer-vis-on,.gjs-layer-vis-off{display:flex;width:13px;height:13px}.gjs-layer-vis-off{display:none}.gjs-layer-vis.gjs-layer-off .gjs-layer-vis-on{display:none}.gjs-layer-vis.gjs-layer-off .gjs-layer-vis-off{display:flex}.gjs-layer-caret{width:15px;height:15px;cursor:pointer;box-sizing:content-box;transform:rotate(90deg);display:flex;opacity:.7;filter:alpha(opacity=70)}.gjs-layer-caret:hover{opacity:1;filter:alpha(opacity=100)}.gjs-layer.open>.gjs-layer-item .gjs-layer-caret{transform:rotate(180deg)}.gjs-layer-title{padding:0;display:flex;align-items:center;background-color:rgba(0,0,0,0) !important;border-bottom:none}.gjs-layer-title-inn{align-items:center;position:relative;display:flex;gap:var(--gjs-flex-item-gap)}.gjs-layer-title-c{width:100%}.gjs-layer__icon{display:block;width:100%;max-width:15px;max-height:15px;padding-left:5px}.gjs-layer__icon svg{fill:currentColor}.gjs-layer-name{display:inline-block;box-sizing:content-box;overflow:hidden;white-space:nowrap;max-width:170px;height:auto}.gjs-layer-name--no-edit{text-overflow:ellipsis}.gjs-layer>.gjs-layer-children{display:none}.gjs-layer.open>.gjs-layer-children{display:block}.gjs-layer-no-chld>.gjs-layer-title-inn>.gjs-layer-caret{visibility:hidden}.gjs-layer-move{display:flex;width:13px;height:13px;box-sizing:content-box;cursor:move}.gjs-layer.gjs-hovered .gjs-layer-item{background-color:var(--gjs-soft-light-color)}.gjs-layer.gjs-selected .gjs-layer-item{background-color:var(--gjs-main-light-color)}.gjs-layers{position:relative;height:100%}.gjs-layers #gjs-placeholder{width:100%;position:absolute}.gjs-layers #gjs-placeholder #gjs-plh-int{height:100%;padding:1px}.gjs-layers #gjs-placeholder #gjs-plh-int.gjs-insert{background-color:var(--gjs-color-green)}#gjs-clm-add-tag,.gjs-clm-tags-btn{background-color:hsla(0,0%,100%,.15);border-radius:2px;padding:3px;margin-right:3px;border:1px solid rgba(0,0,0,.15);width:24px;height:24px;box-sizing:border-box;cursor:pointer}.gjs-clm-tags-btn svg{fill:currentColor;display:block}.gjs-clm-header{display:flex;align-items:center;margin:7px 0}.gjs-clm-header-status{flex-shrink:1;margin-left:auto}.gjs-clm-tag{display:flex;overflow:hidden;align-items:center;border-radius:3px;margin:0 3px 3px 0;padding:5px;cursor:default}.gjs-clm-tag-status,.gjs-clm-tag-close{width:12px;height:12px;flex-shrink:1}.gjs-clm-tag-status svg,.gjs-clm-tag-close svg{vertical-align:middle;fill:currentColor}.gjs-clm-sels-info{margin:7px 0;text-align:left}.gjs-clm-sel-id{font-size:.9em;opacity:.5;filter:alpha(opacity=50)}.gjs-clm-label-sel{float:left;padding-right:5px}.gjs-clm-tags{font-size:var(--gjs-font-size);padding:10px 5px}.gjs-clm-tags #gjs-clm-sel{padding:7px 0;float:left}.gjs-clm-tags #gjs-clm-sel{font-style:italic;margin-left:5px}.gjs-clm-tags #gjs-clm-tags-field{clear:both;padding:5px;margin-bottom:5px;display:flex;flex-wrap:wrap}.gjs-clm-tags #gjs-clm-tags-c{display:flex;flex-wrap:wrap;vertical-align:top;overflow:hidden}.gjs-clm-tags #gjs-clm-new{color:var(--gjs-font-color);padding:var(--gjs-padding-elem-classmanager);display:none}.gjs-clm-tags #gjs-clm-close{opacity:.85;filter:alpha(opacity=85);font-size:20px;line-height:0;cursor:pointer;color:hsla(0,0%,100%,.9)}.gjs-clm-tags #gjs-clm-close:hover{opacity:1;filter:alpha(opacity=100)}.gjs-clm-tags #gjs-clm-checkbox{color:hsla(0,0%,100%,.9);vertical-align:middle;cursor:pointer;font-size:9px}.gjs-clm-tags #gjs-clm-tag-label{flex-grow:1;text-overflow:ellipsis;overflow:hidden;padding:0 3px;cursor:text}.gjs-mdl-container{font-family:var(--gjs-main-font);overflow-y:auto;position:fixed;background-color:rgba(0,0,0,.5);display:flex;top:0;left:0;right:0;bottom:0;z-index:100}.gjs-mdl-dialog{text-shadow:-1px -1px 0 rgba(0,0,0,.05);animation:gjs-slide-down .215s;margin:auto;max-width:850px;width:90%;border-radius:3px;font-weight:lighter;position:relative;z-index:2}.gjs-mdl-title{font-size:1rem}.gjs-mdl-btn-close{position:absolute;right:15px;top:5px}.gjs-mdl-active .gjs-mdl-dialog{animation:gjs-mdl-slide-down .216s}.gjs-mdl-header,.gjs-mdl-content{padding:10px 15px;clear:both}.gjs-mdl-header{position:relative;border-bottom:1px solid var(--gjs-main-dark-color);padding:15px 15px 7px}.gjs-export-dl::after{content:"";clear:both;display:block;margin-bottom:10px}.gjs-dropzone{display:none;opacity:0;position:absolute;top:0;left:0;z-index:11;width:100%;height:100%;transition:opacity .25s;pointer-events:none}.gjs-dropzone-active .gjs-dropzone{display:block;opacity:1}.gjs-am-assets{height:290px;overflow:auto;clear:both;display:flex;flex-wrap:wrap;align-items:flex-start;align-content:flex-start}.gjs-am-assets-header{padding:5px}.gjs-am-add-asset .gjs-am-add-field{width:70%;float:left}.gjs-am-add-asset button{width:25%;float:right}.gjs-am-preview-cont{position:relative;height:70px;width:30%;background-color:var(--gjs-main-color);border-radius:2px;float:left;overflow:hidden}.gjs-am-preview{position:absolute;background-position:center center;background-size:cover;background-repeat:no-repeat;height:100%;width:100%;z-index:1}.gjs-am-preview-bg{opacity:.5;filter:alpha(opacity=50);position:absolute;height:100%;width:100%;z-index:0}.gjs-am-dimensions{opacity:.5;filter:alpha(opacity=50);font-size:10px}.gjs-am-meta{width:70%;float:left;font-size:12px;padding:5px 0 0 5px;box-sizing:border-box}.gjs-am-meta>div{margin-bottom:5px}.gjs-am-close{cursor:pointer;position:absolute;right:5px;top:0;display:none}.gjs-am-asset{border-bottom:1px solid color-mix(in srgb, var(--gjs-main-dark-color), black 3%);padding:5px;cursor:pointer;position:relative;box-sizing:border-box;width:100%}.gjs-am-asset:hover .gjs-am-close{display:block}.gjs-am-highlight{background-color:var(--gjs-main-light-color)}.gjs-am-assets-cont{background-color:var(--gjs-secondary-dark-color);border-radius:3px;box-sizing:border-box;padding:10px;width:45%;float:right;height:325px;overflow:hidden}.gjs-am-file-uploader{width:55%;float:left}.gjs-am-file-uploader>form{background-color:var(--gjs-secondary-dark-color);border:2px dashed;border-radius:3px;position:relative;text-align:center;margin-bottom:15px}.gjs-am-file-uploader>form.gjs-am-hover{border:2px solid var(--gjs-color-green);color:color-mix(in srgb, var(--gjs-color-green), white 5%)}.gjs-am-file-uploader>form.gjs-am-disabled{border-color:red}.gjs-am-file-uploader>form #gjs-am-uploadFile{opacity:0;filter:alpha(opacity=0);padding:var(--gjs-upload-padding);width:100%;box-sizing:border-box}.gjs-am-file-uploader #gjs-am-title{position:absolute;padding:var(--gjs-upload-padding);width:100%}.gjs-cm-editor-c{float:left;box-sizing:border-box;width:50%}.gjs-cm-editor-c .CodeMirror{height:450px}.gjs-cm-editor{font-size:12px}.gjs-cm-editor#gjs-cm-htmlmixed{padding-right:10px;border-right:1px solid var(--gjs-main-dark-color)}.gjs-cm-editor#gjs-cm-htmlmixed #gjs-cm-title{color:#a97d44}.gjs-cm-editor#gjs-cm-css{padding-left:10px}.gjs-cm-editor#gjs-cm-css #gjs-cm-title{color:#ddca7e}.gjs-cm-editor #gjs-cm-title{background-color:var(--gjs-main-dark-color);font-size:12px;padding:5px 10px 3px;text-align:right}.gjs-rte-toolbar{position:absolute;z-index:10}.gjs-rte-toolbar-ui{border:1px solid var(--gjs-main-dark-color);border-radius:3px}.gjs-rte-actionbar{display:flex}.gjs-rte-action{display:flex;align-items:center;justify-content:center;padding:5px;width:25px;border-right:1px solid var(--gjs-main-dark-color);text-align:center;cursor:pointer;outline:none}.gjs-rte-action:last-child{border-right:none}.gjs-rte-action:hover{background-color:var(--gjs-main-light-color)}.gjs-rte-active{background-color:var(--gjs-main-light-color)}.gjs-rte-disabled{color:var(--gjs-main-light-color);cursor:not-allowed}.gjs-rte-disabled:hover{background-color:unset}.sp-container{position:absolute;top:0;left:0;display:inline-block;z-index:9999994;overflow:hidden}.sp-container.sp-flat{position:relative}.sp-container,.sp-container *{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}.sp-top{position:relative;width:100%;display:inline-block}.sp-top-inner{position:absolute;top:0;left:0;bottom:0;right:0}.sp-color{position:absolute;top:0;left:0;bottom:0;right:20%}.sp-hue{position:absolute;top:0;right:0;bottom:0;left:84%;height:100%}.sp-clear-enabled .sp-hue{top:33px;height:77.5%}.sp-fill{padding-top:80%}.sp-sat,.sp-val{position:absolute;top:0;left:0;right:0;bottom:0}.sp-alpha-enabled .sp-top{margin-bottom:18px}.sp-alpha-enabled .sp-alpha{display:block}.sp-alpha-handle{position:absolute;top:-4px;bottom:-4px;width:6px;left:50%;cursor:pointer;border:1px solid #000;background:#fff;opacity:.8}.sp-alpha{display:none;position:absolute;bottom:-14px;right:0;left:0;height:8px}.sp-alpha-inner{border:solid 1px #333}.sp-clear{display:none}.sp-clear.sp-clear-display{background-position:center}.sp-clear-enabled .sp-clear{display:block;position:absolute;top:0px;right:0;bottom:0;left:84%;height:28px}.sp-container,.sp-replacer,.sp-preview,.sp-dragger,.sp-slider,.sp-alpha,.sp-clear,.sp-alpha-handle,.sp-container.sp-dragging .sp-input,.sp-container button{-webkit-user-select:none;-moz-user-select:-moz-none;-o-user-select:none;user-select:none}.sp-container.sp-input-disabled .sp-input-container{display:none}.sp-container.sp-buttons-disabled .sp-button-container{display:none}.sp-container.sp-palette-buttons-disabled .sp-palette-button-container{display:none}.sp-palette-only .sp-picker-container{display:none}.sp-palette-disabled .sp-palette-container{display:none}.sp-initial-disabled .sp-initial{display:none}.sp-sat{background-image:-webkit-gradient(linear, 0 0, 100% 0, from(#fff), to(rgba(204, 154, 129, 0)));background-image:-webkit-linear-gradient(left, #fff, rgba(204, 154, 129, 0));background-image:-moz-linear-gradient(left, #fff, rgba(204, 154, 129, 0));background-image:-o-linear-gradient(left, #fff, rgba(204, 154, 129, 0));background-image:-ms-linear-gradient(left, #fff, rgba(204, 154, 129, 0));background-image:linear-gradient(to right, #fff, rgba(204, 154, 129, 0));-ms-filter:"progid:DXImageTransform.Microsoft.gradient(GradientType = 1, startColorstr=#FFFFFFFF, endColorstr=#00CC9A81)";filter:progid:DXImageTransform.Microsoft.gradient(GradientType = 1, startColorstr="#FFFFFFFF", endColorstr="#00CC9A81")}.sp-val{background-image:-webkit-gradient(linear, 0 100%, 0 0, from(#000000), to(rgba(204, 154, 129, 0)));background-image:-webkit-linear-gradient(bottom, #000000, rgba(204, 154, 129, 0));background-image:-moz-linear-gradient(bottom, #000, rgba(204, 154, 129, 0));background-image:-o-linear-gradient(bottom, #000, rgba(204, 154, 129, 0));background-image:-ms-linear-gradient(bottom, #000, rgba(204, 154, 129, 0));background-image:linear-gradient(to top, #000, rgba(204, 154, 129, 0));-ms-filter:"progid:DXImageTransform.Microsoft.gradient(startColorstr=#00CC9A81, endColorstr=#FF000000)";filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#00CC9A81", endColorstr="#FF000000")}.sp-hue{background:-moz-linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);background:-ms-linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);background:-o-linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);background:-webkit-gradient(linear, left top, left bottom, from(#ff0000), color-stop(0.17, #ffff00), color-stop(0.33, #00ff00), color-stop(0.5, #00ffff), color-stop(0.67, #0000ff), color-stop(0.83, #ff00ff), to(#ff0000));background:-webkit-linear-gradient(top, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);background:linear-gradient(to bottom, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)}.sp-1{height:17%;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#ff0000", endColorstr="#ffff00")}.sp-2{height:16%;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffff00", endColorstr="#00ff00")}.sp-3{height:17%;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#00ff00", endColorstr="#00ffff")}.sp-4{height:17%;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#00ffff", endColorstr="#0000ff")}.sp-5{height:16%;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#0000ff", endColorstr="#ff00ff")}.sp-6{height:17%;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#ff00ff", endColorstr="#ff0000")}.sp-hidden{display:none !important}.sp-cf:before,.sp-cf:after{content:"";display:table}.sp-cf:after{clear:both}@media(max-device-width: 480px){.sp-color{right:40%}.sp-hue{left:63%}.sp-fill{padding-top:60%}}.sp-dragger{border-radius:5px;height:5px;width:5px;border:1px solid #fff;background:#000;cursor:pointer;position:absolute;top:0;left:0}.sp-slider{position:absolute;top:0;cursor:pointer;height:3px;left:-1px;right:-1px;border:1px solid #000;background:#fff;opacity:.8}.sp-container{border-radius:0;background-color:#ececec;border:solid 1px #f0c49b;padding:0}.sp-container,.sp-container button,.sp-container input,.sp-color,.sp-hue,.sp-clear{font:normal 12px "Lucida Grande","Lucida Sans Unicode","Lucida Sans",Geneva,Verdana,sans-serif;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box}.sp-top{margin-bottom:3px}.sp-color,.sp-hue,.sp-clear{border:solid 1px #666}.sp-input-container{float:right;width:100px;margin-bottom:4px}.sp-initial-disabled .sp-input-container{width:100%}.sp-input{font-size:12px !important;border:1px inset;padding:4px 5px;margin:0;width:100%;background:rgba(0,0,0,0);border-radius:3px;color:#222}.sp-input:focus{border:1px solid orange}.sp-input.sp-validation-error{border:1px solid red;background:#fdd}.sp-picker-container,.sp-palette-container{float:left;position:relative;padding:10px;padding-bottom:300px;margin-bottom:-290px}.sp-picker-container{width:172px;border-left:solid 1px #fff}.sp-palette-container{border-right:solid 1px #ccc}.sp-palette-only .sp-palette-container{border:0}.sp-palette .sp-thumb-el{display:block;position:relative;float:left;width:24px;height:15px;margin:3px;cursor:pointer;border:solid 2px rgba(0,0,0,0)}.sp-palette .sp-thumb-el:hover,.sp-palette .sp-thumb-el.sp-thumb-active{border-color:orange}.sp-thumb-el{position:relative}.sp-initial{float:left;border:solid 1px #333}.sp-initial span{width:30px;height:25px;border:none;display:block;float:left;margin:0}.sp-initial .sp-clear-display{background-position:center}.sp-palette-button-container,.sp-button-container{float:right}.sp-replacer{margin:0;overflow:hidden;cursor:pointer;padding:4px;display:inline-block;border:solid 1px #91765d;background:#eee;color:#333;vertical-align:middle}.sp-replacer:hover,.sp-replacer.sp-active{border-color:#f0c49b;color:#111}.sp-replacer.sp-disabled{cursor:default;border-color:silver;color:silver}.sp-dd{padding:2px 0;height:16px;line-height:16px;float:left;font-size:10px}.sp-preview{position:relative;width:25px;height:20px;border:solid 1px #222;margin-right:5px;float:left;z-index:0}.sp-palette{max-width:220px}.sp-palette .sp-thumb-el{width:16px;height:16px;margin:2px 1px;border:solid 1px #d0d0d0}.sp-container{padding-bottom:0}.sp-container button{background-color:#eee;background-image:-webkit-linear-gradient(top, #eeeeee, #cccccc);background-image:-moz-linear-gradient(top, #eeeeee, #cccccc);background-image:-ms-linear-gradient(top, #eeeeee, #cccccc);background-image:-o-linear-gradient(top, #eeeeee, #cccccc);background-image:linear-gradient(to bottom, #eeeeee, #cccccc);border:1px solid #ccc;border-bottom:1px solid #bbb;border-radius:3px;color:#333;font-size:14px;line-height:1;padding:5px 4px;text-align:center;text-shadow:0 1px 0 #eee;vertical-align:middle}.sp-container button:hover{background-color:#ddd;background-image:-webkit-linear-gradient(top, #dddddd, #bbbbbb);background-image:-moz-linear-gradient(top, #dddddd, #bbbbbb);background-image:-ms-linear-gradient(top, #dddddd, #bbbbbb);background-image:-o-linear-gradient(top, #dddddd, #bbbbbb);background-image:linear-gradient(to bottom, #dddddd, #bbbbbb);border:1px solid #bbb;border-bottom:1px solid #999;cursor:pointer;text-shadow:0 1px 0 #ddd}.sp-container button:active{border:1px solid #aaa;border-bottom:1px solid #888;-webkit-box-shadow:inset 0 0 5px 2px #aaa,0 1px 0 0 #eee;-moz-box-shadow:inset 0 0 5px 2px #aaa,0 1px 0 0 #eee;-ms-box-shadow:inset 0 0 5px 2px #aaa,0 1px 0 0 #eee;-o-box-shadow:inset 0 0 5px 2px #aaa,0 1px 0 0 #eee;box-shadow:inset 0 0 5px 2px #aaa,0 1px 0 0 #eee}.sp-cancel{font-size:11px;color:#d93f3f !important;margin:0;padding:2px;margin-right:5px;vertical-align:middle;text-decoration:none}.sp-cancel:hover{color:#d93f3f !important;text-decoration:underline}.sp-palette span:hover,.sp-palette span.sp-thumb-active{border-color:#000}.sp-preview,.sp-alpha,.sp-thumb-el{position:relative;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==)}.sp-preview-inner,.sp-alpha-inner,.sp-thumb-inner{display:block;position:absolute;top:0;left:0;bottom:0;right:0}.sp-palette .sp-thumb-inner{background-position:50% 50%;background-repeat:no-repeat}.sp-palette .sp-thumb-light.sp-thumb-active .sp-thumb-inner{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAYAAABWzo5XAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAIVJREFUeNpiYBhsgJFMffxAXABlN5JruT4Q3wfi/0DsT64h8UD8HmpIPCWG/KemIfOJCUB+Aoacx6EGBZyHBqI+WsDCwuQ9mhxeg2A210Ntfo8klk9sOMijaURm7yc1UP2RNCMbKE9ODK1HM6iegYLkfx8pligC9lCD7KmRof0ZhjQACDAAceovrtpVBRkAAAAASUVORK5CYII=)}.sp-palette .sp-thumb-dark.sp-thumb-active .sp-thumb-inner{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAYAAABWzo5XAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAadEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My41LjEwMPRyoQAAAMdJREFUOE+tkgsNwzAMRMugEAahEAahEAZhEAqlEAZhEAohEAYh81X2dIm8fKpEspLGvudPOsUYpxE2BIJCroJmEW9qJ+MKaBFhEMNabSy9oIcIPwrB+afvAUFoK4H0tMaQ3XtlrggDhOVVMuT4E5MMG0FBbCEYzjYT7OxLEvIHQLY2zWwQ3D+9luyOQTfKDiFD3iUIfPk8VqrKjgAiSfGFPecrg6HN6m/iBcwiDAo7WiBeawa+Kwh7tZoSCGLMqwlSAzVDhoK+6vH4G0P5wdkAAAAASUVORK5CYII=)}.sp-clear-display{background-repeat:no-repeat;background-position:center;background-image:url(data:image/gif;base64,R0lGODlhFAAUAPcAAAAAAJmZmZ2dnZ6enqKioqOjo6SkpKWlpaampqenp6ioqKmpqaqqqqurq/Hx8fLy8vT09PX19ff39/j4+Pn5+fr6+vv7+wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAAUABQAAAihAP9FoPCvoMGDBy08+EdhQAIJCCMybCDAAYUEARBAlFiQQoMABQhKUJBxY0SPICEYHBnggEmDKAuoPMjS5cGYMxHW3IiT478JJA8M/CjTZ0GgLRekNGpwAsYABHIypcAgQMsITDtWJYBR6NSqMico9cqR6tKfY7GeBCuVwlipDNmefAtTrkSzB1RaIAoXodsABiZAEFB06gIBWC1mLVgBa0AAOw==)}.gjs-editor-sp{border:1px solid var(--gjs-main-dark-color);box-shadow:0 0 7px var(--gjs-main-dark-color);border-radius:3px}.gjs-editor-sp .sp-hue,.gjs-editor-sp .sp-slider{cursor:row-resize}.gjs-editor-sp .sp-color,.gjs-editor-sp .sp-dragger{cursor:crosshair}.gjs-editor-sp .sp-alpha-inner,.gjs-editor-sp .sp-alpha-handle{cursor:col-resize}.gjs-editor-sp .sp-hue{left:90%}.gjs-editor-sp .sp-color{right:15%}.gjs-editor-sp .sp-picker-container{border:none}.gjs-editor-sp .colpick_dark .colpick_color{outline:1px solid var(--gjs-main-dark-color)}.gjs-editor-sp .sp-cancel,.gjs-editor-sp .sp-cancel:hover{bottom:-8px;color:#777 !important;font-size:25px;left:0;position:absolute;text-decoration:none}.gjs-editor-sp .sp-alpha-handle{background-color:#ccc;border:1px solid #555;width:4px}.gjs-editor-sp .sp-color,.gjs-editor-sp .sp-hue{border:1px solid #333}.gjs-editor-sp .sp-slider{background-color:#ccc;border:1px solid #555;height:3px;left:-4px;width:22px}.gjs-editor-sp .sp-dragger{background:rgba(0,0,0,0);box-shadow:0 0 0 1px #111}.gjs-editor-sp .sp-button-container{float:none;width:100%;position:relative;text-align:right}.gjs-editor-sp .sp-button-container .sp-choose,.gjs-editor-sp .sp-button-container .sp-choose:hover,.gjs-editor-sp .sp-button-container .sp-choose:active{background:var(--gjs-main-dark-color);border-color:var(--gjs-main-dark-color);color:var(--gjs-font-color);text-shadow:none;box-shadow:none;padding:3px 5px}.gjs-editor-sp .sp-palette-container{border:none;float:none;margin:0;padding:5px 10px 0}.gjs-editor-sp .sp-palette .sp-thumb-el,.gjs-editor-sp .sp-palette .sp-thumb-el:hover{border:1px solid rgba(0,0,0,.9)}.gjs-editor-sp .sp-palette .sp-thumb-el:hover,.gjs-editor-sp .sp-palette .sp-thumb-el.sp-thumb-active{border-color:rgba(0,0,0,.9)}.gjs-one-bg{background-color:var(--gjs-primary-color)}.gjs-one-color{color:var(--gjs-primary-color)}.gjs-one-color-h:hover{color:var(--gjs-primary-color)}.gjs-two-bg{background-color:var(--gjs-secondary-color)}.gjs-two-color{color:var(--gjs-secondary-color)}.gjs-two-color-h:hover{color:var(--gjs-secondary-color)}.gjs-three-bg{background-color:var(--gjs-tertiary-color)}.gjs-three-color{color:var(--gjs-tertiary-color)}.gjs-three-color-h:hover{color:var(--gjs-tertiary-color)}.gjs-four-bg{background-color:var(--gjs-quaternary-color)}.gjs-four-color{color:var(--gjs-quaternary-color)}.gjs-four-color-h:hover{color:var(--gjs-quaternary-color)}.gjs-danger-bg{background-color:var(--gjs-color-red)}.gjs-danger-color{color:var(--gjs-color-red)}.gjs-danger-color-h:hover{color:var(--gjs-color-red)}.gjs-bdrag{pointer-events:none !important;position:absolute !important;z-index:10 !important;width:auto}.gjs-drag-helper{background-color:var(--gjs-color-blue) !important;pointer-events:none !important;position:absolute !important;z-index:10 !important;transform:scale(0.3) !important;transform-origin:top left !important;-webkit-transform-origin:top left !important;margin:15px !important;transition:none !important;outline:none !important}.gjs-grabbing,.gjs-grabbing *{cursor:grabbing !important;cursor:-webkit-grabbing !important}.gjs-grabbing{overflow:hidden}.gjs-off-prv{position:relative;z-index:10;padding:5px;cursor:pointer}.gjs-editor-cont ::-webkit-scrollbar-track{background:var(--gjs-secondary-dark-color)}.gjs-editor-cont ::-webkit-scrollbar-thumb{background-color:hsla(0,0%,100%,.2)}.gjs-editor-cont ::-webkit-scrollbar{width:8px}.gjs-no-touch-actions{touch-action:none}.gjs-disabled{-moz-user-select:none;-khtml-user-select:none;-webkit-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;opacity:.5;filter:alpha(opacity=50)}.gjs-editor{font-family:var(--gjs-main-font);font-size:var(--gjs-font-size);position:relative;box-sizing:border-box;height:100%}.gjs-freezed,.gjs-freezed{opacity:.5;filter:alpha(opacity=50);pointer-events:none}.gjs-hidden{display:none}@keyframes gjs-slide-down{0%{transform:translate(0, -3rem);opacity:0}100%{transform:translate(0, 0);opacity:1}}@keyframes gjs-slide-up{0%{transform:translate(0, 0);opacity:1}100%{transform:translate(0, -3rem);opacity:0}}.cm-s-hopscotch span.cm-error{color:#fff} diff --git a/public/vendor/grapesjs/grapes.min.js b/public/vendor/grapesjs/grapes.min.js new file mode 100644 index 0000000..7e69656 --- /dev/null +++ b/public/vendor/grapesjs/grapes.min.js @@ -0,0 +1,3 @@ +/*! grapesjs - 0.22.13 */ +!function(t,e){'object'==typeof exports&&'object'==typeof module?module.exports=e():'function'==typeof define&&define.amd?define([],e):'object'==typeof exports?exports["grapesjs"]=e():t["grapesjs"]=e()}('undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:this,(()=>(()=>{var t={4729:(t,e,n)=>{var o,r,i;1&&(r=[n(5706),n(4193)],void 0===(i='function'==typeof(o=function(t,e){var n=Array.prototype.slice;function o(t,e,n){return n.length<=4?t.call(e,n[0],n[1],n[2],n[3]):t.apply(e,n)}function r(t,e){return n.call(t,e)}function i(e,n){return null!=e&&(t.isArray(n)||(n=r(arguments,1)),t.all(n,(function(t){return t in e})))}var a=function(){var e=!1,n=-1;function o(){n++,e=!0,t.defer((function(){e=!1}))}return function(){return e||o(),n}}();function s(){this.registeredObjects=[],this.cidIndexes=[]}function l(e,n,o,r){for(var i,a=0,s=n.length;at.maximumStackLength&&(t.shift(),t.pointer--)}}}s.prototype={isRegistered:function(e){return e&&e.cid?this.registeredObjects[e.cid]:t.contains(this.registeredObjects,e)},register:function(t){return!this.isRegistered(t)&&(t&&t.cid?(this.registeredObjects[t.cid]=t,this.cidIndexes.push(t.cid)):this.registeredObjects.push(t),!0)},unregister:function(e){if(this.isRegistered(e)){if(e&&e.cid)delete this.registeredObjects[e.cid],this.cidIndexes.splice(t.indexOf(this.cidIndexes,e.cid),1);else{var n=t.indexOf(this.registeredObjects,e);this.registeredObjects.splice(n,1)}return!0}return!1},get:function(){return t.map(this.cidIndexes,(function(t){return this.registeredObjects[t]}),this).concat(this.registeredObjects)}};var f={add:{undo:function(t,e,n,o){t.remove(n,o)},redo:function(t,e,n,o){o.index&&(o.at=o.index),t.add(n,o)},on:function(e,n,o){return{object:n,before:void 0,after:e,options:t.clone(o)}}},remove:{undo:function(t,e,n,o){"index"in o&&(o.at=o.index),t.add(e,o)},redo:function(t,e,n,o){t.remove(e,o)},on:function(e,n,o){return{object:n,before:e,after:void 0,options:t.clone(o)}}},change:{undo:function(e,n,o,r){t.isEmpty(n)?t.each(t.keys(o),e.unset,e):(e.set(n),r&&r.unsetData&&r.unsetData.before&&r.unsetData.before.length&&t.each(r.unsetData.before,e.unset,e))},redo:function(e,n,o,r){t.isEmpty(o)?t.each(t.keys(n),e.unset,e):(e.set(o),r&&r.unsetData&&r.unsetData.after&&r.unsetData.after.length&&t.each(r.unsetData.after,e.unset,e))},on:function(e,n){var o=e.changedAttributes(),r=t.keys(o),i=t.pick(e.previousAttributes(),r),a=t.keys(i),s=(n||(n={})).unsetData={after:[],before:[]};return r.length!=a.length&&(r.length>a.length?t.each(r,(function(t){t in i||s.before.push(t)}),this):t.each(a,(function(t){t in o||s.after.push(t)}))),{object:e,before:i,after:o,options:t.clone(n)}}},reset:{undo:function(t,e,n){t.reset(e)},redo:function(t,e,n){t.reset(n)},on:function(e,n){return{object:e,before:n.previousModels,after:t.clone(e.models)}}}};function h(){}function v(e,n,o,r){if("object"==typeof n)return t.each(n,(function(t,n){2===e?v(e,t,o,r):v(e,n,t,o)}));switch(e){case 0:i(o,"undo","redo","on")&&t.all(t.pick(o,"undo","redo","on"),t.isFunction)&&(r[n]=o);break;case 1:r[n]&&t.isObject(o)&&(r[n]=t.extend({},r[n],o));break;case 2:delete r[n]}return this}h.prototype=f;var g=e.Model.extend({defaults:{type:null,object:null,before:null,after:null,magicFusionIndex:null},undo:function(t){c("undo",this.attributes)},redo:function(t){c("redo",this.attributes)}}),y=e.Collection.extend({model:g,pointer:-1,track:!1,isCurrentlyUndoRedoing:!1,maximumStackLength:1/0,setMaxLength:function(t){this.maximumStackLength=t}}),m=e.Model.extend({defaults:{maximumStackLength:1/0,track:!1},initialize:function(e){this.stack=new y,this.objectRegistry=new s,this.undoTypes=new h,this.stack.setMaxLength(this.get("maximumStackLength")),this.on("change:maximumStackLength",(function(t,e){this.stack.setMaxLength(e)}),this),e&&e.track&&this.startTracking(),e&&e.register&&(t.isArray(e.register)||t.isArguments(e.register)?o(this.register,this,e.register):this.register(e.register))},startTracking:function(){this.set("track",!0),this.stack.track=!0},stopTracking:function(){this.set("track",!1),this.stack.track=!1},isTracking:function(){return this.get("track")},_addToStack:function(t){d(this.stack,t,r(arguments,1),this.undoTypes)},register:function(){l("on",arguments,this._addToStack,this)},unregister:function(){l("off",arguments,this._addToStack,this)},unregisterAll:function(){o(this.unregister,this,this.objectRegistry.get())},undo:function(t){u("undo",this,this.stack,t)},undoAll:function(){u("undo",this,this.stack,!1,!0)},redo:function(t){u("redo",this,this.stack,t)},redoAll:function(){u("redo",this,this.stack,!1,!0)},isAvailable:function(t){var e=this.stack,n=e.length;switch(t){case"undo":return n>0&&e.pointer>-1;case"redo":return n>0&&e.pointer{var o,r;!function(){var i='object'==typeof self&&self.self===self&&self||'object'==typeof n.g&&n.g.global===n.g&&n.g;if(1)o=[n(5706),n(7774),e],r=function(t,e,n){i.Backbone=function(t,e,n,o){var r=t.Backbone,i=Array.prototype.slice;e.VERSION='1.4.1',e.$=o,e.noConflict=function(){return t.Backbone=r,this},e.emulateHTTP=!1,e.emulateJSON=!1;var a,s=e.Events={},l=/\s+/,c=function(t,e,o,r,i){var a,s=0;if(o&&'object'==typeof o){void 0!==r&&'context'in i&&void 0===i.context&&(i.context=r);for(a=n.keys(o);sthis.length&&(r=this.length),r<0&&(r+=this.length+1);var i,a,s=[],l=[],c=[],u=[],p={},d=e.add,f=e.merge,h=e.remove,v=!1,g=this.comparator&&null==r&&!1!==e.sort,y=n.isString(this.comparator)?this.comparator:null;for(a=0;a7),this._useHashChange=this._wantsHashChange&&this._hasHashChange,this._wantsPushState=!!this.options.pushState,this._hasPushState=!(!this.history||!this.history.pushState),this._usePushState=this._wantsPushState&&this._hasPushState,this.fragment=this.getFragment(),this.root=('/'+this.root+'/').replace(W,'/'),this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){var e=this.root.slice(0,-1)||'/';return this.location.replace(e+'#'+this.getPath()),!0}this._hasPushState&&this.atRoot()&&this.navigate(this.getHash(),{replace:!0})}if(!this._hasHashChange&&this._wantsHashChange&&!this._usePushState){this.iframe=document.createElement('iframe'),this.iframe.src='javascript:0',this.iframe.style.display='none',this.iframe.tabIndex=-1;var o=document.body,r=o.insertBefore(this.iframe,o.firstChild).contentWindow;r.document.open(),r.document.close(),r.location.hash='#'+this.fragment}var i=window.addEventListener||function(t,e){return attachEvent('on'+t,e)};if(this._usePushState?i('popstate',this.checkUrl,!1):this._useHashChange&&!this.iframe?i('hashchange',this.checkUrl,!1):this._wantsHashChange&&(this._checkUrlInterval=setInterval(this.checkUrl,this.interval)),!this.options.silent)return this.loadUrl()},stop:function(){var t=window.removeEventListener||function(t,e){return detachEvent('on'+t,e)};this._usePushState?t('popstate',this.checkUrl,!1):this._useHashChange&&!this.iframe&&t('hashchange',this.checkUrl,!1),this.iframe&&(document.body.removeChild(this.iframe),this.iframe=null),this._checkUrlInterval&&clearInterval(this._checkUrlInterval),z.started=!1},route:function(t,e){this.handlers.unshift({route:t,callback:e})},checkUrl:function(t){var e=this.getFragment();if(e===this.fragment&&this.iframe&&(e=this.getHash(this.iframe.contentWindow)),e===this.fragment)return!1;this.iframe&&this.navigate(e),this.loadUrl()},loadUrl:function(t){return!!this.matchRoot()&&(t=this.fragment=this.getFragment(t),n.some(this.handlers,(function(e){if(e.route.test(t))return e.callback(t),!0})))},navigate:function(t,e){if(!z.started)return!1;e&&!0!==e||(e={trigger:!!e}),t=this.getFragment(t||'');var n=this.root;''!==t&&'?'!==t.charAt(0)||(n=n.slice(0,-1)||'/');var o=n+t;t=t.replace($,'');var r=this.decodeFragment(t);if(this.fragment!==r){if(this.fragment=r,this._usePushState)this.history[e.replace?'replaceState':'pushState']({},document.title,o);else{if(!this._wantsHashChange)return this.location.assign(o);if(this._updateHash(this.location,t,e.replace),this.iframe&&t!==this.getHash(this.iframe.contentWindow)){var i=this.iframe.contentWindow;e.replace||(i.document.open(),i.document.close()),this._updateHash(i.location,t,e.replace)}}return e.trigger?this.loadUrl(t):void 0}},_updateHash:function(t,e,n){if(n){var o=t.href.replace(/(javascript:|#).*$/,'');t.replace(o+'#'+e)}else t.hash='#'+e}}),e.history=new z;var q=function(t,e){var o,r=this;return o=t&&n.has(t,'constructor')?t.constructor:function(){return r.apply(this,arguments)},n.extend(o,r,e),o.prototype=n.create(r.prototype,t),o.prototype.constructor=o,o.__super__=r.prototype,o};y.extend=m.extend=R.extend=P.extend=z.extend=q;var G=function(){throw new Error('A "url" property or function must be specified')},K=function(t,e){var n=e.error;e.error=function(o){n&&n.call(e.context,t,o,e),t.trigger('error',t,o,e)}};return e}(i,n,t,e)}.apply(e,o),void 0===r||(t.exports=r);else;}()},3640:(t,e,n)=>{1&&function(t){t.extendMode("css",{commentStart:"/*",commentEnd:"*/",newlineAfterToken:function(t,e){return/^[;{}]$/.test(e)}}),t.extendMode("javascript",{commentStart:"/*",commentEnd:"*/",newlineAfterToken:function(t,e,n,o){return this.jsonMode?/^[\[,{]$/.test(e)||/^}/.test(n):(";"!=e||!o.lexical||")"!=o.lexical.type)&&/^[;{}]$/.test(e)&&!/^;/.test(n)}});var e=/^(a|abbr|acronym|area|base|bdo|big|br|button|caption|cite|code|col|colgroup|dd|del|dfn|em|frame|hr|iframe|img|input|ins|kbd|label|legend|link|map|object|optgroup|option|param|q|samp|script|select|small|span|strong|sub|sup|textarea|tt|var)$/;t.extendMode("xml",{commentStart:"\x3c!--",commentEnd:"--\x3e",newlineAfterToken:function(t,n,o,r){var i=!1;return"html"==this.configuration&&(i=!!r.context&&e.test(r.context.tagName)),!i&&("tag"==t&&/>$/.test(n)&&r.context||/^-1&&s>-1&&s>a&&(t=t.substr(0,a)+t.substring(a+i.commentStart.length,s)+t.substr(s+i.commentEnd.length)),r.replaceRange(t,n,o)}}))})),t.defineExtension("autoIndentRange",(function(t,e){var n=this;this.operation((function(){for(var o=t.line;o<=e.line;o++)n.indentLine(o,"smart")}))})),t.defineExtension("autoFormatRange",(function(e,n){var o=this,r=o.getMode(),i=o.getRange(e,n).split("\n"),a=t.copyState(r,o.getTokenAt(e).state),s=o.getOption("tabSize"),l="",c=0,u=0===e.ch;function p(){l+="\n",u=!0,++c}for(var d=0;d2),g=/Android/.test(t),y=v||g||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(t),m=v||/Mac/.test(e),b=/\bCrOS\b/.test(t),_=/win/i.test(e),w=p&&t.match(/Version\/(\d*\.\d*)/);w&&(w=Number(w[1])),w&&w>=15&&(p=!1,l=!0);var x=m&&(c||p&&(null==w||w<12.11)),C=n||a&&s>=9;function S(t){return new RegExp("(^|\\s)"+t+"(?:$|\\s)\\s*")}var O,T=function(t,e){var n=t.className,o=S(e).exec(n);if(o){var r=n.slice(o.index+o[0].length);t.className=n.slice(0,o.index)+(r?o[1]+r:"")}};function P(t){for(var e=t.childNodes.length;e>0;--e)t.removeChild(t.firstChild);return t}function E(t,e){return P(t).appendChild(e)}function k(t,e,n,o){var r=document.createElement(t);if(n&&(r.className=n),o&&(r.style.cssText=o),"string"==typeof e)r.appendChild(document.createTextNode(e));else if(e)for(var i=0;i=e)return a+(e-i);a+=s-i,a+=n-a%n,i=s+1}}v?I=function(t){t.selectionStart=0,t.selectionEnd=t.value.length}:a&&(I=function(t){try{t.select()}catch(t){}});var F=function(){this.id=null,this.f=null,this.time=0,this.handler=N(this.onTimeout,this)};function H(t,e){for(var n=0;n=e)return o+Math.min(a,e-r);if(r+=i-o,o=i+1,(r+=n-r%n)>=e)return o}}var G=[""];function K(t){for(;G.length<=t;)G.push(Y(G)+" ");return G[t]}function Y(t){return t[t.length-1]}function J(t,e){for(var n=[],o=0;o"€"&&(t.toUpperCase()!=t.toLowerCase()||tt.test(t))}function nt(t,e){return e?!!(e.source.indexOf("\\w")>-1&&et(t))||e.test(t):et(t)}function ot(t){for(var e in t)if(t.hasOwnProperty(e)&&t[e])return!1;return!0}var rt=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;function it(t){return t.charCodeAt(0)>=768&&rt.test(t)}function at(t,e,n){for(;(n<0?e>0:en?-1:1;;){if(e==n)return e;var r=(e+n)/2,i=o<0?Math.ceil(r):Math.floor(r);if(i==e)return t(i)?e:n;t(i)?n=i:e=i+o}}function lt(t,e,n,o){if(!t)return o(e,n,"ltr",0);for(var r=!1,i=0;ie||e==n&&a.to==e)&&(o(Math.max(a.from,e),Math.min(a.to,n),1==a.level?"rtl":"ltr",i),r=!0)}r||o(e,n,"ltr")}var ct=null;function ut(t,e,n){var o;ct=null;for(var r=0;re)return r;i.to==e&&(i.from!=i.to&&"before"==n?o=r:ct=r),i.from==e&&(i.from!=i.to&&"before"!=n?o=r:ct=r)}return null!=o?o:ct}var pt=function(){var t="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",e="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";function n(n){return n<=247?t.charAt(n):1424<=n&&n<=1524?"R":1536<=n&&n<=1785?e.charAt(n-1536):1774<=n&&n<=2220?"r":8192<=n&&n<=8203?"w":8204==n?"b":"L"}var o=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,r=/[stwN]/,i=/[LRr]/,a=/[Lb1n]/,s=/[1n]/;function l(t,e,n){this.level=t,this.from=e,this.to=n}return function(t,e){var c="ltr"==e?"L":"R";if(0==t.length||"ltr"==e&&!o.test(t))return!1;for(var u=t.length,p=[],d=0;d-1&&(o[e]=r.slice(0,i).concat(r.slice(i+1)))}}}function yt(t,e){var n=vt(t,e);if(n.length)for(var o=Array.prototype.slice.call(arguments,2),r=0;r0}function wt(t){t.prototype.on=function(t,e){ht(this,t,e)},t.prototype.off=function(t,e){gt(this,t,e)}}function xt(t){t.preventDefault?t.preventDefault():t.returnValue=!1}function Ct(t){t.stopPropagation?t.stopPropagation():t.cancelBubble=!0}function St(t){return null!=t.defaultPrevented?t.defaultPrevented:0==t.returnValue}function Ot(t){xt(t),Ct(t)}function Tt(t){return t.target||t.srcElement}function Pt(t){var e=t.which;return null==e&&(1&t.button?e=1:2&t.button?e=3:4&t.button&&(e=2)),m&&t.ctrlKey&&1==e&&(e=3),e}var Et,kt,At=function(){if(a&&s<9)return!1;var t=k('div');return"draggable"in t||"dragDrop"in t}();function jt(t){if(null==Et){var e=k("span","​");E(t,k("span",[e,document.createTextNode("x")])),0!=t.firstChild.offsetHeight&&(Et=e.offsetWidth<=1&&e.offsetHeight>2&&!(a&&s<8))}var n=Et?k("span","​"):k("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return n.setAttribute("cm-text",""),n}function Mt(t){if(null!=kt)return kt;var e=E(t,document.createTextNode("AخA")),n=O(e,0,1).getBoundingClientRect(),o=O(e,1,2).getBoundingClientRect();return P(t),!(!n||n.left==n.right)&&(kt=o.right-n.right<3)}var Dt,Lt=3!="\n\nb".split(/\n/).length?function(t){for(var e=0,n=[],o=t.length;e<=o;){var r=t.indexOf("\n",e);-1==r&&(r=t.length);var i=t.slice(e,"\r"==t.charAt(r-1)?r-1:r),a=i.indexOf("\r");-1!=a?(n.push(i.slice(0,a)),e+=a+1):(n.push(i),e=r+1)}return n}:function(t){return t.split(/\r\n?|\n/)},It=window.getSelection?function(t){try{return t.selectionStart!=t.selectionEnd}catch(t){return!1}}:function(t){var e;try{e=t.ownerDocument.selection.createRange()}catch(t){}return!(!e||e.parentElement()!=t)&&0!=e.compareEndPoints("StartToEnd",e)},Nt="oncopy"in(Dt=k("div"))||(Dt.setAttribute("oncopy","return;"),"function"==typeof Dt.oncopy),Rt=null;function Vt(t){if(null!=Rt)return Rt;var e=E(t,k("span","x")),n=e.getBoundingClientRect(),o=O(e,0,1).getBoundingClientRect();return Rt=Math.abs(n.left-o.left)>1}var Ft={},Ht={};function Ut(t,e){arguments.length>2&&(e.dependencies=Array.prototype.slice.call(arguments,2)),Ft[t]=e}function zt(t,e){Ht[t]=e}function Bt(t){if("string"==typeof t&&Ht.hasOwnProperty(t))t=Ht[t];else if(t&&"string"==typeof t.name&&Ht.hasOwnProperty(t.name)){var e=Ht[t.name];"string"==typeof e&&(e={name:e}),(t=Q(e,t)).name=e.name}else{if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return Bt("application/xml");if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+json$/.test(t))return Bt("application/json")}return"string"==typeof t?{name:t}:t||{name:"null"}}function Wt(t,e){e=Bt(e);var n=Ft[e.name];if(!n)return Wt(t,"text/plain");var o=n(t,e);if($t.hasOwnProperty(e.name)){var r=$t[e.name];for(var i in r)r.hasOwnProperty(i)&&(o.hasOwnProperty(i)&&(o["_"+i]=o[i]),o[i]=r[i])}if(o.name=e.name,e.helperType&&(o.helperType=e.helperType),e.modeProps)for(var a in e.modeProps)o[a]=e.modeProps[a];return o}var $t={};function qt(t,e){R(e,$t.hasOwnProperty(t)?$t[t]:$t[t]={})}function Gt(t,e){if(!0===e)return e;if(t.copyState)return t.copyState(e);var n={};for(var o in e){var r=e[o];r instanceof Array&&(r=r.concat([])),n[o]=r}return n}function Kt(t,e){for(var n;t.innerMode&&(n=t.innerMode(e))&&n.mode!=t;)e=n.state,t=n.mode;return n||{mode:t,state:e}}function Yt(t,e,n){return!t.startState||t.startState(e,n)}var Jt=function(t,e,n){this.pos=this.start=0,this.string=t,this.tabSize=e||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0,this.lineOracle=n};function Xt(t,e){if((e-=t.first)<0||e>=t.size)throw new Error("There is no line "+(e+t.first)+" in the document.");for(var n=t;!n.lines;)for(var o=0;;++o){var r=n.children[o],i=r.chunkSize();if(e=t.first&&en?ie(n,Xt(t,n).text.length):fe(e,Xt(t,e.line).text.length)}function fe(t,e){var n=t.ch;return null==n||n>e?ie(t.line,e):n<0?ie(t.line,0):t}function he(t,e){for(var n=[],o=0;o=this.string.length},Jt.prototype.sol=function(){return this.pos==this.lineStart},Jt.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},Jt.prototype.next=function(){if(this.pose},Jt.prototype.eatSpace=function(){for(var t=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>t},Jt.prototype.skipToEnd=function(){this.pos=this.string.length},Jt.prototype.skipTo=function(t){var e=this.string.indexOf(t,this.pos);if(e>-1)return this.pos=e,!0},Jt.prototype.backUp=function(t){this.pos-=t},Jt.prototype.column=function(){return this.lastColumnPos0?null:(o&&!1!==e&&(this.pos+=o[0].length),o)}var r=function(t){return n?t.toLowerCase():t};if(r(this.string.substr(this.pos,t.length))==r(t))return!1!==e&&(this.pos+=t.length),!0},Jt.prototype.current=function(){return this.string.slice(this.start,this.pos)},Jt.prototype.hideFirstChars=function(t,e){this.lineStart+=t;try{return e()}finally{this.lineStart-=t}},Jt.prototype.lookAhead=function(t){var e=this.lineOracle;return e&&e.lookAhead(t)},Jt.prototype.baseToken=function(){var t=this.lineOracle;return t&&t.baseToken(this.pos)};var ve=function(t,e){this.state=t,this.lookAhead=e},ge=function(t,e,n,o){this.state=e,this.doc=t,this.line=n,this.maxLookAhead=o||0,this.baseTokens=null,this.baseTokenPos=1};function ye(t,e,n,o){var r=[t.state.modeGen],i={};Te(t,e.text,t.doc.mode,n,(function(t,e){return r.push(t,e)}),i,o);for(var a=n.state,s=function(o){n.baseTokens=r;var s=t.state.overlays[o],l=1,c=0;n.state=!0,Te(t,e.text,s.mode,n,(function(t,e){for(var n=l;ct&&r.splice(l,1,t,r[l+1],o),l+=2,c=Math.min(t,o)}if(e)if(s.opaque)r.splice(n,l-n,t,"overlay "+e),l=n+2;else for(;nt.options.maxHighlightLength&&Gt(t.doc.mode,o.state),i=ye(t,e,o);r&&(o.state=r),e.stateAfter=o.save(!r),e.styles=i.styles,i.classes?e.styleClasses=i.classes:e.styleClasses&&(e.styleClasses=null),n===t.doc.highlightFrontier&&(t.doc.modeFrontier=Math.max(t.doc.modeFrontier,++t.doc.highlightFrontier))}return e.styles}function be(t,e,n){var o=t.doc,r=t.display;if(!o.mode.startState)return new ge(o,!0,e);var i=Pe(t,e,n),a=i>o.first&&Xt(o,i-1).stateAfter,s=a?ge.fromSaved(o,a,i):new ge(o,Yt(o.mode),i);return o.iter(i,e,(function(n){_e(t,n.text,s);var o=s.line;n.stateAfter=o==e-1||o%5==0||o>=r.viewFrom&&oe.start)return i}throw new Error("Mode "+t.name+" failed to advance stream.")}ge.prototype.lookAhead=function(t){var e=this.doc.getLine(this.line+t);return null!=e&&t>this.maxLookAhead&&(this.maxLookAhead=t),e},ge.prototype.baseToken=function(t){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=t;)this.baseTokenPos+=2;var e=this.baseTokens[this.baseTokenPos+1];return{type:e&&e.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-t}},ge.prototype.nextLine=function(){this.line++,this.maxLookAhead>0&&this.maxLookAhead--},ge.fromSaved=function(t,e,n){return e instanceof ve?new ge(t,Gt(t.mode,e.state),n,e.lookAhead):new ge(t,Gt(t.mode,e),n)},ge.prototype.save=function(t){var e=!1!==t?Gt(this.doc.mode,this.state):this.state;return this.maxLookAhead>0?new ve(e,this.maxLookAhead):e};var Ce=function(t,e,n){this.start=t.start,this.end=t.pos,this.string=t.current(),this.type=e||null,this.state=n};function Se(t,e,n,o){var r,i,a=t.doc,s=a.mode,l=Xt(a,(e=de(a,e)).line),c=be(t,e.line,n),u=new Jt(l.text,t.options.tabSize,c);for(o&&(i=[]);(o||u.post.options.maxHighlightLength?(s=!1,a&&_e(t,e,o,p.pos),p.pos=e.length,l=null):l=Oe(xe(n,p,o.state,d),i),d){var f=d[0].name;f&&(l="m-"+(l?f+" "+l:f))}if(!s||u!=l){for(;ca;--s){if(s<=i.first)return i.first;var l=Xt(i,s-1),c=l.stateAfter;if(c&&(!n||s+(c instanceof ve?c.lookAhead:0)<=i.modeFrontier))return s;var u=V(l.text,null,t.options.tabSize);(null==r||o>u)&&(r=s-1,o=u)}return r}function Ee(t,e){if(t.modeFrontier=Math.min(t.modeFrontier,e),!(t.highlightFrontiern;o--){var r=Xt(t,o).stateAfter;if(r&&(!(r instanceof ve)||o+r.lookAhead=e:i.to>e);(o||(o=[])).push(new De(a,i.from,s?null:i.to))}}return o}function Ve(t,e,n){var o;if(t)for(var r=0;r=e:i.to>e)||i.from==e&&"bookmark"==a.type&&(!n||i.marker.insertLeft)){var s=null==i.from||(a.inclusiveLeft?i.from<=e:i.from0&&s)for(var b=0;b0)){var u=[l,1],p=ae(c.from,s.from),d=ae(c.to,s.to);(p<0||!a.inclusiveLeft&&!p)&&u.push({from:c.from,to:s.from}),(d>0||!a.inclusiveRight&&!d)&&u.push({from:s.to,to:c.to}),r.splice.apply(r,u),l+=u.length-3}}return r}function ze(t){var e=t.markedSpans;if(e){for(var n=0;ne)&&(!n||qe(n,i.marker)<0)&&(n=i.marker)}return n}function Xe(t,e,n,o,r){var i=Xt(t,e),a=Ae&&i.markedSpans;if(a)for(var s=0;s=0&&p<=0||u<=0&&p>=0)&&(u<=0&&(l.marker.inclusiveRight&&r.inclusiveLeft?ae(c.to,n)>=0:ae(c.to,n)>0)||u>=0&&(l.marker.inclusiveRight&&r.inclusiveLeft?ae(c.from,o)<=0:ae(c.from,o)<0)))return!0}}}function Ze(t){for(var e;e=Ke(t);)t=e.find(-1,!0).line;return t}function Qe(t){for(var e;e=Ye(t);)t=e.find(1,!0).line;return t}function tn(t){for(var e,n;e=Ye(t);)t=e.find(1,!0).line,(n||(n=[])).push(t);return n}function en(t,e){var n=Xt(t,e),o=Ze(n);return n==o?e:ee(o)}function nn(t,e){if(e>t.lastLine())return e;var n,o=Xt(t,e);if(!on(t,o))return e;for(;n=Ye(o);)o=n.find(1,!0).line;return ee(o)+1}function on(t,e){var n=Ae&&e.markedSpans;if(n)for(var o=void 0,r=0;re.maxLineLength&&(e.maxLineLength=n,e.maxLine=t)}))}var cn=function(t,e,n){this.text=t,Be(this,e),this.height=n?n(this):1};function un(t,e,n,o){t.text=e,t.stateAfter&&(t.stateAfter=null),t.styles&&(t.styles=null),null!=t.order&&(t.order=null),ze(t),Be(t,n);var r=o?o(t):1;r!=t.height&&te(t,r)}function pn(t){t.parent=null,ze(t)}cn.prototype.lineNo=function(){return ee(this)},wt(cn);var dn={},fn={};function hn(t,e){if(!t||/^\s*$/.test(t))return null;var n=e.addModeClass?fn:dn;return n[t]||(n[t]=t.replace(/\S+/g,"cm-$&"))}function vn(t,e){var n=A("span",null,null,l?"padding-right: .1px":null),o={pre:A("pre",[n],"CodeMirror-line"),content:n,col:0,pos:0,cm:t,trailingSpace:!1,splitSpaces:t.getOption("lineWrapping")};e.measure={};for(var r=0;r<=(e.rest?e.rest.length:0);r++){var i=r?e.rest[r-1]:e.line,a=void 0;o.pos=0,o.addToken=yn,Mt(t.display.measure)&&(a=dt(i,t.doc.direction))&&(o.addToken=bn(o.addToken,a)),o.map=[],wn(i,o,me(t,i,e!=t.display.externalMeasured&&ee(i))),i.styleClasses&&(i.styleClasses.bgClass&&(o.bgClass=L(i.styleClasses.bgClass,o.bgClass||"")),i.styleClasses.textClass&&(o.textClass=L(i.styleClasses.textClass,o.textClass||""))),0==o.map.length&&o.map.push(0,0,o.content.appendChild(jt(t.display.measure))),0==r?(e.measure.map=o.map,e.measure.cache={}):((e.measure.maps||(e.measure.maps=[])).push(o.map),(e.measure.caches||(e.measure.caches=[])).push({}))}if(l){var s=o.content.lastChild;(/\bcm-tab\b/.test(s.className)||s.querySelector&&s.querySelector(".cm-tab"))&&(o.content.className="cm-tab-wrap-hack")}return yt(t,"renderLine",t,e.line,o.pre),o.pre.className&&(o.textClass=L(o.pre.className,o.textClass||"")),o}function gn(t){var e=k("span","•","cm-invalidchar");return e.title="\\u"+t.charCodeAt(0).toString(16),e.setAttribute("aria-label",e.title),e}function yn(t,e,n,o,r,i,l){if(e){var c,u=t.splitSpaces?mn(e,t.trailingSpace):e,p=t.cm.state.specialChars,d=!1;if(p.test(e)){c=document.createDocumentFragment();for(var f=0;1;){p.lastIndex=f;var h=p.exec(e),v=h?h.index-f:e.length-f;if(v){var g=document.createTextNode(u.slice(f,f+v));a&&s<9?c.appendChild(k("span",[g])):c.appendChild(g),t.map.push(t.pos,t.pos+v,g),t.col+=v,t.pos+=v}if(!h)break;f+=v+1;var y=void 0;if("\t"==h[0]){var m=t.cm.options.tabSize,b=m-t.col%m;(y=c.appendChild(k("span",K(b),"cm-tab"))).setAttribute("role","presentation"),y.setAttribute("cm-text","\t"),t.col+=b}else"\r"==h[0]||"\n"==h[0]?((y=c.appendChild(k("span","\r"==h[0]?"␍":"␤","cm-invalidchar"))).setAttribute("cm-text",h[0]),t.col+=1):((y=t.cm.options.specialCharPlaceholder(h[0])).setAttribute("cm-text",h[0]),a&&s<9?c.appendChild(k("span",[y])):c.appendChild(y),t.col+=1);t.map.push(t.pos,t.pos+1,y),t.pos++}}else t.col+=e.length,c=document.createTextNode(u),t.map.push(t.pos,t.pos+e.length,c),a&&s<9&&(d=!0),t.pos+=e.length;if(t.trailingSpace=32==u.charCodeAt(e.length-1),n||o||r||d||i||l){var _=n||"";o&&(_+=o),r&&(_+=r);var w=k("span",[c],_,i);if(l)for(var x in l)l.hasOwnProperty(x)&&"style"!=x&&"class"!=x&&w.setAttribute(x,l[x]);return t.content.appendChild(w)}t.content.appendChild(c)}}function mn(t,e){if(t.length>1&&!/ /.test(t))return t;for(var n=e,o="",r=0;rc&&p.from<=c);d++);if(p.to>=u)return t(n,o,r,i,a,s,l);t(n,o.slice(0,p.to-c),r,i,null,s,l),i=null,o=o.slice(p.to-c),c=p.to}}}function _n(t,e,n,o){var r=!o&&n.widgetNode;r&&t.map.push(t.pos,t.pos+e,r),!o&&t.cm.display.input.needsContentAttribute&&(r||(r=t.content.appendChild(document.createElement("span"))),r.setAttribute("cm-marker",n.id)),r&&(t.cm.display.input.setUneditable(r),t.content.appendChild(r)),t.pos+=e,t.trailingSpace=!1}function wn(t,e,n){var o=t.markedSpans,r=t.text,i=0;if(o)for(var a,s,l,c,u,p,d,f=r.length,h=0,v=1,g="",y=0;;){if(y==h){l=c=u=s="",d=null,p=null,y=1/0;for(var m=[],b=void 0,_=0;_h||x.collapsed&&w.to==h&&w.from==h)){if(null!=w.to&&w.to!=h&&y>w.to&&(y=w.to,c=""),x.className&&(l+=" "+x.className),x.css&&(s=(s?s+";":"")+x.css),x.startStyle&&w.from==h&&(u+=" "+x.startStyle),x.endStyle&&w.to==y&&(b||(b=[])).push(x.endStyle,w.to),x.title&&((d||(d={})).title=x.title),x.attributes)for(var C in x.attributes)(d||(d={}))[C]=x.attributes[C];x.collapsed&&(!p||qe(p.marker,x)<0)&&(p=w)}else w.from>h&&y>w.from&&(y=w.from)}if(b)for(var S=0;S=f)break;for(var T=Math.min(f,y);1;){if(g){var P=h+g.length;if(!p){var E=P>T?g.slice(0,T-h):g;e.addToken(e,E,a?a+l:l,u,h+E.length==y?c:"",s,d)}if(P>=T){g=g.slice(T-h),h=T;break}h=P,u=""}g=r.slice(i,i=n[v++]),a=hn(n[v++],e.cm.options)}}else for(var k=1;k2&&i.push((l.bottom+c.top)/2-n.top)}}i.push(n.bottom-n.top)}}function Zn(t,e,n){if(t.line==e)return{map:t.measure.map,cache:t.measure.cache};for(var o=0;on)return{map:t.measure.maps[r],cache:t.measure.caches[r],before:!0}}function Qn(t,e){var n=ee(e=Ze(e)),o=t.display.externalMeasured=new xn(t.doc,e,n);o.lineN=n;var r=o.built=vn(t,o);return o.text=r.pre,E(t.display.lineMeasure,r.pre),o}function to(t,e,n,o){return oo(t,no(t,e),n,o)}function eo(t,e){if(e>=t.display.viewFrom&&e=n.lineN&&ee)&&(r=(i=l-s)-1,e>=l&&(a="right")),null!=r){if(o=t[c+2],s==l&&n==(o.insertLeft?"left":"right")&&(a=n),"left"==n&&0==r)for(;c&&t[c-2]==t[c-3]&&t[c-1].insertLeft;)o=t[(c-=3)+2],a="left";if("right"==n&&r==l-s)for(;c=0&&(n=t[r]).left==n.right;r--);return n}function lo(t,e,n,o){var r,i=ao(e.map,n,o),l=i.node,c=i.start,u=i.end,p=i.collapse;if(3==l.nodeType){for(var d=0;d<4;d++){for(;c&&it(e.line.text.charAt(i.coverStart+c));)--c;for(;i.coverStart+u0&&(p=o="right"),r=t.options.lineWrapping&&(f=l.getClientRects()).length>1?f["right"==o?f.length-1:0]:l.getBoundingClientRect()}if(a&&s<9&&!c&&(!r||!r.left&&!r.right)){var h=l.parentNode.getClientRects()[0];r=h?{left:h.left,right:h.left+jo(t.display),top:h.top,bottom:h.bottom}:io}for(var v=r.top-e.rect.top,g=r.bottom-e.rect.top,y=(v+g)/2,m=e.view.measure.heights,b=0;b=o.text.length?(l=o.text.length,c="before"):l<=0&&(l=0,c="after"),!s)return a("before"==c?l-1:l,"before"==c);function u(t,e,n){return a(n?t-1:t,1==s[e].level!=n)}var p=ut(s,l,c),d=ct,f=u(l,p,"before"==c);return null!=d&&(f.other=u(l,d,"before"!=c)),f}function wo(t,e){var n=0;e=de(t.doc,e),t.options.lineWrapping||(n=jo(t.display)*e.ch);var o=Xt(t.doc,e.line),r=an(o)+$n(t.display);return{left:n,right:n,top:r,bottom:r+o.height}}function xo(t,e,n,o,r){var i=ie(t,e,n);return i.xRel=r,o&&(i.outside=o),i}function Co(t,e,n){var o=t.doc;if((n+=t.display.viewOffset)<0)return xo(o.first,0,null,-1,-1);var r=ne(o,n),i=o.first+o.size-1;if(r>i)return xo(o.first+o.size-1,Xt(o,i).text.length,null,1,1);e<0&&(e=0);for(var a=Xt(o,r);;){var s=Po(t,a,r,e,n),l=Je(a,s.ch+(s.xRel>0||s.outside>0?1:0));if(!l)return s;var c=l.find(1);if(c.line==r)return c;a=Xt(o,r=c.line)}}function So(t,e,n,o){o-=go(e);var r=e.text.length,i=st((function(e){return oo(t,n,e-1).bottom<=o}),r,0);return{begin:i,end:r=st((function(e){return oo(t,n,e).top>o}),i,r)}}function Oo(t,e,n,o){return n||(n=no(t,e)),So(t,e,n,yo(t,e,oo(t,n,o),"line").top)}function To(t,e,n,o){return!(t.bottom<=n)&&(t.top>n||(o?t.left:t.right)>e)}function Po(t,e,n,o,r){r-=an(e);var i=no(t,e),a=go(e),s=0,l=e.text.length,c=!0,u=dt(e,t.doc.direction);if(u){var p=(t.options.lineWrapping?ko:Eo)(t,e,n,i,u,o,r);s=(c=1!=p.level)?p.from:p.to-1,l=c?p.to:p.from-1}var d,f,h=null,v=null,g=st((function(e){var n=oo(t,i,e);return n.top+=a,n.bottom+=a,!!To(n,o,r,!1)&&(n.top<=r&&n.left<=o&&(h=e,v=n),!0)}),s,l),y=!1;if(v){var m=o-v.left=_.bottom?1:0}return xo(n,g=at(e.text,g,1),f,y,o-d)}function Eo(t,e,n,o,r,i,a){var s=st((function(s){var l=r[s],c=1!=l.level;return To(_o(t,ie(n,c?l.to:l.from,c?"before":"after"),"line",e,o),i,a,!0)}),0,r.length-1),l=r[s];if(s>0){var c=1!=l.level,u=_o(t,ie(n,c?l.from:l.to,c?"after":"before"),"line",e,o);To(u,i,a,!0)&&u.top>a&&(l=r[s-1])}return l}function ko(t,e,n,o,r,i,a){var s=So(t,e,o,a),l=s.begin,c=s.end;/\s/.test(e.text.charAt(c-1))&&c--;for(var u=null,p=null,d=0;d=c||f.to<=l)){var h=oo(t,o,1!=f.level?Math.min(c,f.to)-1:Math.max(l,f.from)).right,v=hv)&&(u=f,p=v)}}return u||(u=r[r.length-1]),u.fromc&&(u={from:u.from,to:c,level:u.level}),u}function Ao(t){if(null!=t.cachedTextHeight)return t.cachedTextHeight;if(null==ro){ro=k("pre",null,"CodeMirror-line-like");for(var e=0;e<49;++e)ro.appendChild(document.createTextNode("x")),ro.appendChild(k("br"));ro.appendChild(document.createTextNode("x"))}E(t.measure,ro);var n=ro.offsetHeight/50;return n>3&&(t.cachedTextHeight=n),P(t.measure),n||1}function jo(t){if(null!=t.cachedCharWidth)return t.cachedCharWidth;var e=k("span","xxxxxxxxxx"),n=k("pre",[e],"CodeMirror-line-like");E(t.measure,n);var o=e.getBoundingClientRect(),r=(o.right-o.left)/10;return r>2&&(t.cachedCharWidth=r),r||10}function Mo(t){for(var e=t.display,n={},o={},r=e.gutters.clientLeft,i=e.gutters.firstChild,a=0;i;i=i.nextSibling,++a){var s=t.display.gutterSpecs[a].className;n[s]=i.offsetLeft+i.clientLeft+r,o[s]=i.clientWidth}return{fixedPos:Do(e),gutterTotalWidth:e.gutters.offsetWidth,gutterLeft:n,gutterWidth:o,wrapperWidth:e.wrapper.clientWidth}}function Do(t){return t.scroller.getBoundingClientRect().left-t.sizer.getBoundingClientRect().left}function Lo(t){var e=Ao(t.display),n=t.options.lineWrapping,o=n&&Math.max(5,t.display.scroller.clientWidth/jo(t.display)-3);return function(r){if(on(t.doc,r))return 0;var i=0;if(r.widgets)for(var a=0;a0&&(l=Xt(t.doc,c.line).text).length==c.ch){var u=V(l,l.length,t.options.tabSize)-l.length;c=ie(c.line,Math.max(0,Math.round((i-Gn(t.display).left)/jo(t.display))-u))}return c}function Ro(t,e){if(e>=t.display.viewTo)return null;if((e-=t.display.viewFrom)<0)return null;for(var n=t.display.view,o=0;oe)&&(r.updateLineNumbers=e),t.curOp.viewChanged=!0,e>=r.viewTo)Ae&&en(t.doc,e)r.viewFrom?Ho(t):(r.viewFrom+=o,r.viewTo+=o);else if(e<=r.viewFrom&&n>=r.viewTo)Ho(t);else if(e<=r.viewFrom){var i=Uo(t,n,n+o,1);i?(r.view=r.view.slice(i.index),r.viewFrom=i.lineN,r.viewTo+=o):Ho(t)}else if(n>=r.viewTo){var a=Uo(t,e,e,-1);a?(r.view=r.view.slice(0,a.index),r.viewTo=a.lineN):Ho(t)}else{var s=Uo(t,e,e,-1),l=Uo(t,n,n+o,1);s&&l?(r.view=r.view.slice(0,s.index).concat(Cn(t,s.lineN,l.lineN)).concat(r.view.slice(l.index)),r.viewTo+=o):Ho(t)}var c=r.externalMeasured;c&&(n=r.lineN&&e=o.viewTo)){var i=o.view[Ro(t,e)];if(null!=i.node){var a=i.changes||(i.changes=[]);-1==H(a,n)&&a.push(n)}}}function Ho(t){t.display.viewFrom=t.display.viewTo=t.doc.first,t.display.view=[],t.display.viewOffset=0}function Uo(t,e,n,o){var r,i=Ro(t,e),a=t.display.view;if(!Ae||n==t.doc.first+t.doc.size)return{index:i,lineN:n};for(var s=t.display.viewFrom,l=0;l0){if(i==a.length-1)return null;r=s+a[i].size-e,i++}else r=s-e;e+=r,n+=r}for(;en(t.doc,n)!=n;){if(i==(o<0?0:a.length-1))return null;n+=o*a[i-(o<0?1:0)].size,i+=o}return{index:i,lineN:n}}function zo(t,e,n){var o=t.display;0==o.view.length||e>=o.viewTo||n<=o.viewFrom?(o.view=Cn(t,e,n),o.viewFrom=e):(o.viewFrom>e?o.view=Cn(t,e,o.viewFrom).concat(o.view):o.viewFromn&&(o.view=o.view.slice(0,Ro(t,n)))),o.viewTo=n}function Bo(t){for(var e=t.display.view,n=0,o=0;o=t.display.viewTo||s.to().line0&&(r.style.width=i.right-i.left+"px")}if(o.other){var a=n.appendChild(k("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));a.style.display="",a.style.left=o.other.left+"px",a.style.top=o.other.top+"px",a.style.height=.85*(o.other.bottom-o.other.top)+"px"}}function Go(t,e){return t.top-e.top||t.left-e.left}function Ko(t,e,n){var o=t.display,r=t.doc,i=document.createDocumentFragment(),a=Gn(t.display),s=a.left,l=Math.max(o.sizerWidth,Yn(t)-o.sizer.offsetLeft)-a.right,c="ltr"==r.direction;function u(t,e,n,o){e<0&&(e=0),e=Math.round(e),o=Math.round(o),i.appendChild(k("div",null,"CodeMirror-selected","position: absolute; left: "+t+"px;\n top: "+e+"px; width: "+(null==n?l-t:n)+"px;\n height: "+(o-e)+"px"))}function p(e,n,o){var i,a,p=Xt(r,e),d=p.text.length;function f(n,o){return bo(t,ie(e,n),"div",p,o)}function h(e,n,o){var r=Oo(t,p,null,e),i="ltr"==n==("after"==o)?"left":"right";return f("after"==o?r.begin:r.end-(/\s/.test(p.text.charAt(r.end-1))?2:1),i)[i]}var v=dt(p,r.direction);return lt(v,n||0,null==o?d:o,(function(t,e,r,p){var g="ltr"==r,y=f(t,g?"left":"right"),m=f(e-1,g?"right":"left"),b=null==n&&0==t,_=null==o&&e==d,w=0==p,x=!v||p==v.length-1;if(m.top-y.top<=3){var C=(c?_:b)&&x,S=(c?b:_)&&w?s:(g?y:m).left,O=C?l:(g?m:y).right;u(S,y.top,O-S,y.bottom)}else{var T,P,E,k;g?(T=c&&b&&w?s:y.left,P=c?l:h(t,r,"before"),E=c?s:h(e,r,"after"),k=c&&_&&x?l:m.right):(T=c?h(t,r,"before"):s,P=!c&&b&&w?l:y.right,E=!c&&_&&x?s:m.left,k=c?h(e,r,"after"):l),u(T,y.top,P-T,y.bottom),y.bottom0?e.blinker=setInterval((function(){t.hasFocus()||Qo(t),e.cursorDiv.style.visibility=(n=!n)?"":"hidden"}),t.options.cursorBlinkRate):t.options.cursorBlinkRate<0&&(e.cursorDiv.style.visibility="hidden")}}function Jo(t){t.hasFocus()||(t.display.input.focus(),t.state.focused||Zo(t))}function Xo(t){t.state.delayingBlurEvent=!0,setTimeout((function(){t.state.delayingBlurEvent&&(t.state.delayingBlurEvent=!1,t.state.focused&&Qo(t))}),100)}function Zo(t,e){t.state.delayingBlurEvent&&!t.state.draggingText&&(t.state.delayingBlurEvent=!1),"nocursor"!=t.options.readOnly&&(t.state.focused||(yt(t,"focus",t,e),t.state.focused=!0,D(t.display.wrapper,"CodeMirror-focused"),t.curOp||t.display.selForContextMenu==t.doc.sel||(t.display.input.reset(),l&&setTimeout((function(){return t.display.input.reset(!0)}),20)),t.display.input.receivedFocus()),Yo(t))}function Qo(t,e){t.state.delayingBlurEvent||(t.state.focused&&(yt(t,"blur",t,e),t.state.focused=!1,T(t.display.wrapper,"CodeMirror-focused")),clearInterval(t.display.blinker),setTimeout((function(){t.state.focused||(t.display.shift=!1)}),150))}function tr(t){for(var e=t.display,n=e.lineDiv.offsetTop,o=Math.max(0,e.scroller.getBoundingClientRect().top),r=e.lineDiv.getBoundingClientRect().top,i=0,l=0;l.005||v<-.005)&&(rt.display.sizerWidth){var y=Math.ceil(d/jo(t.display));y>t.display.maxLineLength&&(t.display.maxLineLength=y,t.display.maxLine=c.line,t.display.maxLineChanged=!0)}}}Math.abs(i)>2&&(e.scroller.scrollTop+=i)}function er(t){if(t.widgets)for(var e=0;e=a&&(i=ne(e,an(Xt(e,l))-t.wrapper.clientHeight),a=l)}return{from:i,to:Math.max(a,i+1)}}function or(t,e){if(!mt(t,"scrollCursorIntoView")){var n=t.display,o=n.sizer.getBoundingClientRect(),r=null;if(e.top+o.top<0?r=!0:e.bottom+o.top>(window.innerHeight||document.documentElement.clientHeight)&&(r=!1),null!=r&&!h){var i=k("div","​",null,"position: absolute;\n top: "+(e.top-n.viewOffset-$n(t.display))+"px;\n height: "+(e.bottom-e.top+Kn(t)+n.barHeight)+"px;\n left: "+e.left+"px; width: "+Math.max(2,e.right-e.left)+"px;");t.display.lineSpace.appendChild(i),i.scrollIntoView(r),t.display.lineSpace.removeChild(i)}}}function rr(t,e,n,o){var r;null==o&&(o=0),t.options.lineWrapping||e!=n||(n="before"==e.sticky?ie(e.line,e.ch+1,"before"):e,e=e.ch?ie(e.line,"before"==e.sticky?e.ch-1:e.ch,"after"):e);for(var i=0;i<5;i++){var a=!1,s=_o(t,e),l=n&&n!=e?_o(t,n):s,c=ar(t,r={left:Math.min(s.left,l.left),top:Math.min(s.top,l.top)-o,right:Math.max(s.left,l.left),bottom:Math.max(s.bottom,l.bottom)+o}),u=t.doc.scrollTop,p=t.doc.scrollLeft;if(null!=c.scrollTop&&(fr(t,c.scrollTop),Math.abs(t.doc.scrollTop-u)>1&&(a=!0)),null!=c.scrollLeft&&(vr(t,c.scrollLeft),Math.abs(t.doc.scrollLeft-p)>1&&(a=!0)),!a)break}return r}function ir(t,e){var n=ar(t,e);null!=n.scrollTop&&fr(t,n.scrollTop),null!=n.scrollLeft&&vr(t,n.scrollLeft)}function ar(t,e){var n=t.display,o=Ao(t.display);e.top<0&&(e.top=0);var r=t.curOp&&null!=t.curOp.scrollTop?t.curOp.scrollTop:n.scroller.scrollTop,i=Jn(t),a={};e.bottom-e.top>i&&(e.bottom=e.top+i);var s=t.doc.height+qn(n),l=e.tops-o;if(e.topr+i){var u=Math.min(e.top,(c?s:e.bottom)-i);u!=r&&(a.scrollTop=u)}var p=t.options.fixedGutter?0:n.gutters.offsetWidth,d=t.curOp&&null!=t.curOp.scrollLeft?t.curOp.scrollLeft:n.scroller.scrollLeft-p,f=Yn(t)-n.gutters.offsetWidth,h=e.right-e.left>f;return h&&(e.right=e.left+f),e.left<10?a.scrollLeft=0:e.leftf+d-3&&(a.scrollLeft=e.right+(h?0:10)-f),a}function sr(t,e){null!=e&&(pr(t),t.curOp.scrollTop=(null==t.curOp.scrollTop?t.doc.scrollTop:t.curOp.scrollTop)+e)}function lr(t){pr(t);var e=t.getCursor();t.curOp.scrollToPos={from:e,to:e,margin:t.options.cursorScrollMargin}}function cr(t,e,n){null==e&&null==n||pr(t),null!=e&&(t.curOp.scrollLeft=e),null!=n&&(t.curOp.scrollTop=n)}function ur(t,e){pr(t),t.curOp.scrollToPos=e}function pr(t){var e=t.curOp.scrollToPos;e&&(t.curOp.scrollToPos=null,dr(t,wo(t,e.from),wo(t,e.to),e.margin))}function dr(t,e,n,o){var r=ar(t,{left:Math.min(e.left,n.left),top:Math.min(e.top,n.top)-o,right:Math.max(e.right,n.right),bottom:Math.max(e.bottom,n.bottom)+o});cr(t,r.scrollLeft,r.scrollTop)}function fr(t,e){Math.abs(t.doc.scrollTop-e)<2||(n||Wr(t,{top:e}),hr(t,e,!0),n&&Wr(t),Nr(t,100))}function hr(t,e,n){e=Math.max(0,Math.min(t.display.scroller.scrollHeight-t.display.scroller.clientHeight,e)),(t.display.scroller.scrollTop!=e||n)&&(t.doc.scrollTop=e,t.display.scrollbars.setScrollTop(e),t.display.scroller.scrollTop!=e&&(t.display.scroller.scrollTop=e))}function vr(t,e,n,o){e=Math.max(0,Math.min(e,t.display.scroller.scrollWidth-t.display.scroller.clientWidth)),(n?e==t.doc.scrollLeft:Math.abs(t.doc.scrollLeft-e)<2)&&!o||(t.doc.scrollLeft=e,Kr(t),t.display.scroller.scrollLeft!=e&&(t.display.scroller.scrollLeft=e),t.display.scrollbars.setScrollLeft(e))}function gr(t){var e=t.display,n=e.gutters.offsetWidth,o=Math.round(t.doc.height+qn(t.display));return{clientHeight:e.scroller.clientHeight,viewHeight:e.wrapper.clientHeight,scrollWidth:e.scroller.scrollWidth,clientWidth:e.scroller.clientWidth,viewWidth:e.wrapper.clientWidth,barLeft:t.options.fixedGutter?n:0,docHeight:o,scrollHeight:o+Kn(t)+e.barHeight,nativeBarWidth:e.nativeBarWidth,gutterWidth:n}}var yr=function(t,e,n){this.cm=n;var o=this.vert=k("div",[k("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),r=this.horiz=k("div",[k("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");o.tabIndex=r.tabIndex=-1,t(o),t(r),ht(o,"scroll",(function(){o.clientHeight&&e(o.scrollTop,"vertical")})),ht(r,"scroll",(function(){r.clientWidth&&e(r.scrollLeft,"horizontal")})),this.checkedZeroWidth=!1,a&&s<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};yr.prototype.update=function(t){var e=t.scrollWidth>t.clientWidth+1,n=t.scrollHeight>t.clientHeight+1,o=t.nativeBarWidth;if(n){this.vert.style.display="block",this.vert.style.bottom=e?o+"px":"0";var r=t.viewHeight-(e?o:0);this.vert.firstChild.style.height=Math.max(0,t.scrollHeight-t.clientHeight+r)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(e){this.horiz.style.display="block",this.horiz.style.right=n?o+"px":"0",this.horiz.style.left=t.barLeft+"px";var i=t.viewWidth-t.barLeft-(n?o:0);this.horiz.firstChild.style.width=Math.max(0,t.scrollWidth-t.clientWidth+i)+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&t.clientHeight>0&&(0==o&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:n?o:0,bottom:e?o:0}},yr.prototype.setScrollLeft=function(t){this.horiz.scrollLeft!=t&&(this.horiz.scrollLeft=t),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")},yr.prototype.setScrollTop=function(t){this.vert.scrollTop!=t&&(this.vert.scrollTop=t),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")},yr.prototype.zeroWidthHack=function(){var t=m&&!f?"12px":"18px";this.horiz.style.height=this.vert.style.width=t,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new F,this.disableVert=new F},yr.prototype.enableZeroWidthBar=function(t,e,n){function o(){var r=t.getBoundingClientRect();("vert"==n?document.elementFromPoint(r.right-1,(r.top+r.bottom)/2):document.elementFromPoint((r.right+r.left)/2,r.bottom-1))!=t?t.style.pointerEvents="none":e.set(1e3,o)}t.style.pointerEvents="auto",e.set(1e3,o)},yr.prototype.clear=function(){var t=this.horiz.parentNode;t.removeChild(this.horiz),t.removeChild(this.vert)};var mr=function(){};function br(t,e){e||(e=gr(t));var n=t.display.barWidth,o=t.display.barHeight;_r(t,e);for(var r=0;r<4&&n!=t.display.barWidth||o!=t.display.barHeight;r++)n!=t.display.barWidth&&t.options.lineWrapping&&tr(t),_r(t,gr(t)),n=t.display.barWidth,o=t.display.barHeight}function _r(t,e){var n=t.display,o=n.scrollbars.update(e);n.sizer.style.paddingRight=(n.barWidth=o.right)+"px",n.sizer.style.paddingBottom=(n.barHeight=o.bottom)+"px",n.heightForcer.style.borderBottom=o.bottom+"px solid transparent",o.right&&o.bottom?(n.scrollbarFiller.style.display="block",n.scrollbarFiller.style.height=o.bottom+"px",n.scrollbarFiller.style.width=o.right+"px"):n.scrollbarFiller.style.display="",o.bottom&&t.options.coverGutterNextToScrollbar&&t.options.fixedGutter?(n.gutterFiller.style.display="block",n.gutterFiller.style.height=o.bottom+"px",n.gutterFiller.style.width=e.gutterWidth+"px"):n.gutterFiller.style.display=""}mr.prototype.update=function(){return{bottom:0,right:0}},mr.prototype.setScrollLeft=function(){},mr.prototype.setScrollTop=function(){},mr.prototype.clear=function(){};var wr={native:yr,null:mr};function xr(t){t.display.scrollbars&&(t.display.scrollbars.clear(),t.display.scrollbars.addClass&&T(t.display.wrapper,t.display.scrollbars.addClass)),t.display.scrollbars=new wr[t.options.scrollbarStyle]((function(e){t.display.wrapper.insertBefore(e,t.display.scrollbarFiller),ht(e,"mousedown",(function(){t.state.focused&&setTimeout((function(){return t.display.input.focus()}),0)})),e.setAttribute("cm-not-content","true")}),(function(e,n){"horizontal"==n?vr(t,e):fr(t,e)}),t),t.display.scrollbars.addClass&&D(t.display.wrapper,t.display.scrollbars.addClass)}var Cr=0;function Sr(t){t.curOp={cm:t,viewChanged:!1,startHeight:t.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Cr,markArrays:null},On(t.curOp)}function Or(t){var e=t.curOp;e&&Pn(e,(function(t){for(var e=0;e=n.viewTo)||n.maxLineChanged&&e.options.lineWrapping,t.update=t.mustUpdate&&new Vr(e,t.mustUpdate&&{top:t.scrollTop,ensure:t.scrollToPos},t.forceUpdate)}function Er(t){t.updatedDisplay=t.mustUpdate&&zr(t.cm,t.update)}function kr(t){var e=t.cm,n=e.display;t.updatedDisplay&&tr(e),t.barMeasure=gr(e),n.maxLineChanged&&!e.options.lineWrapping&&(t.adjustWidthTo=to(e,n.maxLine,n.maxLine.text.length).left+3,e.display.sizerWidth=t.adjustWidthTo,t.barMeasure.scrollWidth=Math.max(n.scroller.clientWidth,n.sizer.offsetLeft+t.adjustWidthTo+Kn(e)+e.display.barWidth),t.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+t.adjustWidthTo-Yn(e))),(t.updatedDisplay||t.selectionChanged)&&(t.preparedSelection=n.input.prepareSelection())}function Ar(t){var e=t.cm;null!=t.adjustWidthTo&&(e.display.sizer.style.minWidth=t.adjustWidthTo+"px",t.maxScrollLeft=t.display.viewTo)){var n=+new Date+t.options.workTime,o=be(t,e.highlightFrontier),r=[];e.iter(o.line,Math.min(e.first+e.size,t.display.viewTo+500),(function(i){if(o.line>=t.display.viewFrom){var a=i.styles,s=i.text.length>t.options.maxHighlightLength?Gt(e.mode,o.state):null,l=ye(t,i,o,!0);s&&(o.state=s),i.styles=l.styles;var c=i.styleClasses,u=l.classes;u?i.styleClasses=u:c&&(i.styleClasses=null);for(var p=!a||a.length!=i.styles.length||c!=u&&(!c||!u||c.bgClass!=u.bgClass||c.textClass!=u.textClass),d=0;!p&&dn)return Nr(t,t.options.workDelay),!0})),e.highlightFrontier=o.line,e.modeFrontier=Math.max(e.modeFrontier,o.line),r.length&&Mr(t,(function(){for(var e=0;e=n.viewFrom&&e.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&n.renderedView==n.view&&0==Bo(t))return!1;Yr(t)&&(Ho(t),e.dims=Mo(t));var r=o.first+o.size,i=Math.max(e.visible.from-t.options.viewportMargin,o.first),a=Math.min(r,e.visible.to+t.options.viewportMargin);n.viewFroma&&n.viewTo-a<20&&(a=Math.min(r,n.viewTo)),Ae&&(i=en(t.doc,i),a=nn(t.doc,a));var s=i!=n.viewFrom||a!=n.viewTo||n.lastWrapHeight!=e.wrapperHeight||n.lastWrapWidth!=e.wrapperWidth;zo(t,i,a),n.viewOffset=an(Xt(t.doc,n.viewFrom)),t.display.mover.style.top=n.viewOffset+"px";var l=Bo(t);if(!s&&0==l&&!e.force&&n.renderedView==n.view&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;var c=Hr(t);return l>4&&(n.lineDiv.style.display="none"),$r(t,n.updateLineNumbers,e.dims),l>4&&(n.lineDiv.style.display=""),n.renderedView=n.view,Ur(c),P(n.cursorDiv),P(n.selectionDiv),n.gutters.style.height=n.sizer.style.minHeight=0,s&&(n.lastWrapHeight=e.wrapperHeight,n.lastWrapWidth=e.wrapperWidth,Nr(t,400)),n.updateLineNumbers=null,!0}function Br(t,e){for(var n=e.viewport,o=!0;;o=!1){if(o&&t.options.lineWrapping&&e.oldDisplayWidth!=Yn(t))o&&(e.visible=nr(t.display,t.doc,n));else if(n&&null!=n.top&&(n={top:Math.min(t.doc.height+qn(t.display)-Jn(t),n.top)}),e.visible=nr(t.display,t.doc,n),e.visible.from>=t.display.viewFrom&&e.visible.to<=t.display.viewTo)break;if(!zr(t,e))break;tr(t);var r=gr(t);Wo(t),br(t,r),Gr(t,r),e.force=!1}e.signal(t,"update",t),t.display.viewFrom==t.display.reportedViewFrom&&t.display.viewTo==t.display.reportedViewTo||(e.signal(t,"viewportChange",t,t.display.viewFrom,t.display.viewTo),t.display.reportedViewFrom=t.display.viewFrom,t.display.reportedViewTo=t.display.viewTo)}function Wr(t,e){var n=new Vr(t,e);if(zr(t,n)){tr(t),Br(t,n);var o=gr(t);Wo(t),br(t,o),Gr(t,o),n.finish()}}function $r(t,e,n){var o=t.display,r=t.options.lineNumbers,i=o.lineDiv,a=i.firstChild;function s(e){var n=e.nextSibling;return l&&m&&t.display.currentWheelTarget==e?e.style.display="none":e.parentNode.removeChild(e),n}for(var c=o.view,u=o.viewFrom,p=0;p-1&&(f=!1),jn(t,d,u,n)),f&&(P(d.lineNumber),d.lineNumber.appendChild(document.createTextNode(re(t.options,u)))),a=d.node.nextSibling}else{var h=Fn(t,d,u,n);i.insertBefore(h,a)}u+=d.size}for(;a;)a=s(a)}function qr(t){var e=t.gutters.offsetWidth;t.sizer.style.marginLeft=e+"px",kn(t,"gutterChanged",t)}function Gr(t,e){t.display.sizer.style.minHeight=e.docHeight+"px",t.display.heightForcer.style.top=e.docHeight+"px",t.display.gutters.style.height=e.docHeight+t.display.barHeight+Kn(t)+"px"}function Kr(t){var e=t.display,n=e.view;if(e.alignWidgets||e.gutters.firstChild&&t.options.fixedGutter){for(var o=Do(e)-e.scroller.scrollLeft+t.doc.scrollLeft,r=e.gutters.offsetWidth,i=o+"px",a=0;as.clientWidth,u=s.scrollHeight>s.clientHeight;if(r&&c||i&&u){if(i&&m&&l)t:for(var d=e.target,f=a.view;d!=s;d=d.parentNode)for(var h=0;h=0&&ae(t,o.to())<=0)return n}return-1};var ai=function(t,e){this.anchor=t,this.head=e};function si(t,e,n){var o=t&&t.options.selectionsMayTouch,r=e[n];e.sort((function(t,e){return ae(t.from(),e.from())})),n=H(e,r);for(var i=1;i0:l>=0){var c=ue(s.from(),a.from()),u=ce(s.to(),a.to()),p=s.empty()?a.from()==a.head:s.from()==s.head;i<=n&&--n,e.splice(--i,2,new ai(p?u:c,p?c:u))}}return new ii(e,n)}function li(t,e){return new ii([new ai(t,e||t)],0)}function ci(t){return t.text?ie(t.from.line+t.text.length-1,Y(t.text).length+(1==t.text.length?t.from.ch:0)):t.to}function ui(t,e){if(ae(t,e.from)<0)return t;if(ae(t,e.to)<=0)return ci(e);var n=t.line+e.text.length-(e.to.line-e.from.line)-1,o=t.ch;return t.line==e.to.line&&(o+=ci(e).ch-e.to.ch),ie(n,o)}function pi(t,e){for(var n=[],o=0;o1&&t.remove(s.line+1,h-1),t.insert(s.line+1,y)}kn(t,"change",t,e)}function mi(t,e,n){function o(t,r,i){if(t.linked)for(var a=0;a1&&!t.done[t.done.length-2].ranges?(t.done.pop(),Y(t.done)):void 0}function Ti(t,e,n,o){var r=t.history;r.undone.length=0;var i,a,s=+new Date;if((r.lastOp==o||r.lastOrigin==e.origin&&e.origin&&("+"==e.origin.charAt(0)&&r.lastModTime>s-(t.cm?t.cm.options.historyEventDelay:500)||"*"==e.origin.charAt(0)))&&(i=Oi(r,r.lastOp==o)))a=Y(i.changes),0==ae(e.from,e.to)&&0==ae(e.from,a.to)?a.to=ci(e):i.changes.push(Ci(t,e));else{var l=Y(r.done);for(l&&l.ranges||ki(t.sel,r.done),i={changes:[Ci(t,e)],generation:r.generation},r.done.push(i);r.done.length>r.undoDepth;)r.done.shift(),r.done[0].ranges||r.done.shift()}r.done.push(n),r.generation=++r.maxGeneration,r.lastModTime=r.lastSelTime=s,r.lastOp=r.lastSelOp=o,r.lastOrigin=r.lastSelOrigin=e.origin,a||yt(t,"historyAdded")}function Pi(t,e,n,o){var r=e.charAt(0);return"*"==r||"+"==r&&n.ranges.length==o.ranges.length&&n.somethingSelected()==o.somethingSelected()&&new Date-t.history.lastSelTime<=(t.cm?t.cm.options.historyEventDelay:500)}function Ei(t,e,n,o){var r=t.history,i=o&&o.origin;n==r.lastSelOp||i&&r.lastSelOrigin==i&&(r.lastModTime==r.lastSelTime&&r.lastOrigin==i||Pi(t,i,Y(r.done),e))?r.done[r.done.length-1]=e:ki(e,r.done),r.lastSelTime=+new Date,r.lastSelOrigin=i,r.lastSelOp=n,o&&!1!==o.clearRedo&&Si(r.undone)}function ki(t,e){var n=Y(e);n&&n.ranges&&n.equals(t)||e.push(t)}function Ai(t,e,n,o){var r=e["spans_"+t.id],i=0;t.iter(Math.max(t.first,n),Math.min(t.first+t.size,o),(function(n){n.markedSpans&&((r||(r=e["spans_"+t.id]={}))[i]=n.markedSpans),++i}))}function ji(t){if(!t)return null;for(var e,n=0;n-1&&(Y(s)[p]=c[p],delete c[p])}}}return o}function Ii(t,e,n,o){if(o){var r=t.anchor;if(n){var i=ae(e,r)<0;i!=ae(n,r)<0?(r=e,e=n):i!=ae(e,n)<0&&(e=n)}return new ai(r,e)}return new ai(n||e,e)}function Ni(t,e,n,o,r){null==r&&(r=t.cm&&(t.cm.display.shift||t.extend)),zi(t,new ii([Ii(t.sel.primary(),e,n,r)],0),o)}function Ri(t,e,n){for(var o=[],r=t.cm&&(t.cm.display.shift||t.extend),i=0;i=e.ch:s.to>e.ch))){if(r&&(yt(l,"beforeCursorEnter"),l.explicitlyCleared)){if(i.markedSpans){--a;continue}break}if(!l.atomic)continue;if(n){var p=l.find(o<0?1:-1),d=void 0;if((o<0?u:c)&&(p=Yi(t,p,-o,p&&p.line==e.line?i:null)),p&&p.line==e.line&&(d=ae(p,n))&&(o<0?d<0:d>0))return Gi(t,p,e,o,r)}var f=l.find(o<0?-1:1);return(o<0?c:u)&&(f=Yi(t,f,o,f.line==e.line?i:null)),f?Gi(t,f,e,o,r):null}}return e}function Ki(t,e,n,o,r){var i=o||1,a=Gi(t,e,n,i,r)||!r&&Gi(t,e,n,i,!0)||Gi(t,e,n,-i,r)||!r&&Gi(t,e,n,-i,!0);return a||(t.cantEdit=!0,ie(t.first,0))}function Yi(t,e,n,o){return n<0&&0==e.ch?e.line>t.first?de(t,ie(e.line-1)):null:n>0&&e.ch==(o||Xt(t,e.line)).text.length?e.line=0;--r)Qi(t,{from:o[r].from,to:o[r].to,text:r?[""]:e.text,origin:e.origin});else Qi(t,e)}}function Qi(t,e){if(1!=e.text.length||""!=e.text[0]||0!=ae(e.from,e.to)){var n=pi(t,e);Ti(t,e,n,t.cm?t.cm.curOp.id:NaN),na(t,e,n,Fe(t,e));var o=[];mi(t,(function(t,n){n||-1!=H(o,t.history)||(sa(t.history,e),o.push(t.history)),na(t,e,null,Fe(t,e))}))}}function ta(t,e,n){var o=t.cm&&t.cm.state.suppressEdits;if(!o||n){for(var r,i=t.history,a=t.sel,s="undo"==e?i.done:i.undone,l="undo"==e?i.undone:i.done,c=0;c=0;--f){var h=d(f);if(h)return h.v}}}}function ea(t,e){if(0!=e&&(t.first+=e,t.sel=new ii(J(t.sel.ranges,(function(t){return new ai(ie(t.anchor.line+e,t.anchor.ch),ie(t.head.line+e,t.head.ch))})),t.sel.primIndex),t.cm)){Vo(t.cm,t.first,t.first-e,e);for(var n=t.cm.display,o=n.viewFrom;ot.lastLine())){if(e.from.linei&&(e={from:e.from,to:ie(i,Xt(t,i).text.length),text:[e.text[0]],origin:e.origin}),e.removed=Zt(t,e.from,e.to),n||(n=pi(t,e)),t.cm?oa(t.cm,e,o):yi(t,e,o),Bi(t,n,B),t.cantEdit&&Ki(t,ie(t.firstLine(),0))&&(t.cantEdit=!1)}}function oa(t,e,n){var o=t.doc,r=t.display,i=e.from,a=e.to,s=!1,l=i.line;t.options.lineWrapping||(l=ee(Ze(Xt(o,i.line))),o.iter(l,a.line+1,(function(t){if(t==r.maxLine)return s=!0,!0}))),o.sel.contains(e.from,e.to)>-1&&bt(t),yi(o,e,n,Lo(t)),t.options.lineWrapping||(o.iter(l,i.line+e.text.length,(function(t){var e=sn(t);e>r.maxLineLength&&(r.maxLine=t,r.maxLineLength=e,r.maxLineChanged=!0,s=!1)})),s&&(t.curOp.updateMaxLine=!0)),Ee(o,i.line),Nr(t,400);var c=e.text.length-(a.line-i.line)-1;e.full?Vo(t):i.line!=a.line||1!=e.text.length||gi(t.doc,e)?Vo(t,i.line,a.line+1,c):Fo(t,i.line,"text");var u=_t(t,"changes"),p=_t(t,"change");if(p||u){var d={from:i,to:a,text:e.text,removed:e.removed,origin:e.origin};p&&kn(t,"change",t,d),u&&(t.curOp.changeObjs||(t.curOp.changeObjs=[])).push(d)}t.display.selForContextMenu=null}function ra(t,e,n,o,r){var i;o||(o=n),ae(o,n)<0&&(n=(i=[o,n])[0],o=i[1]),"string"==typeof e&&(e=t.splitLines(e)),Zi(t,{from:n,to:o,text:e,origin:r})}function ia(t,e,n,o){n1||!(this.children[0]instanceof ca))){var s=[];this.collapse(s),this.children=[new ca(s)],this.children[0].parent=this}},collapse:function(t){for(var e=0;e50){for(var a=r.lines.length%25+25,s=a;s10);t.parent.maybeSpill()}},iterN:function(t,e,n){for(var o=0;o0||0==a&&!1!==i.clearWhenEmpty)return i;if(i.replacedWith&&(i.collapsed=!0,i.widgetNode=A("span",[i.replacedWith],"CodeMirror-widget"),o.handleMouseEvents||i.widgetNode.setAttribute("cm-ignore-events","true"),o.insertLeft&&(i.widgetNode.insertLeft=!0)),i.collapsed){if(Xe(t,e.line,e,n,i)||e.line!=n.line&&Xe(t,n.line,e,n,i))throw new Error("Inserting collapsed marker partially overlapping an existing one");Me()}i.addToHistory&&Ti(t,{from:e,to:n,origin:"markText"},t.sel,NaN);var s,l=e.line,c=t.cm;if(t.iter(l,n.line+1,(function(o){c&&i.collapsed&&!c.options.lineWrapping&&Ze(o)==c.display.maxLine&&(s=!0),i.collapsed&&l!=e.line&&te(o,0),Ne(o,new De(i,l==e.line?e.ch:null,l==n.line?n.ch:null),t.cm&&t.cm.curOp),++l})),i.collapsed&&t.iter(e.line,n.line+1,(function(e){on(t,e)&&te(e,0)})),i.clearOnEnter&&ht(i,"beforeCursorEnter",(function(){return i.clear()})),i.readOnly&&(je(),(t.history.done.length||t.history.undone.length)&&t.clearHistory()),i.collapsed&&(i.id=++ha,i.atomic=!0),c){if(s&&(c.curOp.updateMaxLine=!0),i.collapsed)Vo(c,e.line,n.line+1);else if(i.className||i.startStyle||i.endStyle||i.css||i.attributes||i.title)for(var u=e.line;u<=n.line;u++)Fo(c,u,"text");i.atomic&&$i(c.doc),kn(c,"markerAdded",c,i)}return i}va.prototype.clear=function(){if(!this.explicitlyCleared){var t=this.doc.cm,e=t&&!t.curOp;if(e&&Sr(t),_t(this,"clear")){var n=this.find();n&&kn(this,"clear",n.from,n.to)}for(var o=null,r=null,i=0;it.display.maxLineLength&&(t.display.maxLine=c,t.display.maxLineLength=u,t.display.maxLineChanged=!0)}null!=o&&t&&this.collapsed&&Vo(t,o,r+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,t&&$i(t.doc)),t&&kn(t,"markerCleared",t,this,o,r),e&&Or(t),this.parent&&this.parent.clear()}},va.prototype.find=function(t,e){var n,o;null==t&&"bookmark"==this.type&&(t=1);for(var r=0;r=0;l--)Zi(this,o[l]);s?Ui(this,s):this.cm&&lr(this.cm)})),undo:Ir((function(){ta(this,"undo")})),redo:Ir((function(){ta(this,"redo")})),undoSelection:Ir((function(){ta(this,"undo",!0)})),redoSelection:Ir((function(){ta(this,"redo",!0)})),setExtending:function(t){this.extend=t},getExtending:function(){return this.extend},historySize:function(){for(var t=this.history,e=0,n=0,o=0;o=t.ch)&&e.push(r.marker.parent||r.marker)}return e},findMarks:function(t,e,n){t=de(this,t),e=de(this,e);var o=[],r=t.line;return this.iter(t.line,e.line+1,(function(i){var a=i.markedSpans;if(a)for(var s=0;s=l.to||null==l.from&&r!=t.line||null!=l.from&&r==e.line&&l.from>=e.ch||n&&!n(l.marker)||o.push(l.marker.parent||l.marker)}++r})),o},getAllMarks:function(){var t=[];return this.iter((function(e){var n=e.markedSpans;if(n)for(var o=0;ot)return e=t,!0;t-=i,++n})),de(this,ie(n,e))},indexFromPos:function(t){var e=(t=de(this,t)).ch;if(t.linee&&(e=t.from),null!=t.to&&t.to-1)return e.state.draggingText(t),void setTimeout((function(){return e.display.input.focus()}),20);try{var p=t.dataTransfer.getData("Text");if(p){var d;if(e.state.draggingText&&!e.state.draggingText.copy&&(d=e.listSelections()),Bi(e.doc,li(n,n)),d)for(var f=0;f=0;e--)ra(t.doc,"",o[e].from,o[e].to,"+delete");lr(t)}))}function Ga(t,e,n){var o=at(t.text,e+n,n);return o<0||o>t.text.length?null:o}function Ka(t,e,n){var o=Ga(t,e.ch,n);return null==o?null:new ie(e.line,o,n<0?"after":"before")}function Ya(t,e,n,o,r){if(t){"rtl"==e.doc.direction&&(r=-r);var i=dt(n,e.doc.direction);if(i){var a,s=r<0?Y(i):i[0],l=r<0==(1==s.level)?"after":"before";if(s.level>0||"rtl"==e.doc.direction){var c=no(e,n);a=r<0?n.text.length-1:0;var u=oo(e,c,a).top;a=st((function(t){return oo(e,c,t).top==u}),r<0==(1==s.level)?s.from:s.to-1,a),"before"==l&&(a=Ga(n,a,1))}else a=r<0?s.to:s.from;return new ie(o,a,l)}}return new ie(o,r<0?n.text.length:0,r<0?"before":"after")}function Ja(t,e,n,o){var r=dt(e,t.doc.direction);if(!r)return Ka(e,n,o);n.ch>=e.text.length?(n.ch=e.text.length,n.sticky="before"):n.ch<=0&&(n.ch=0,n.sticky="after");var i=ut(r,n.ch,n.sticky),a=r[i];if("ltr"==t.doc.direction&&a.level%2==0&&(o>0?a.to>n.ch:a.from=a.from&&d>=u.begin)){var f=p?"before":"after";return new ie(n.line,d,f)}}var h=function(t,e,o){for(var i=function(t,e){return e?new ie(n.line,l(t,1),"before"):new ie(n.line,t,"after")};t>=0&&t0==(1!=a.level),c=s?o.begin:l(o.end,-1);if(a.from<=c&&c0?u.end:l(u.begin,-1);return null==g||o>0&&g==e.text.length||!(v=h(o>0?0:r.length-1,o,c(g)))?null:v}Va.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Va.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Va.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"},Va.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},Va["default"]=m?Va.macDefault:Va.pcDefault;var Xa={selectAll:Ji,singleSelection:function(t){return t.setSelection(t.getCursor("anchor"),t.getCursor("head"),B)},killLine:function(t){return qa(t,(function(e){if(e.empty()){var n=Xt(t.doc,e.head.line).text.length;return e.head.ch==n&&e.head.line0)r=new ie(r.line,r.ch+1),t.replaceRange(i.charAt(r.ch-1)+i.charAt(r.ch-2),ie(r.line,r.ch-2),r,"+transpose");else if(r.line>t.doc.first){var a=Xt(t.doc,r.line-1).text;a&&(r=new ie(r.line,1),t.replaceRange(i.charAt(0)+t.doc.lineSeparator()+a.charAt(a.length-1),ie(r.line-1,a.length-1),r,"+transpose"))}n.push(new ai(r,r))}t.setSelections(n)}))},newlineAndIndent:function(t){return Mr(t,(function(){for(var e=t.listSelections(),n=e.length-1;n>=0;n--)t.replaceRange(t.doc.lineSeparator(),e[n].anchor,e[n].head,"+input");e=t.listSelections();for(var o=0;o-1&&(ae((r=s.ranges[r]).from(),e)<0||e.xRel>0)&&(ae(r.to(),e)>0||e.xRel<0)?xs(t,o,e,i):Ss(t,o,e,i)}function xs(t,e,n,o){var r=t.display,i=!1,c=Dr(t,(function(e){l&&(r.scroller.draggable=!1),t.state.draggingText=!1,t.state.delayingBlurEvent&&(t.hasFocus()?t.state.delayingBlurEvent=!1:Xo(t)),gt(r.wrapper.ownerDocument,"mouseup",c),gt(r.wrapper.ownerDocument,"mousemove",u),gt(r.scroller,"dragstart",p),gt(r.scroller,"drop",c),i||(xt(e),o.addNew||Ni(t.doc,n,null,null,o.extend),l&&!d||a&&9==s?setTimeout((function(){r.wrapper.ownerDocument.body.focus({preventScroll:!0}),r.input.focus()}),20):r.input.focus())})),u=function(t){i=i||Math.abs(e.clientX-t.clientX)+Math.abs(e.clientY-t.clientY)>=10},p=function(){return i=!0};l&&(r.scroller.draggable=!0),t.state.draggingText=c,c.copy=!o.moveOnDrag,ht(r.wrapper.ownerDocument,"mouseup",c),ht(r.wrapper.ownerDocument,"mousemove",u),ht(r.scroller,"dragstart",p),ht(r.scroller,"drop",c),t.state.delayingBlurEvent=!0,setTimeout((function(){return r.input.focus()}),20),r.scroller.dragDrop&&r.scroller.dragDrop()}function Cs(t,e,n){if("char"==n)return new ai(e,e);if("word"==n)return t.findWordAt(e);if("line"==n)return new ai(ie(e.line,0),de(t.doc,ie(e.line+1,0)));var o=n(t,e);return new ai(o.from,o.to)}function Ss(t,e,n,o){a&&Xo(t);var r=t.display,i=t.doc;xt(e);var s,l,c=i.sel,u=c.ranges;if(o.addNew&&!o.extend?(l=i.sel.contains(n),s=l>-1?u[l]:new ai(n,n)):(s=i.sel.primary(),l=i.sel.primIndex),"rectangle"==o.unit)o.addNew||(s=new ai(n,n)),n=No(t,e,!0,!0),l=-1;else{var p=Cs(t,n,o.unit);s=o.extend?Ii(s,p.anchor,p.head,o.extend):p}o.addNew?-1==l?(l=u.length,zi(i,si(t,u.concat([s]),l),{scroll:!1,origin:"*mouse"})):u.length>1&&u[l].empty()&&"char"==o.unit&&!o.extend?(zi(i,si(t,u.slice(0,l).concat(u.slice(l+1)),0),{scroll:!1,origin:"*mouse"}),c=i.sel):Vi(i,l,s,W):(l=0,zi(i,new ii([s],0),W),c=i.sel);var d=n;function f(e){if(0!=ae(d,e))if(d=e,"rectangle"==o.unit){for(var r=[],a=t.options.tabSize,u=V(Xt(i,n.line).text,n.ch,a),p=V(Xt(i,e.line).text,e.ch,a),f=Math.min(u,p),h=Math.max(u,p),v=Math.min(n.line,e.line),g=Math.min(t.lastLine(),Math.max(n.line,e.line));v<=g;v++){var y=Xt(i,v).text,m=q(y,f,a);f==h?r.push(new ai(ie(v,m),ie(v,m))):y.length>m&&r.push(new ai(ie(v,m),ie(v,q(y,h,a))))}r.length||r.push(new ai(n,n)),zi(i,si(t,c.ranges.slice(0,l).concat(r),l),{origin:"*mouse",scroll:!1}),t.scrollIntoView(e)}else{var b,_=s,w=Cs(t,e,o.unit),x=_.anchor;ae(w.anchor,x)>0?(b=w.head,x=ue(_.from(),w.anchor)):(b=w.anchor,x=ce(_.to(),w.head));var C=c.ranges.slice(0);C[l]=Os(t,new ai(de(i,x),b)),zi(i,si(t,C,l),W)}}var h=r.wrapper.getBoundingClientRect(),v=0;function g(e){var n=++v,a=No(t,e,!0,"rectangle"==o.unit);if(a)if(0!=ae(a,d)){t.curOp.focus=M(),f(a);var s=nr(r,i);(a.line>=s.to||a.lineh.bottom?20:0;l&&setTimeout(Dr(t,(function(){v==n&&(r.scroller.scrollTop+=l,g(e))})),50)}}function y(e){t.state.selectingText=!1,v=1/0,e&&(xt(e),r.input.focus()),gt(r.wrapper.ownerDocument,"mousemove",m),gt(r.wrapper.ownerDocument,"mouseup",b),i.history.lastSelOrigin=null}var m=Dr(t,(function(t){0!==t.buttons&&Pt(t)?g(t):y(t)})),b=Dr(t,y);t.state.selectingText=b,ht(r.wrapper.ownerDocument,"mousemove",m),ht(r.wrapper.ownerDocument,"mouseup",b)}function Os(t,e){var n=e.anchor,o=e.head,r=Xt(t.doc,n.line);if(0==ae(n,o)&&n.sticky==o.sticky)return e;var i=dt(r);if(!i)return e;var a=ut(i,n.ch,n.sticky),s=i[a];if(s.from!=n.ch&&s.to!=n.ch)return e;var l,c=a+(s.from==n.ch==(1!=s.level)?0:1);if(0==c||c==i.length)return e;if(o.line!=n.line)l=(o.line-n.line)*("ltr"==t.doc.direction?1:-1)>0;else{var u=ut(i,o.ch,o.sticky),p=u-a||(o.ch-n.ch)*(1==s.level?-1:1);l=u==c-1||u==c?p<0:p>0}var d=i[c+(l?-1:0)],f=l==(1==d.level),h=f?d.from:d.to,v=f?"after":"before";return n.ch==h&&n.sticky==v?e:new ai(new ie(n.line,h,v),o)}function Ts(t,e,n,o){var r,i;if(e.touches)r=e.touches[0].clientX,i=e.touches[0].clientY;else try{r=e.clientX,i=e.clientY}catch(t){return!1}if(r>=Math.floor(t.display.gutters.getBoundingClientRect().right))return!1;o&&xt(e);var a=t.display,s=a.lineDiv.getBoundingClientRect();if(i>s.bottom||!_t(t,n))return St(e);i-=s.top-a.viewOffset;for(var l=0;l=r)return yt(t,n,t,ne(t.doc,i),t.display.gutterSpecs[l].className,e),St(e)}}function Ps(t,e){return Ts(t,e,"gutterClick",!0)}function Es(t,e){Wn(t.display,e)||ks(t,e)||mt(t,e,"contextmenu")||C||t.display.input.onContextMenu(e)}function ks(t,e){return!!_t(t,"gutterContextMenu")&&Ts(t,e,"gutterContextMenu",!1)}function As(t){t.display.wrapper.className=t.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+t.options.theme.replace(/(^|\s)\s*/g," cm-s-"),fo(t)}gs.prototype.compare=function(t,e,n){return this.time+vs>t&&0==ae(e,this.pos)&&n==this.button};var js={toString:function(){return"CodeMirror.Init"}},Ms={},Ds={};function Ls(t){var e=t.optionHandlers;function n(n,o,r,i){t.defaults[n]=o,r&&(e[n]=i?function(t,e,n){n!=js&&r(t,e,n)}:r)}t.defineOption=n,t.Init=js,n("value","",(function(t,e){return t.setValue(e)}),!0),n("mode",null,(function(t,e){t.doc.modeOption=e,hi(t)}),!0),n("indentUnit",2,hi,!0),n("indentWithTabs",!1),n("smartIndent",!0),n("tabSize",4,(function(t){vi(t),fo(t),Vo(t)}),!0),n("lineSeparator",null,(function(t,e){if(t.doc.lineSep=e,e){var n=[],o=t.doc.first;t.doc.iter((function(t){for(var r=0;;){var i=t.text.indexOf(e,r);if(-1==i)break;r=i+e.length,n.push(ie(o,i))}o++}));for(var r=n.length-1;r>=0;r--)ra(t.doc,e,n[r],ie(n[r].line,n[r].ch+e.length))}})),n("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,(function(t,e,n){t.state.specialChars=new RegExp(e.source+(e.test("\t")?"":"|\t"),"g"),n!=js&&t.refresh()})),n("specialCharPlaceholder",gn,(function(t){return t.refresh()}),!0),n("electricChars",!0),n("inputStyle",y?"contenteditable":"textarea",(function(){throw new Error("inputStyle can not (yet) be changed in a running editor")}),!0),n("spellcheck",!1,(function(t,e){return t.getInputField().spellcheck=e}),!0),n("autocorrect",!1,(function(t,e){return t.getInputField().autocorrect=e}),!0),n("autocapitalize",!1,(function(t,e){return t.getInputField().autocapitalize=e}),!0),n("rtlMoveVisually",!_),n("wholeLineUpdateBefore",!0),n("theme","default",(function(t){As(t),Zr(t)}),!0),n("keyMap","default",(function(t,e,n){var o=$a(e),r=n!=js&&$a(n);r&&r.detach&&r.detach(t,o),o.attach&&o.attach(t,r||null)})),n("extraKeys",null),n("configureMouse",null),n("lineWrapping",!1,Ns,!0),n("gutters",[],(function(t,e){t.display.gutterSpecs=Jr(e,t.options.lineNumbers),Zr(t)}),!0),n("fixedGutter",!0,(function(t,e){t.display.gutters.style.left=e?Do(t.display)+"px":"0",t.refresh()}),!0),n("coverGutterNextToScrollbar",!1,(function(t){return br(t)}),!0),n("scrollbarStyle","native",(function(t){xr(t),br(t),t.display.scrollbars.setScrollTop(t.doc.scrollTop),t.display.scrollbars.setScrollLeft(t.doc.scrollLeft)}),!0),n("lineNumbers",!1,(function(t,e){t.display.gutterSpecs=Jr(t.options.gutters,e),Zr(t)}),!0),n("firstLineNumber",1,Zr,!0),n("lineNumberFormatter",(function(t){return t}),Zr,!0),n("showCursorWhenSelecting",!1,Wo,!0),n("resetSelectionOnContextMenu",!0),n("lineWiseCopyCut",!0),n("pasteLinesPerSelection",!0),n("selectionsMayTouch",!1),n("readOnly",!1,(function(t,e){"nocursor"==e&&(Qo(t),t.display.input.blur()),t.display.input.readOnlyChanged(e)})),n("screenReaderLabel",null,(function(t,e){e=''===e?null:e,t.display.input.screenReaderLabelChanged(e)})),n("disableInput",!1,(function(t,e){e||t.display.input.reset()}),!0),n("dragDrop",!0,Is),n("allowDropFileTypes",null),n("cursorBlinkRate",530),n("cursorScrollMargin",0),n("cursorHeight",1,Wo,!0),n("singleCursorHeightPerLine",!0,Wo,!0),n("workTime",100),n("workDelay",100),n("flattenSpans",!0,vi,!0),n("addModeClass",!1,vi,!0),n("pollInterval",100),n("undoDepth",200,(function(t,e){return t.doc.history.undoDepth=e})),n("historyEventDelay",1250),n("viewportMargin",10,(function(t){return t.refresh()}),!0),n("maxHighlightLength",1e4,vi,!0),n("moveInputWithCursor",!0,(function(t,e){e||t.display.input.resetPosition()})),n("tabindex",null,(function(t,e){return t.display.input.getField().tabIndex=e||""})),n("autofocus",null),n("direction","ltr",(function(t,e){return t.doc.setDirection(e)}),!0),n("phrases",null)}function Is(t,e,n){if(!e!=!(n&&n!=js)){var o=t.display.dragFunctions,r=e?ht:gt;r(t.display.scroller,"dragstart",o.start),r(t.display.scroller,"dragenter",o.enter),r(t.display.scroller,"dragover",o.over),r(t.display.scroller,"dragleave",o.leave),r(t.display.scroller,"drop",o.drop)}}function Ns(t){t.options.lineWrapping?(D(t.display.wrapper,"CodeMirror-wrap"),t.display.sizer.style.minWidth="",t.display.sizerWidth=null):(T(t.display.wrapper,"CodeMirror-wrap"),ln(t)),Io(t),Vo(t),fo(t),setTimeout((function(){return br(t)}),100)}function Rs(t,e){var n=this;if(!(this instanceof Rs))return new Rs(t,e);this.options=e=e?R(e):{},R(Ms,e,!1);var o=e.value;"string"==typeof o?o=new Ca(o,e.mode,null,e.lineSeparator,e.direction):e.mode&&(o.modeOption=e.mode),this.doc=o;var r=new Rs.inputStyles[e.inputStyle](this),i=this.display=new Qr(t,o,r,e);for(var c in i.wrapper.CodeMirror=this,As(this),e.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),xr(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new F,keySeq:null,specialChars:null},e.autofocus&&!y&&i.input.focus(),a&&s<11&&setTimeout((function(){return n.display.input.reset(!0)}),20),Vs(this),ja(),Sr(this),this.curOp.forceUpdate=!0,bi(this,o),e.autofocus&&!y||this.hasFocus()?setTimeout((function(){n.hasFocus()&&!n.state.focused&&Zo(n)}),20):Qo(this),Ds)Ds.hasOwnProperty(c)&&Ds[c](this,e[c],js);Yr(this),e.finishInit&&e.finishInit(this);for(var u=0;u20*20}ht(e.scroller,"touchstart",(function(r){if(!mt(t,r)&&!i(r)&&!Ps(t,r)){e.input.ensurePolled(),clearTimeout(n);var a=+new Date;e.activeTouch={start:a,moved:!1,prev:a-o.end<=300?o:null},1==r.touches.length&&(e.activeTouch.left=r.touches[0].pageX,e.activeTouch.top=r.touches[0].pageY)}})),ht(e.scroller,"touchmove",(function(){e.activeTouch&&(e.activeTouch.moved=!0)})),ht(e.scroller,"touchend",(function(n){var o=e.activeTouch;if(o&&!Wn(e,n)&&null!=o.left&&!o.moved&&new Date-o.start<300){var i,a=t.coordsChar(e.activeTouch,"page");i=!o.prev||l(o,o.prev)?new ai(a,a):!o.prev.prev||l(o,o.prev.prev)?t.findWordAt(a):new ai(ie(a.line,0),de(t.doc,ie(a.line+1,0))),t.setSelection(i.anchor,i.head),t.focus(),xt(n)}r()})),ht(e.scroller,"touchcancel",r),ht(e.scroller,"scroll",(function(){e.scroller.clientHeight&&(fr(t,e.scroller.scrollTop),vr(t,e.scroller.scrollLeft,!0),yt(t,"scroll",t))})),ht(e.scroller,"mousewheel",(function(e){return ri(t,e)})),ht(e.scroller,"DOMMouseScroll",(function(e){return ri(t,e)})),ht(e.wrapper,"scroll",(function(){return e.wrapper.scrollTop=e.wrapper.scrollLeft=0})),e.dragFunctions={enter:function(e){mt(t,e)||Ot(e)},over:function(e){mt(t,e)||(Pa(t,e),Ot(e))},start:function(e){return Ta(t,e)},drop:Dr(t,Oa),leave:function(e){mt(t,e)||Ea(t)}};var c=e.input.getField();ht(c,"keyup",(function(e){return ps.call(t,e)})),ht(c,"keydown",Dr(t,cs)),ht(c,"keypress",Dr(t,ds)),ht(c,"focus",(function(e){return Zo(t,e)})),ht(c,"blur",(function(e){return Qo(t,e)}))}Rs.defaults=Ms,Rs.optionHandlers=Ds;var Fs=[];function Hs(t,e,n,o){var r,i=t.doc;null==n&&(n="add"),"smart"==n&&(i.mode.indent?r=be(t,e).state:n="prev");var a=t.options.tabSize,s=Xt(i,e),l=V(s.text,null,a);s.stateAfter&&(s.stateAfter=null);var c,u=s.text.match(/^\s*/)[0];if(o||/\S/.test(s.text)){if("smart"==n&&((c=i.mode.indent(r,s.text.slice(u.length),s.text))==z||c>150)){if(!o)return;n="prev"}}else c=0,n="not";"prev"==n?c=e>i.first?V(Xt(i,e-1).text,null,a):0:"add"==n?c=l+t.options.indentUnit:"subtract"==n?c=l-t.options.indentUnit:"number"==typeof n&&(c=l+n),c=Math.max(0,c);var p="",d=0;if(t.options.indentWithTabs)for(var f=Math.floor(c/a);f;--f)d+=a,p+="\t";if(da,l=Lt(e),c=null;if(s&&o.ranges.length>1)if(Us&&Us.text.join("\n")==e){if(o.ranges.length%Us.text.length==0){c=[];for(var u=0;u=0;d--){var f=o.ranges[d],h=f.from(),v=f.to();f.empty()&&(n&&n>0?h=ie(h.line,h.ch-n):t.state.overwrite&&!s?v=ie(v.line,Math.min(Xt(i,v.line).text.length,v.ch+Y(l).length)):s&&Us&&Us.lineWise&&Us.text.join("\n")==l.join("\n")&&(h=v=ie(h.line,0)));var g={from:h,to:v,text:c?c[d%c.length]:l,origin:r||(s?"paste":t.state.cutIncoming>a?"cut":"+input")};Zi(t.doc,g),kn(t,"inputRead",t,g)}e&&!s&&$s(t,e),lr(t),t.curOp.updateInput<2&&(t.curOp.updateInput=p),t.curOp.typing=!0,t.state.pasteIncoming=t.state.cutIncoming=-1}function Ws(t,e){var n=t.clipboardData&&t.clipboardData.getData("Text");if(n)return t.preventDefault(),e.isReadOnly()||e.options.disableInput||Mr(e,(function(){return Bs(e,n,0,null,"paste")})),!0}function $s(t,e){if(t.options.electricChars&&t.options.smartIndent)for(var n=t.doc.sel,o=n.ranges.length-1;o>=0;o--){var r=n.ranges[o];if(!(r.head.ch>100||o&&n.ranges[o-1].head.line==r.head.line)){var i=t.getModeAt(r.head),a=!1;if(i.electricChars){for(var s=0;s-1){a=Hs(t,r.head.line,"smart");break}}else i.electricInput&&i.electricInput.test(Xt(t.doc,r.head.line).text.slice(0,r.head.ch))&&(a=Hs(t,r.head.line,"smart"));a&&kn(t,"electricInput",t,r.head.line)}}}function qs(t){for(var e=[],n=[],o=0;on&&(Hs(this,r.head.line,t,!0),n=r.head.line,o==this.doc.sel.primIndex&&lr(this));else{var i=r.from(),a=r.to(),s=Math.max(n,i.line);n=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var l=s;l0&&Vi(this.doc,o,new ai(i,c[o].to()),B)}}})),getTokenAt:function(t,e){return Se(this,t,e)},getLineTokens:function(t,e){return Se(this,ie(t),e,!0)},getTokenTypeAt:function(t){t=de(this.doc,t);var e,n=me(this,Xt(this.doc,t.line)),o=0,r=(n.length-1)/2,i=t.ch;if(0==i)e=n[2];else for(;;){var a=o+r>>1;if((a?n[2*a-1]:0)>=i)r=a;else{if(!(n[2*a+1]i&&(t=i,r=!0),o=Xt(this.doc,t)}else o=t;return yo(this,o,{top:0,left:0},e||"page",n||r).top+(r?this.doc.height-an(o):0)},defaultTextHeight:function(){return Ao(this.display)},defaultCharWidth:function(){return jo(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(t,e,n,o,r){var i=this.display,a=(t=_o(this,de(this.doc,t))).bottom,s=t.left;if(e.style.position="absolute",e.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(e),i.sizer.appendChild(e),"over"==o)a=t.top;else if("above"==o||"near"==o){var l=Math.max(i.wrapper.clientHeight,this.doc.height),c=Math.max(i.sizer.clientWidth,i.lineSpace.clientWidth);('above'==o||t.bottom+e.offsetHeight>l)&&t.top>e.offsetHeight?a=t.top-e.offsetHeight:t.bottom+e.offsetHeight<=l&&(a=t.bottom),s+e.offsetWidth>c&&(s=c-e.offsetWidth)}e.style.top=a+"px",e.style.left=e.style.right="","right"==r?(s=i.sizer.clientWidth-e.offsetWidth,e.style.right="0px"):("left"==r?s=0:"middle"==r&&(s=(i.sizer.clientWidth-e.offsetWidth)/2),e.style.left=s+"px"),n&&ir(this,{left:s,top:a,right:s+e.offsetWidth,bottom:a+e.offsetHeight})},triggerOnKeyDown:Lr(cs),triggerOnKeyPress:Lr(ds),triggerOnKeyUp:ps,triggerOnMouseDown:Lr(ms),execCommand:function(t){if(Xa.hasOwnProperty(t))return Xa[t].call(null,this)},triggerElectric:Lr((function(t){$s(this,t)})),findPosH:function(t,e,n,o){var r=1;e<0&&(r=-1,e=-e);for(var i=de(this.doc,t),a=0;a0&&a(e.charAt(n-1));)--n;for(;o.5||this.options.lineWrapping)&&Io(this),yt(this,"refresh",this)})),swapDoc:Lr((function(t){var e=this.doc;return e.cm=null,this.state.selectingText&&this.state.selectingText(),bi(this,t),fo(this),this.display.input.reset(),cr(this,t.scrollLeft,t.scrollTop),this.curOp.forceScroll=!0,kn(this,"swapDoc",this,e),e})),phrase:function(t){var e=this.options.phrases;return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:t},getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},wt(t),t.registerHelper=function(e,o,r){n.hasOwnProperty(e)||(n[e]=t[e]={_global:[]}),n[e][o]=r},t.registerGlobalHelper=function(e,o,r,i){t.registerHelper(e,o,i),n[e]._global.push({pred:r,val:i})}}function Js(t,e,n,o,r){var i=e,a=n,s=Xt(t,e.line),l=r&&"rtl"==t.direction?-n:n;function c(){var n=e.line+l;return!(n=t.first+t.size)&&(e=new ie(n,e.ch,e.sticky),s=Xt(t,n))}function u(i){var a;if("codepoint"==o){var u=s.text.charCodeAt(e.ch+(n>0?0:-1));if(isNaN(u))a=null;else{var p=n>0?u>=55296&&u<56320:u>=56320&&u<57343;a=new ie(e.line,Math.max(0,Math.min(s.text.length,e.ch+n*(p?2:1))),-n)}}else a=r?Ja(t.cm,s,e,n):Ka(s,e,n);if(null==a){if(i||!c())return!1;e=Ya(r,t.cm,s,e.line,l)}else e=a;return!0}if("char"==o||"codepoint"==o)u();else if("column"==o)u(!0);else if("word"==o||"group"==o)for(var p=null,d="group"==o,f=t.cm&&t.cm.getHelper(e,"wordChars"),h=!0;!(n<0)||u(!h);h=!1){var v=s.text.charAt(e.ch)||"\n",g=nt(v,f)?"w":d&&"\n"==v?"n":!d||/\s/.test(v)?null:"p";if(!d||h||g||(g="s"),p&&p!=g){n<0&&(n=1,u(),e.sticky="after");break}if(g&&(p=g),n>0&&!u(!h))break}var y=Ki(t,e,i,a,!0);return se(i,y)&&(y.hitSide=!0),y}function Xs(t,e,n,o){var r,i,a=t.doc,s=e.left;if("page"==o){var l=Math.min(t.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),c=Math.max(l-.5*Ao(t.display),3);r=(n>0?e.bottom:e.top)+n*c}else"line"==o&&(r=n>0?e.bottom+3:e.top-3);for(;(i=Co(t,s,r)).outside;){if(n<0?r<=0:r>=a.height){i.hitSide=!0;break}r+=5*n}return i}var Zs=function(t){this.cm=t,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new F,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null};function Qs(t,e){var n=eo(t,e.line);if(!n||n.hidden)return null;var o=Xt(t.doc,e.line),r=Zn(n,o,e.line),i=dt(o,t.doc.direction),a="left";i&&(a=ut(i,e.ch)%2?"right":"left");var s=ao(r.map,e.ch,a);return s.offset="right"==s.collapse?s.end:s.start,s}function tl(t){for(var e=t;e;e=e.parentNode)if(/CodeMirror-gutter-wrapper/.test(e.className))return!0;return!1}function el(t,e){return e&&(t.bad=!0),t}function nl(t,e,n,o,r){var i="",a=!1,s=t.doc.lineSeparator(),l=!1;function c(t){return function(e){return e.id==t}}function u(){a&&(i+=s,l&&(i+=s),a=l=!1)}function p(t){t&&(u(),i+=t)}function d(e){if(1==e.nodeType){var n=e.getAttribute("cm-text");if(n)return void p(n);var i,f=e.getAttribute("cm-marker");if(f){var h=t.findMarks(ie(o,0),ie(r+1,0),c(+f));return void(h.length&&(i=h[0].find(0))&&p(Zt(t.doc,i.from,i.to).join(s)))}if("false"==e.getAttribute("contenteditable"))return;var v=/^(pre|div|p|li|table|br)$/i.test(e.nodeName);if(!/^br$/i.test(e.nodeName)&&0==e.textContent.length)return;v&&u();for(var g=0;g=e.display.viewTo||i.line=e.display.viewFrom&&Qs(e,r)||{node:l[0].measure.map[2],offset:0},u=i.lineo.firstLine()&&(a=ie(a.line-1,Xt(o.doc,a.line-1).length)),s.ch==Xt(o.doc,s.line).text.length&&s.liner.viewTo-1)return!1;a.line==r.viewFrom||0==(t=Ro(o,a.line))?(e=ee(r.view[0].line),n=r.view[0].node):(e=ee(r.view[t].line),n=r.view[t-1].node.nextSibling);var l,c,u=Ro(o,s.line);if(u==r.view.length-1?(l=r.viewTo-1,c=r.lineDiv.lastChild):(l=ee(r.view[u+1].line)-1,c=r.view[u+1].node.previousSibling),!n)return!1;for(var p=o.doc.splitLines(nl(o,n,c,e,l)),d=Zt(o.doc,ie(e,0),ie(l,Xt(o.doc,l).text.length));p.length>1&&d.length>1;)if(Y(p)==Y(d))p.pop(),d.pop(),l--;else{if(p[0]!=d[0])break;p.shift(),d.shift(),e++}for(var f=0,h=0,v=p[0],g=d[0],y=Math.min(v.length,g.length);fa.ch&&m.charCodeAt(m.length-h-1)==b.charCodeAt(b.length-h-1);)f--,h++;p[p.length-1]=m.slice(0,m.length-h).replace(/^\u200b+/,""),p[0]=p[0].slice(f).replace(/\u200b+$/,"");var w=ie(e,f),x=ie(l,d.length?Y(d).length-h:0);return p.length>1||p[0]||ae(w,x)?(ra(o.doc,p,w,x,"+input"),!0):void 0},Zs.prototype.ensurePolled=function(){this.forceCompositionEnd()},Zs.prototype.reset=function(){this.forceCompositionEnd()},Zs.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())},Zs.prototype.readFromDOMSoon=function(){var t=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout((function(){if(t.readDOMTimeout=null,t.composing){if(!t.composing.done)return;t.composing=null}t.updateFromDOM()}),80))},Zs.prototype.updateFromDOM=function(){var t=this;!this.cm.isReadOnly()&&this.pollContent()||Mr(this.cm,(function(){return Vo(t.cm)}))},Zs.prototype.setUneditable=function(t){t.contentEditable="false"},Zs.prototype.onKeyPress=function(t){0==t.charCode||this.composing||(t.preventDefault(),this.cm.isReadOnly()||Dr(this.cm,Bs)(this.cm,String.fromCharCode(null==t.charCode?t.keyCode:t.charCode),0))},Zs.prototype.readOnlyChanged=function(t){this.div.contentEditable=String("nocursor"!=t)},Zs.prototype.onContextMenu=function(){},Zs.prototype.resetPosition=function(){},Zs.prototype.needsContentAttribute=!0;var il=function(t){this.cm=t,this.prevInput="",this.pollingFast=!1,this.polling=new F,this.hasSelection=!1,this.composing=null};function al(t,e){if((e=e?R(e):{}).value=t.value,!e.tabindex&&t.tabIndex&&(e.tabindex=t.tabIndex),!e.placeholder&&t.placeholder&&(e.placeholder=t.placeholder),null==e.autofocus){var n=M();e.autofocus=n==t||null!=t.getAttribute("autofocus")&&n==document.body}function o(){t.value=s.getValue()}var r;if(t.form&&(ht(t.form,"submit",o),!e.leaveSubmitMethodAlone)){var i=t.form;r=i.submit;try{var a=i.submit=function(){o(),i.submit=r,i.submit(),i.submit=a}}catch(t){}}e.finishInit=function(n){n.save=o,n.getTextArea=function(){return t},n.toTextArea=function(){n.toTextArea=isNaN,o(),t.parentNode.removeChild(n.getWrapperElement()),t.style.display="",t.form&&(gt(t.form,"submit",o),e.leaveSubmitMethodAlone||"function"!=typeof t.form.submit||(t.form.submit=r))}},t.style.display="none";var s=Rs((function(e){return t.parentNode.insertBefore(e,t.nextSibling)}),e);return s}function sl(t){t.off=gt,t.on=ht,t.wheelEventPixels=oi,t.Doc=Ca,t.splitLines=Lt,t.countColumn=V,t.findColumn=q,t.isWordChar=et,t.Pass=z,t.signal=yt,t.Line=cn,t.changeEnd=ci,t.scrollbarModel=wr,t.Pos=ie,t.cmpPos=ae,t.modes=Ft,t.mimeModes=Ht,t.resolveMode=Bt,t.getMode=Wt,t.modeExtensions=$t,t.extendMode=qt,t.copyState=Gt,t.startState=Yt,t.innerMode=Kt,t.commands=Xa,t.keyMap=Va,t.keyName=Wa,t.isModifierKey=za,t.lookupKey=Ua,t.normalizeKeyMap=Ha,t.StringStream=Jt,t.SharedTextMarker=ya,t.TextMarker=va,t.LineWidget=pa,t.e_preventDefault=xt,t.e_stopPropagation=Ct,t.e_stop=Ot,t.addClass=D,t.contains=j,t.rmClass=T,t.keyNames=La}il.prototype.init=function(t){var e=this,n=this,o=this.cm;this.createField(t);var r=this.textarea;function i(t){if(!mt(o,t)){if(o.somethingSelected())zs({lineWise:!1,text:o.getSelections()});else{if(!o.options.lineWiseCopyCut)return;var e=qs(o);zs({lineWise:!0,text:e.text}),"cut"==t.type?o.setSelections(e.ranges,null,B):(n.prevInput="",r.value=e.text.join("\n"),I(r))}"cut"==t.type&&(o.state.cutIncoming=+new Date)}}t.wrapper.insertBefore(this.wrapper,t.wrapper.firstChild),v&&(r.style.width="0px"),ht(r,"input",(function(){a&&s>=9&&e.hasSelection&&(e.hasSelection=null),n.poll()})),ht(r,"paste",(function(t){mt(o,t)||Ws(t,o)||(o.state.pasteIncoming=+new Date,n.fastPoll())})),ht(r,"cut",i),ht(r,"copy",i),ht(t.scroller,"paste",(function(e){if(!Wn(t,e)&&!mt(o,e)){if(!r.dispatchEvent)return o.state.pasteIncoming=+new Date,void n.focus();var i=new Event("paste");i.clipboardData=e.clipboardData,r.dispatchEvent(i)}})),ht(t.lineSpace,"selectstart",(function(e){Wn(t,e)||xt(e)})),ht(r,"compositionstart",(function(){var t=o.getCursor("from");n.composing&&n.composing.range.clear(),n.composing={start:t,range:o.markText(t,o.getCursor("to"),{className:"CodeMirror-composing"})}})),ht(r,"compositionend",(function(){n.composing&&(n.poll(),n.composing.range.clear(),n.composing=null)}))},il.prototype.createField=function(t){this.wrapper=Ks(),this.textarea=this.wrapper.firstChild},il.prototype.screenReaderLabelChanged=function(t){t?this.textarea.setAttribute('aria-label',t):this.textarea.removeAttribute('aria-label')},il.prototype.prepareSelection=function(){var t=this.cm,e=t.display,n=t.doc,o=$o(t);if(t.options.moveInputWithCursor){var r=_o(t,n.sel.primary().head,"div"),i=e.wrapper.getBoundingClientRect(),a=e.lineDiv.getBoundingClientRect();o.teTop=Math.max(0,Math.min(e.wrapper.clientHeight-10,r.top+a.top-i.top)),o.teLeft=Math.max(0,Math.min(e.wrapper.clientWidth-10,r.left+a.left-i.left))}return o},il.prototype.showSelection=function(t){var e=this.cm.display;E(e.cursorDiv,t.cursors),E(e.selectionDiv,t.selection),null!=t.teTop&&(this.wrapper.style.top=t.teTop+"px",this.wrapper.style.left=t.teLeft+"px")},il.prototype.reset=function(t){if(!this.contextMenuPending&&!this.composing){var e=this.cm;if(e.somethingSelected()){this.prevInput="";var n=e.getSelection();this.textarea.value=n,e.state.focused&&I(this.textarea),a&&s>=9&&(this.hasSelection=n)}else t||(this.prevInput=this.textarea.value="",a&&s>=9&&(this.hasSelection=null))}},il.prototype.getField=function(){return this.textarea},il.prototype.supportsTouch=function(){return!1},il.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!y||M()!=this.textarea))try{this.textarea.focus()}catch(t){}},il.prototype.blur=function(){this.textarea.blur()},il.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0},il.prototype.receivedFocus=function(){this.slowPoll()},il.prototype.slowPoll=function(){var t=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,(function(){t.poll(),t.cm.state.focused&&t.slowPoll()}))},il.prototype.fastPoll=function(){var t=!1,e=this;function n(){e.poll()||t?(e.pollingFast=!1,e.slowPoll()):(t=!0,e.polling.set(60,n))}e.pollingFast=!0,e.polling.set(20,n)},il.prototype.poll=function(){var t=this,e=this.cm,n=this.textarea,o=this.prevInput;if(this.contextMenuPending||!e.state.focused||It(n)&&!o&&!this.composing||e.isReadOnly()||e.options.disableInput||e.state.keySeq)return!1;var r=n.value;if(r==o&&!e.somethingSelected())return!1;if(a&&s>=9&&this.hasSelection===r||m&&/[\uf700-\uf7ff]/.test(r))return e.display.input.reset(),!1;if(e.doc.sel==e.display.selForContextMenu){var i=r.charCodeAt(0);if(8203!=i||o||(o="​"),8666==i)return this.reset(),this.cm.execCommand("undo")}for(var l=0,c=Math.min(o.length,r.length);l1e3||r.indexOf("\n")>-1?n.value=t.prevInput="":t.prevInput=r,t.composing&&(t.composing.range.clear(),t.composing.range=e.markText(t.composing.start,e.getCursor("to"),{className:"CodeMirror-composing"}))})),!0},il.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},il.prototype.onKeyPress=function(){a&&s>=9&&(this.hasSelection=null),this.fastPoll()},il.prototype.onContextMenu=function(t){var e=this,n=e.cm,o=n.display,r=e.textarea;e.contextMenuPending&&e.contextMenuPending();var i=No(n,t),c=o.scroller.scrollTop;if(i&&!p){n.options.resetSelectionOnContextMenu&&-1==n.doc.sel.contains(i)&&Dr(n,zi)(n.doc,li(i),B);var u,d=r.style.cssText,f=e.wrapper.style.cssText,h=e.wrapper.offsetParent.getBoundingClientRect();if(e.wrapper.style.cssText="position: static",r.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(t.clientY-h.top-5)+"px; left: "+(t.clientX-h.left-5)+"px;\n z-index: 1000; background: "+(a?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",l&&(u=window.scrollY),o.input.focus(),l&&window.scrollTo(null,u),o.input.reset(),n.somethingSelected()||(r.value=e.prevInput=" "),e.contextMenuPending=y,o.selForContextMenu=n.doc.sel,clearTimeout(o.detectingSelectAll),a&&s>=9&&g(),C){Ot(t);var v=function(){gt(window,"mouseup",v),setTimeout(y,20)};ht(window,"mouseup",v)}else setTimeout(y,50)}function g(){if(null!=r.selectionStart){var t=n.somethingSelected(),i="​"+(t?r.value:"");r.value="⇚",r.value=i,e.prevInput=t?"":"​",r.selectionStart=1,r.selectionEnd=i.length,o.selForContextMenu=n.doc.sel}}function y(){if(e.contextMenuPending==y&&(e.contextMenuPending=!1,e.wrapper.style.cssText=f,r.style.cssText=d,a&&s<9&&o.scrollbars.setScrollTop(o.scroller.scrollTop=c),null!=r.selectionStart)){(!a||a&&s<9)&&g();var t=0,i=function(){o.selForContextMenu==n.doc.sel&&0==r.selectionStart&&r.selectionEnd>0&&"​"==e.prevInput?Dr(n,Ji)(n):t++<10?o.detectingSelectAll=setTimeout(i,500):(o.selForContextMenu=null,o.input.reset())};o.detectingSelectAll=setTimeout(i,200)}}},il.prototype.readOnlyChanged=function(t){t||this.reset(),this.textarea.disabled="nocursor"==t,this.textarea.readOnly=!!t},il.prototype.setUneditable=function(){},il.prototype.needsContentAttribute=!1,Ls(Rs),Ys(Rs);var ll="iter insert remove copy getEditor constructor".split(" ");for(var cl in Ca.prototype)Ca.prototype.hasOwnProperty(cl)&&H(ll,cl)<0&&(Rs.prototype[cl]=function(t){return function(){return t.apply(this.doc,arguments)}}(Ca.prototype[cl]));return wt(Ca),Rs.inputStyles={textarea:il,contenteditable:Zs},Rs.defineMode=function(t){Rs.defaults.mode||"null"==t||(Rs.defaults.mode=t),Ut.apply(this,arguments)},Rs.defineMIME=zt,Rs.defineMode("null",(function(){return{token:function(t){return t.skipToEnd()}}})),Rs.defineMIME("text/plain","null"),Rs.defineExtension=function(t,e){Rs.prototype[t]=e},Rs.defineDocExtension=function(t,e){Ca.prototype[t]=e},Rs.fromTextArea=al,sl(Rs),Rs.version="5.63.0",Rs}())},7389:(t,e,n)=>{1&&function(t){"use strict";function e(t){for(var e={},n=0;n*\/]/.test(n)?x(null,"select-op"):"."==n&&t.match(/^-?[_a-z][_a-z0-9-]*/i)?x("qualifier","qualifier"):/[:;{}\[\]\(\)]/.test(n)?x(null,n):t.match(/^[\w-.]+(?=\()/)?(/^(url(-prefix)?|domain|regexp)$/i.test(t.current())&&(e.tokenize=O),x("variable callee","variable")):/[\w\\\-]/.test(n)?(t.eatWhile(/[\w\\\-]/),x("property","word")):x(null,null):/[\d.]/.test(t.peek())?(t.eatWhile(/[\w.%]/),x("number","unit")):t.match(/^-[\w\\\-]*/)?(t.eatWhile(/[\w\\\-]/),t.match(/^\s*:/,!1)?x("variable-2","variable-definition"):x("variable-2","variable")):t.match(/^\w+-/)?x("meta","meta"):void 0}function S(t){return function(e,n){for(var o,r=!1;null!=(o=e.next());){if(o==t&&!r){")"==t&&e.backUp(1);break}r=!r&&"\\"==o}return(o==t||!r&&")"!=t)&&(n.tokenize=null),x("string","string")}}function O(t,e){return t.next(),t.match(/^\s*[\"\')]/,!1)?e.tokenize=null:e.tokenize=S(")"),x(null,"(")}function T(t,e,n){this.type=t,this.indent=e,this.prev=n}function P(t,e,n,o){return t.context=new T(n,e.indentation()+(!1===o?0:a),t.context),n}function E(t){return t.context.prev&&(t.context=t.context.prev),t.context.type}function k(t,e,n){return M[n.context.type](t,e,n)}function A(t,e,n,o){for(var r=o||1;r>0;r--)n.context=n.context.prev;return k(t,e,n)}function j(t){var e=t.current().toLowerCase();i=y.hasOwnProperty(e)?"atom":g.hasOwnProperty(e)?"keyword":"variable"}var M={top:function(t,e,n){if("{"==t)return P(n,e,"block");if("}"==t&&n.context.prev)return E(n);if(_&&/@component/i.test(t))return P(n,e,"atComponentBlock");if(/^@(-moz-)?document$/i.test(t))return P(n,e,"documentTypes");if(/^@(media|supports|(-moz-)?document|import)$/i.test(t))return P(n,e,"atBlock");if(/^@(font-face|counter-style)/i.test(t))return n.stateArg=t,"restricted_atBlock_before";if(/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(t))return"keyframes";if(t&&"@"==t.charAt(0))return P(n,e,"at");if("hash"==t)i="builtin";else if("word"==t)i="tag";else{if("variable-definition"==t)return"maybeprop";if("interpolation"==t)return P(n,e,"interpolation");if(":"==t)return"pseudo";if(m&&"("==t)return P(n,e,"parens")}return n.context.type},block:function(t,e,n){if("word"==t){var o=e.current().toLowerCase();return d.hasOwnProperty(o)?(i="property","maybeprop"):f.hasOwnProperty(o)?(i=w?"string-2":"property","maybeprop"):m?(i=e.match(/^\s*:(?:\s|$)/,!1)?"property":"tag","block"):(i+=" error","maybeprop")}return"meta"==t?"block":m||"hash"!=t&&"qualifier"!=t?M.top(t,e,n):(i="error","block")},maybeprop:function(t,e,n){return":"==t?P(n,e,"prop"):k(t,e,n)},prop:function(t,e,n){if(";"==t)return E(n);if("{"==t&&m)return P(n,e,"propBlock");if("}"==t||"{"==t)return A(t,e,n);if("("==t)return P(n,e,"parens");if("hash"!=t||/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(e.current())){if("word"==t)j(e);else if("interpolation"==t)return P(n,e,"interpolation")}else i+=" error";return"prop"},propBlock:function(t,e,n){return"}"==t?E(n):"word"==t?(i="property","maybeprop"):n.context.type},parens:function(t,e,n){return"{"==t||"}"==t?A(t,e,n):")"==t?E(n):"("==t?P(n,e,"parens"):"interpolation"==t?P(n,e,"interpolation"):("word"==t&&j(e),"parens")},pseudo:function(t,e,n){return"meta"==t?"pseudo":"word"==t?(i="variable-3",n.context.type):k(t,e,n)},documentTypes:function(t,e,n){return"word"==t&&l.hasOwnProperty(e.current())?(i="tag",n.context.type):M.atBlock(t,e,n)},atBlock:function(t,e,n){if("("==t)return P(n,e,"atBlock_parens");if("}"==t||";"==t)return A(t,e,n);if("{"==t)return E(n)&&P(n,e,m?"block":"top");if("interpolation"==t)return P(n,e,"interpolation");if("word"==t){var o=e.current().toLowerCase();i="only"==o||"not"==o||"and"==o||"or"==o?"keyword":c.hasOwnProperty(o)?"attribute":u.hasOwnProperty(o)?"property":p.hasOwnProperty(o)?"keyword":d.hasOwnProperty(o)?"property":f.hasOwnProperty(o)?w?"string-2":"property":y.hasOwnProperty(o)?"atom":g.hasOwnProperty(o)?"keyword":"error"}return n.context.type},atComponentBlock:function(t,e,n){return"}"==t?A(t,e,n):"{"==t?E(n)&&P(n,e,m?"block":"top",!1):("word"==t&&(i="error"),n.context.type)},atBlock_parens:function(t,e,n){return")"==t?E(n):"{"==t||"}"==t?A(t,e,n,2):M.atBlock(t,e,n)},restricted_atBlock_before:function(t,e,n){return"{"==t?P(n,e,"restricted_atBlock"):"word"==t&&"@counter-style"==n.stateArg?(i="variable","restricted_atBlock_before"):k(t,e,n)},restricted_atBlock:function(t,e,n){return"}"==t?(n.stateArg=null,E(n)):"word"==t?(i="@font-face"==n.stateArg&&!h.hasOwnProperty(e.current().toLowerCase())||"@counter-style"==n.stateArg&&!v.hasOwnProperty(e.current().toLowerCase())?"error":"property","maybeprop"):"restricted_atBlock"},keyframes:function(t,e,n){return"word"==t?(i="variable","keyframes"):"{"==t?P(n,e,"top"):k(t,e,n)},at:function(t,e,n){return";"==t?E(n):"{"==t||"}"==t?A(t,e,n):("word"==t?i="tag":"hash"==t&&(i="builtin"),"at")},interpolation:function(t,e,n){return"}"==t?E(n):"{"==t||";"==t?A(t,e,n):("word"==t?i="variable":"variable"!=t&&"("!=t&&")"!=t&&(i="error"),"interpolation")}};return{startState:function(t){return{tokenize:null,state:o?"block":"top",stateArg:null,context:new T(o?"block":"top",t||0,null)}},token:function(t,e){if(!e.tokenize&&t.eatSpace())return null;var n=(e.tokenize||C)(t,e);return n&&"object"==typeof n&&(r=n[1],n=n[0]),i=n,"comment"!=r&&(e.state=M[e.state](r,t,e)),i},indent:function(t,e){var n=t.context,o=e&&e.charAt(0),r=n.indent;return"prop"!=n.type||"}"!=o&&")"!=o||(n=n.prev),n.prev&&("}"!=o||"block"!=n.type&&"top"!=n.type&&"interpolation"!=n.type&&"restricted_atBlock"!=n.type?(")"!=o||"parens"!=n.type&&"atBlock_parens"!=n.type)&&("{"!=o||"at"!=n.type&&"atBlock"!=n.type)||(r=Math.max(0,n.indent-a)):r=(n=n.prev).indent),r},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",blockCommentContinue:" * ",lineComment:b,fold:"brace"}}));var n=["domain","regexp","url","url-prefix"],o=e(n),r=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],i=e(r),a=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","orientation","device-pixel-ratio","min-device-pixel-ratio","max-device-pixel-ratio","pointer","any-pointer","hover","any-hover","prefers-color-scheme"],s=e(a),l=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive","dark","light"],c=e(l),u=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","all","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","binding","bleed","block-size","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-content","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","gap","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-gap","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-gap","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","inset","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","left","letter-spacing","line-break","line-height","line-height-step","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","place-content","place-items","place-self","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotate","rotation","rotation-point","row-gap","ruby-align","ruby-overhang","ruby-position","ruby-span","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-type","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-orientation","text-outline","text-overflow","text-rendering","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","touch-action","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-select","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","paint-order","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode"],p=e(u),d=["accent-color","aspect-ratio","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","content-visibility","margin-block","margin-block-end","margin-block-start","margin-inline","margin-inline-end","margin-inline-start","overflow-anchor","overscroll-behavior","padding-block","padding-block-end","padding-block-start","padding-inline","padding-inline-end","padding-inline-start","scroll-snap-stop","scrollbar-3d-light-color","scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-track-color","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","shape-inside","zoom"],f=e(d),h=e(["font-display","font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"]),v=e(["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"]),g=["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],y=e(g),m=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","axis-pan","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","blur","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","brightness","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","contrast","copy","counter","counters","cover","crop","cross","crosshair","cubic-bezier","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","devanagari","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","drop-shadow","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fill-box","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","georgian","grayscale","graytext","grid","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hard-light","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","hue","hue-rotate","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","luminosity","malayalam","manipulation","match","matrix","matrix3d","media-controls-background","media-current-time-display","media-fullscreen-button","media-mute-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-volume-slider","media-volume-slider-container","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menulist-text","menulist-textfield","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","multiple_mask_images","multiply","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","opacity","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","pinch-zoom","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturate","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","self-start","self-end","semi-condensed","semi-expanded","separate","sepia","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","somali","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","square-button","start","static","status-bar","stretch","stroke","stroke-box","sub","subpixel-antialiased","svg_masks","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unidirectional-pan","unset","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","view-box","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"],b=e(m),_=n.concat(r).concat(a).concat(l).concat(u).concat(d).concat(g).concat(m);function w(t,e){for(var n,o=!1;null!=(n=t.next());){if(o&&"/"==n){e.tokenize=null;break}o="*"==n}return["comment","comment"]}t.registerHelper("hintWords","css",_),t.defineMIME("text/css",{documentTypes:o,mediaTypes:i,mediaFeatures:s,mediaValueKeywords:c,propertyKeywords:p,nonStandardPropertyKeywords:f,fontProperties:h,counterDescriptors:v,colorKeywords:y,valueKeywords:b,tokenHooks:{"/":function(t,e){return!!t.eat("*")&&(e.tokenize=w,w(t,e))}},name:"css"}),t.defineMIME("text/x-scss",{mediaTypes:i,mediaFeatures:s,mediaValueKeywords:c,propertyKeywords:p,nonStandardPropertyKeywords:f,colorKeywords:y,valueKeywords:b,fontProperties:h,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(t,e){return t.eat("/")?(t.skipToEnd(),["comment","comment"]):t.eat("*")?(e.tokenize=w,w(t,e)):["operator","operator"]},":":function(t){return!!t.match(/^\s*\{/,!1)&&[null,null]},$:function(t){return t.match(/^[\w-]+/),t.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"#":function(t){return!!t.eat("{")&&[null,"interpolation"]}},name:"css",helperType:"scss"}),t.defineMIME("text/x-less",{mediaTypes:i,mediaFeatures:s,mediaValueKeywords:c,propertyKeywords:p,nonStandardPropertyKeywords:f,colorKeywords:y,valueKeywords:b,fontProperties:h,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(t,e){return t.eat("/")?(t.skipToEnd(),["comment","comment"]):t.eat("*")?(e.tokenize=w,w(t,e)):["operator","operator"]},"@":function(t){return t.eat("{")?[null,"interpolation"]:!t.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i,!1)&&(t.eatWhile(/[\w\\\-]/),t.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"])},"&":function(){return["atom","atom"]}},name:"css",helperType:"less"}),t.defineMIME("text/x-gss",{documentTypes:o,mediaTypes:i,mediaFeatures:s,propertyKeywords:p,nonStandardPropertyKeywords:f,fontProperties:h,counterDescriptors:v,colorKeywords:y,valueKeywords:b,supportsAtComponent:!0,tokenHooks:{"/":function(t,e){return!!t.eat("*")&&(e.tokenize=w,w(t,e))}},name:"css",helperType:"gss"})}(n(4408))},8253:(t,e,n)=>{1&&function(t){"use strict";var e={script:[["lang",/(javascript|babel)/i,"javascript"],["type",/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i,"javascript"],["type",/./,"text/plain"],[null,null,"javascript"]],style:[["lang",/^css$/i,"css"],["type",/^(text\/)?(x-)?(stylesheet|css)$/i,"css"],["type",/./,"text/plain"],[null,null,"css"]]};function n(t,e,n){var o=t.current(),r=o.search(e);return r>-1?t.backUp(o.length-r):o.match(/<\/?$/)&&(t.backUp(o.length),t.match(e,!1)||t.match(o)),n}var o={};function r(t){var e=o[t];return e||(o[t]=new RegExp("\\s+"+t+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*"))}function i(t,e){var n=t.match(r(e));return n?/^\s*(.*?)\s*$/.exec(n[2])[1]:""}function a(t,e){return new RegExp((e?"^":"")+"","i")}function s(t,e){for(var n in t)for(var o=e[n]||(e[n]=[]),r=t[n],i=r.length-1;i>=0;i--)o.unshift(r[i])}function l(t,e){for(var n=0;n=0;d--)c.script.unshift(["type",p[d].matches,p[d].mode]);function f(e,r){var s,u=i.token(e,r.htmlState),p=/\btag\b/.test(u);if(p&&!/[<>\s\/]/.test(e.current())&&(s=r.htmlState.tagName&&r.htmlState.tagName.toLowerCase())&&c.hasOwnProperty(s))r.inTag=s+" ";else if(r.inTag&&p&&/>$/.test(e.current())){var d=/^([\S]+) (.*)/.exec(r.inTag);r.inTag=null;var h=">"==e.current()&&l(c[d[1]],d[2]),v=t.getMode(o,h),g=a(d[1],!0),y=a(d[1],!1);r.token=function(t,e){return t.match(g,!1)?(e.token=f,e.localState=e.localMode=null,null):n(t,y,e.localMode.token(t,e.localState))},r.localMode=v,r.localState=t.startState(v,i.indent(r.htmlState,"",""))}else r.inTag&&(r.inTag+=e.current(),e.eol()&&(r.inTag+=" "));return u}return{startState:function(){return{token:f,inTag:null,localMode:null,localState:null,htmlState:t.startState(i)}},copyState:function(e){var n;return e.localState&&(n=t.copyState(e.localMode,e.localState)),{token:e.token,inTag:e.inTag,localMode:e.localMode,localState:n,htmlState:t.copyState(i,e.htmlState)}},token:function(t,e){return e.token(t,e)},indent:function(e,n,o){return!e.localMode||/^\s*<\//.test(n)?i.indent(e.htmlState,n,o):e.localMode.indent?e.localMode.indent(e.localState,n,o):t.Pass},innerMode:function(t){return{state:t.localState||t.htmlState,mode:t.localMode||i}}}}),"xml","javascript","css"),t.defineMIME("text/html","htmlmixed")}(n(4408),n(9701),n(6061),n(7389))},6061:(t,e,n)=>{1&&function(t){"use strict";t.defineMode("javascript",(function(e,n){var o,r,i=e.indentUnit,a=n.statementIndent,s=n.jsonld,l=n.json||s,c=!1!==n.trackScope,u=n.typescript,p=n.wordCharacters||/[\w$\xa1-\uffff]/,d=function(){function t(t){return{type:t,style:"keyword"}}var e=t("keyword a"),n=t("keyword b"),o=t("keyword c"),r=t("keyword d"),i=t("operator"),a={type:"atom",style:"atom"};return{if:t("if"),while:e,with:e,else:n,do:n,try:n,finally:n,return:r,break:r,continue:r,new:t("new"),delete:o,void:o,throw:o,debugger:t("debugger"),var:t("var"),const:t("var"),let:t("var"),function:t("function"),catch:t("catch"),for:t("for"),switch:t("switch"),case:t("case"),default:t("default"),in:i,typeof:i,instanceof:i,true:a,false:a,null:a,undefined:a,NaN:a,Infinity:a,this:t("this"),class:t("class"),super:t("atom"),yield:o,export:t("export"),import:t("import"),extends:o,await:o}}(),f=/[+\-*&%=<>!?|~^@]/,h=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;function v(t){for(var e,n=!1,o=!1;null!=(e=t.next());){if(!n){if("/"==e&&!o)return;"["==e?o=!0:o&&"]"==e&&(o=!1)}n=!n&&"\\"==e}}function g(t,e,n){return o=t,r=n,e}function y(t,e){var n=t.next();if('"'==n||"'"==n)return e.tokenize=m(n),e.tokenize(t,e);if("."==n&&t.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/))return g("number","number");if("."==n&&t.match(".."))return g("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(n))return g(n);if("="==n&&t.eat(">"))return g("=>","operator");if("0"==n&&t.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/))return g("number","number");if(/\d/.test(n))return t.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/),g("number","number");if("/"==n)return t.eat("*")?(e.tokenize=b,b(t,e)):t.eat("/")?(t.skipToEnd(),g("comment","comment")):re(t,e,1)?(v(t),t.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/),g("regexp","string-2")):(t.eat("="),g("operator","operator",t.current()));if("`"==n)return e.tokenize=_,_(t,e);if("#"==n&&"!"==t.peek())return t.skipToEnd(),g("meta","meta");if("#"==n&&t.eatWhile(p))return g("variable","property");if("<"==n&&t.match("!--")||"-"==n&&t.match("->")&&!/\S/.test(t.string.slice(0,t.start)))return t.skipToEnd(),g("comment","comment");if(f.test(n))return">"==n&&e.lexical&&">"==e.lexical.type||(t.eat("=")?"!"!=n&&"="!=n||t.eat("="):/[<>*+\-|&?]/.test(n)&&(t.eat(n),">"==n&&t.eat(n))),"?"==n&&t.eat(".")?g("."):g("operator","operator",t.current());if(p.test(n)){t.eatWhile(p);var o=t.current();if("."!=e.lastType){if(d.propertyIsEnumerable(o)){var r=d[o];return g(r.type,r.style,o)}if("async"==o&&t.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/,!1))return g("async","keyword",o)}return g("variable","variable",o)}}function m(t){return function(e,n){var o,r=!1;if(s&&"@"==e.peek()&&e.match(h))return n.tokenize=y,g("jsonld-keyword","meta");for(;null!=(o=e.next())&&(o!=t||r);)r=!r&&"\\"==o;return r||(n.tokenize=y),g("string","string")}}function b(t,e){for(var n,o=!1;n=t.next();){if("/"==n&&o){e.tokenize=y;break}o="*"==n}return g("comment","comment")}function _(t,e){for(var n,o=!1;null!=(n=t.next());){if(!o&&("`"==n||"$"==n&&t.eat("{"))){e.tokenize=y;break}o=!o&&"\\"==n}return g("quasi","string-2",t.current())}var w="([{}])";function x(t,e){e.fatArrowAt&&(e.fatArrowAt=null);var n=t.string.indexOf("=>",t.start);if(!(n<0)){if(u){var o=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(t.string.slice(t.start,n));o&&(n=o.index)}for(var r=0,i=!1,a=n-1;a>=0;--a){var s=t.string.charAt(a),l=w.indexOf(s);if(l>=0&&l<3){if(!r){++a;break}if(0==--r){"("==s&&(i=!0);break}}else if(l>=3&&l<6)++r;else if(p.test(s))i=!0;else if(/["'\/`]/.test(s))for(;;--a){if(0==a)return;if(t.string.charAt(a-1)==s&&"\\"!=t.string.charAt(a-2)){a--;break}}else if(i&&!r){++a;break}}i&&!r&&(e.fatArrowAt=a)}}var C={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,this:!0,import:!0,"jsonld-keyword":!0};function S(t,e,n,o,r,i){this.indented=t,this.column=e,this.type=n,this.prev=r,this.info=i,null!=o&&(this.align=o)}function O(t,e){if(!c)return!1;for(var n=t.localVars;n;n=n.next)if(n.name==e)return!0;for(var o=t.context;o;o=o.prev)for(n=o.vars;n;n=n.next)if(n.name==e)return!0}function T(t,e,n,o,r){var i=t.cc;for(P.state=t,P.stream=r,P.marked=null,P.cc=i,P.style=e,t.lexical.hasOwnProperty("align")||(t.lexical.align=!0);1;)if((i.length?i.pop():l?$:B)(n,o)){for(;i.length&&i[i.length-1].lex;)i.pop()();return P.marked?P.marked:"variable"==n&&O(t,o)?"variable-2":e}}var P={state:null,column:null,marked:null,cc:null};function E(){for(var t=arguments.length-1;t>=0;t--)P.cc.push(arguments[t])}function k(){return E.apply(null,arguments),!0}function A(t,e){for(var n=e;n;n=n.next)if(n.name==t)return!0;return!1}function j(t){var e=P.state;if(P.marked="def",c){if(e.context)if("var"==e.lexical.info&&e.context&&e.context.block){var o=M(t,e.context);if(null!=o)return void(e.context=o)}else if(!A(t,e.localVars))return void(e.localVars=new I(t,e.localVars));n.globalVars&&!A(t,e.globalVars)&&(e.globalVars=new I(t,e.globalVars))}}function M(t,e){if(e){if(e.block){var n=M(t,e.prev);return n?n==e.prev?e:new L(n,e.vars,!0):null}return A(t,e.vars)?e:new L(e.prev,new I(t,e.vars),!1)}return null}function D(t){return"public"==t||"private"==t||"protected"==t||"abstract"==t||"readonly"==t}function L(t,e,n){this.prev=t,this.vars=e,this.block=n}function I(t,e){this.name=t,this.next=e}var N=new I("this",new I("arguments",null));function R(){P.state.context=new L(P.state.context,P.state.localVars,!1),P.state.localVars=N}function V(){P.state.context=new L(P.state.context,P.state.localVars,!0),P.state.localVars=null}function F(){P.state.localVars=P.state.context.vars,P.state.context=P.state.context.prev}function H(t,e){var n=function(){var n=P.state,o=n.indented;if("stat"==n.lexical.type)o=n.lexical.indented;else for(var r=n.lexical;r&&")"==r.type&&r.align;r=r.prev)o=r.indented;n.lexical=new S(o,P.stream.column(),t,null,n.lexical,e)};return n.lex=!0,n}function U(){var t=P.state;t.lexical.prev&&(")"==t.lexical.type&&(t.indented=t.lexical.indented),t.lexical=t.lexical.prev)}function z(t){function e(n){return n==t?k():";"==t||"}"==n||")"==n||"]"==n?E():k(e)}return e}function B(t,e){return"var"==t?k(H("vardef",e),Et,z(";"),U):"keyword a"==t?k(H("form"),G,B,U):"keyword b"==t?k(H("form"),B,U):"keyword d"==t?P.stream.match(/^\s*$/,!1)?k():k(H("stat"),Y,z(";"),U):"debugger"==t?k(z(";")):"{"==t?k(H("}"),V,dt,U,F):";"==t?k():"if"==t?("else"==P.state.lexical.info&&P.state.cc[P.state.cc.length-1]==U&&P.state.cc.pop()(),k(H("form"),G,B,U,Lt)):"function"==t?k(Vt):"for"==t?k(H("form"),V,It,B,F,U):"class"==t||u&&"interface"==e?(P.marked="keyword",k(H("form","class"==t?t:e),Bt,U)):"variable"==t?u&&"declare"==e?(P.marked="keyword",k(B)):u&&("module"==e||"enum"==e||"type"==e)&&P.stream.match(/^\s*\w/,!1)?(P.marked="keyword","enum"==e?k(ee):"type"==e?k(Ht,z("operator"),yt,z(";")):k(H("form"),kt,z("{"),H("}"),dt,U,U)):u&&"namespace"==e?(P.marked="keyword",k(H("form"),$,B,U)):u&&"abstract"==e?(P.marked="keyword",k(B)):k(H("stat"),it):"switch"==t?k(H("form"),G,z("{"),H("}","switch"),V,dt,U,U,F):"case"==t?k($,z(":")):"default"==t?k(z(":")):"catch"==t?k(H("form"),R,W,B,U,F):"export"==t?k(H("stat"),Gt,U):"import"==t?k(H("stat"),Yt,U):"async"==t?k(B):"@"==e?k($,B):E(H("stat"),$,z(";"),U)}function W(t){if("("==t)return k(Ut,z(")"))}function $(t,e){return K(t,e,!1)}function q(t,e){return K(t,e,!0)}function G(t){return"("!=t?E():k(H(")"),Y,z(")"),U)}function K(t,e,n){if(P.state.fatArrowAt==P.stream.start){var o=n?et:tt;if("("==t)return k(R,H(")"),ut(Ut,")"),U,z("=>"),o,F);if("variable"==t)return E(R,kt,z("=>"),o,F)}var r=n?X:J;return C.hasOwnProperty(t)?k(r):"function"==t?k(Vt,r):"class"==t||u&&"interface"==e?(P.marked="keyword",k(H("form"),zt,U)):"keyword c"==t||"async"==t?k(n?q:$):"("==t?k(H(")"),Y,z(")"),U,r):"operator"==t||"spread"==t?k(n?q:$):"["==t?k(H("]"),te,U,r):"{"==t?pt(st,"}",null,r):"quasi"==t?E(Z,r):"new"==t?k(nt(n)):k()}function Y(t){return t.match(/[;\}\)\],]/)?E():E($)}function J(t,e){return","==t?k(Y):X(t,e,!1)}function X(t,e,n){var o=0==n?J:X,r=0==n?$:q;return"=>"==t?k(R,n?et:tt,F):"operator"==t?/\+\+|--/.test(e)||u&&"!"==e?k(o):u&&"<"==e&&P.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/,!1)?k(H(">"),ut(yt,">"),U,o):"?"==e?k($,z(":"),r):k(r):"quasi"==t?E(Z,o):";"!=t?"("==t?pt(q,")","call",o):"."==t?k(at,o):"["==t?k(H("]"),Y,z("]"),U,o):u&&"as"==e?(P.marked="keyword",k(yt,o)):"regexp"==t?(P.state.lastType=P.marked="operator",P.stream.backUp(P.stream.pos-P.stream.start-1),k(r)):void 0:void 0}function Z(t,e){return"quasi"!=t?E():"${"!=e.slice(e.length-2)?k(Z):k(Y,Q)}function Q(t){if("}"==t)return P.marked="string-2",P.state.tokenize=_,k(Z)}function tt(t){return x(P.stream,P.state),E("{"==t?B:$)}function et(t){return x(P.stream,P.state),E("{"==t?B:q)}function nt(t){return function(e){return"."==e?k(t?rt:ot):"variable"==e&&u?k(Ot,t?X:J):E(t?q:$)}}function ot(t,e){if("target"==e)return P.marked="keyword",k(J)}function rt(t,e){if("target"==e)return P.marked="keyword",k(X)}function it(t){return":"==t?k(U,B):E(J,z(";"),U)}function at(t){if("variable"==t)return P.marked="property",k()}function st(t,e){return"async"==t?(P.marked="property",k(st)):"variable"==t||"keyword"==P.style?(P.marked="property","get"==e||"set"==e?k(lt):(u&&P.state.fatArrowAt==P.stream.start&&(n=P.stream.match(/^\s*:\s*/,!1))&&(P.state.fatArrowAt=P.stream.pos+n[0].length),k(ct))):"number"==t||"string"==t?(P.marked=s?"property":P.style+" property",k(ct)):"jsonld-keyword"==t?k(ct):u&&D(e)?(P.marked="keyword",k(st)):"["==t?k($,ft,z("]"),ct):"spread"==t?k(q,ct):"*"==e?(P.marked="keyword",k(st)):":"==t?E(ct):void 0;var n}function lt(t){return"variable"!=t?E(ct):(P.marked="property",k(Vt))}function ct(t){return":"==t?k(q):"("==t?E(Vt):void 0}function ut(t,e,n){function o(r,i){if(n?n.indexOf(r)>-1:","==r){var a=P.state.lexical;return"call"==a.info&&(a.pos=(a.pos||0)+1),k((function(n,o){return n==e||o==e?E():E(t)}),o)}return r==e||i==e?k():n&&n.indexOf(";")>-1?E(t):k(z(e))}return function(n,r){return n==e||r==e?k():E(t,o)}}function pt(t,e,n){for(var o=3;o"),yt):"quasi"==t?E(wt,St):void 0}function mt(t){if("=>"==t)return k(yt)}function bt(t){return t.match(/[\}\)\]]/)?k():","==t||";"==t?k(bt):E(_t,bt)}function _t(t,e){return"variable"==t||"keyword"==P.style?(P.marked="property",k(_t)):"?"==e||"number"==t||"string"==t?k(_t):":"==t?k(yt):"["==t?k(z("variable"),ht,z("]"),_t):"("==t?E(Ft,_t):t.match(/[;\}\)\],]/)?void 0:k()}function wt(t,e){return"quasi"!=t?E():"${"!=e.slice(e.length-2)?k(wt):k(yt,xt)}function xt(t){if("}"==t)return P.marked="string-2",P.state.tokenize=_,k(wt)}function Ct(t,e){return"variable"==t&&P.stream.match(/^\s*[?:]/,!1)||"?"==e?k(Ct):":"==t?k(yt):"spread"==t?k(Ct):E(yt)}function St(t,e){return"<"==e?k(H(">"),ut(yt,">"),U,St):"|"==e||"."==t||"&"==e?k(yt):"["==t?k(yt,z("]"),St):"extends"==e||"implements"==e?(P.marked="keyword",k(yt)):"?"==e?k(yt,z(":"),yt):void 0}function Ot(t,e){if("<"==e)return k(H(">"),ut(yt,">"),U,St)}function Tt(){return E(yt,Pt)}function Pt(t,e){if("="==e)return k(yt)}function Et(t,e){return"enum"==e?(P.marked="keyword",k(ee)):E(kt,ft,Mt,Dt)}function kt(t,e){return u&&D(e)?(P.marked="keyword",k(kt)):"variable"==t?(j(e),k()):"spread"==t?k(kt):"["==t?pt(jt,"]"):"{"==t?pt(At,"}"):void 0}function At(t,e){return"variable"!=t||P.stream.match(/^\s*:/,!1)?("variable"==t&&(P.marked="property"),"spread"==t?k(kt):"}"==t?E():"["==t?k($,z(']'),z(':'),At):k(z(":"),kt,Mt)):(j(e),k(Mt))}function jt(){return E(kt,Mt)}function Mt(t,e){if("="==e)return k(q)}function Dt(t){if(","==t)return k(Et)}function Lt(t,e){if("keyword b"==t&&"else"==e)return k(H("form","else"),B,U)}function It(t,e){return"await"==e?k(It):"("==t?k(H(")"),Nt,U):void 0}function Nt(t){return"var"==t?k(Et,Rt):"variable"==t?k(Rt):E(Rt)}function Rt(t,e){return")"==t?k():";"==t?k(Rt):"in"==e||"of"==e?(P.marked="keyword",k($,Rt)):E($,Rt)}function Vt(t,e){return"*"==e?(P.marked="keyword",k(Vt)):"variable"==t?(j(e),k(Vt)):"("==t?k(R,H(")"),ut(Ut,")"),U,vt,B,F):u&&"<"==e?k(H(">"),ut(Tt,">"),U,Vt):void 0}function Ft(t,e){return"*"==e?(P.marked="keyword",k(Ft)):"variable"==t?(j(e),k(Ft)):"("==t?k(R,H(")"),ut(Ut,")"),U,vt,F):u&&"<"==e?k(H(">"),ut(Tt,">"),U,Ft):void 0}function Ht(t,e){return"keyword"==t||"variable"==t?(P.marked="type",k(Ht)):"<"==e?k(H(">"),ut(Tt,">"),U):void 0}function Ut(t,e){return"@"==e&&k($,Ut),"spread"==t?k(Ut):u&&D(e)?(P.marked="keyword",k(Ut)):u&&"this"==t?k(ft,Mt):E(kt,ft,Mt)}function zt(t,e){return"variable"==t?Bt(t,e):Wt(t,e)}function Bt(t,e){if("variable"==t)return j(e),k(Wt)}function Wt(t,e){return"<"==e?k(H(">"),ut(Tt,">"),U,Wt):"extends"==e||"implements"==e||u&&","==t?("implements"==e&&(P.marked="keyword"),k(u?yt:$,Wt)):"{"==t?k(H("}"),$t,U):void 0}function $t(t,e){return"async"==t||"variable"==t&&("static"==e||"get"==e||"set"==e||u&&D(e))&&P.stream.match(/^\s+[\w$\xa1-\uffff]/,!1)?(P.marked="keyword",k($t)):"variable"==t||"keyword"==P.style?(P.marked="property",k(qt,$t)):"number"==t||"string"==t?k(qt,$t):"["==t?k($,ft,z("]"),qt,$t):"*"==e?(P.marked="keyword",k($t)):u&&"("==t?E(Ft,$t):";"==t||","==t?k($t):"}"==t?k():"@"==e?k($,$t):void 0}function qt(t,e){if("!"==e)return k(qt);if("?"==e)return k(qt);if(":"==t)return k(yt,Mt);if("="==e)return k(q);var n=P.state.lexical.prev;return E(n&&"interface"==n.info?Ft:Vt)}function Gt(t,e){return"*"==e?(P.marked="keyword",k(Qt,z(";"))):"default"==e?(P.marked="keyword",k($,z(";"))):"{"==t?k(ut(Kt,"}"),Qt,z(";")):E(B)}function Kt(t,e){return"as"==e?(P.marked="keyword",k(z("variable"))):"variable"==t?E(q,Kt):void 0}function Yt(t){return"string"==t?k():"("==t?E($):"."==t?E(J):E(Jt,Xt,Qt)}function Jt(t,e){return"{"==t?pt(Jt,"}"):("variable"==t&&j(e),"*"==e&&(P.marked="keyword"),k(Zt))}function Xt(t){if(","==t)return k(Jt,Xt)}function Zt(t,e){if("as"==e)return P.marked="keyword",k(Jt)}function Qt(t,e){if("from"==e)return P.marked="keyword",k($)}function te(t){return"]"==t?k():E(ut(q,"]"))}function ee(){return E(H("form"),kt,z("{"),H("}"),ut(ne,"}"),U,U)}function ne(){return E(kt,Mt)}function oe(t,e){return"operator"==t.lastType||","==t.lastType||f.test(e.charAt(0))||/[,.]/.test(e.charAt(0))}function re(t,e,n){return e.tokenize==y&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(e.lastType)||"quasi"==e.lastType&&/\{\s*$/.test(t.string.slice(0,t.pos-(n||0)))}return F.lex=!0,U.lex=!0,{startState:function(t){var e={tokenize:y,lastType:"sof",cc:[],lexical:new S((t||0)-i,0,"block",!1),localVars:n.localVars,context:n.localVars&&new L(null,null,!1),indented:t||0};return n.globalVars&&"object"==typeof n.globalVars&&(e.globalVars=n.globalVars),e},token:function(t,e){if(t.sol()&&(e.lexical.hasOwnProperty("align")||(e.lexical.align=!1),e.indented=t.indentation(),x(t,e)),e.tokenize!=b&&t.eatSpace())return null;var n=e.tokenize(t,e);return"comment"==o?n:(e.lastType="operator"!=o||"++"!=r&&"--"!=r?o:"incdec",T(e,n,o,r,t))},indent:function(e,o){if(e.tokenize==b||e.tokenize==_)return t.Pass;if(e.tokenize!=y)return 0;var r,s=o&&o.charAt(0),l=e.lexical;if(!/^\s*else\b/.test(o))for(var c=e.cc.length-1;c>=0;--c){var u=e.cc[c];if(u==U)l=l.prev;else if(u!=Lt&&u!=F)break}for(;("stat"==l.type||"form"==l.type)&&("}"==s||(r=e.cc[e.cc.length-1])&&(r==J||r==X)&&!/^[,\.=+\-*:?[\(]/.test(o));)l=l.prev;a&&")"==l.type&&"stat"==l.prev.type&&(l=l.prev);var p=l.type,d=s==p;return"vardef"==p?l.indented+("operator"==e.lastType||","==e.lastType?l.info.length+1:0):"form"==p&&"{"==s?l.indented:"form"==p?l.indented+i:"stat"==p?l.indented+(oe(e,o)?a||i:0):"switch"!=l.info||d||0==n.doubleIndentSwitch?l.align?l.column+(d?0:1):l.indented+(d?0:i):l.indented+(/^(?:case|default)\b/.test(o)?i:2*i)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:l?null:"/*",blockCommentEnd:l?null:"*/",blockCommentContinue:l?null:" * ",lineComment:l?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:l?"json":"javascript",jsonldMode:s,jsonMode:l,expressionAllowed:re,skipExpression:function(e){T(e,"atom","atom","true",new t.StringStream("",2,null))}}})),t.registerHelper("wordChars","javascript",/[\w$]/),t.defineMIME("text/javascript","javascript"),t.defineMIME("text/ecmascript","javascript"),t.defineMIME("application/javascript","javascript"),t.defineMIME("application/x-javascript","javascript"),t.defineMIME("application/ecmascript","javascript"),t.defineMIME("application/json",{name:"javascript",json:!0}),t.defineMIME("application/x-json",{name:"javascript",json:!0}),t.defineMIME("application/manifest+json",{name:"javascript",json:!0}),t.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),t.defineMIME("text/typescript",{name:"javascript",typescript:!0}),t.defineMIME("application/typescript",{name:"javascript",typescript:!0})}(n(4408))},9701:(t,e,n)=>{1&&function(t){"use strict";var e={autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0},n={autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,allowMissingTagName:!1,caseFold:!1};t.defineMode("xml",(function(o,r){var i,a,s=o.indentUnit,l={},c=r.htmlMode?e:n;for(var u in c)l[u]=c[u];for(var u in r)l[u]=r[u];function p(t,e){function n(n){return e.tokenize=n,n(t,e)}var o=t.next();return"<"==o?t.eat("!")?t.eat("[")?t.match("CDATA[")?n(h("atom","]]>")):null:t.match("--")?n(h("comment","--\x3e")):t.match("DOCTYPE",!0,!0)?(t.eatWhile(/[\w\._\-]/),n(v(1))):null:t.eat("?")?(t.eatWhile(/[\w\._\-]/),e.tokenize=h("meta","?>"),"meta"):(i=t.eat("/")?"closeTag":"openTag",e.tokenize=d,"tag bracket"):"&"==o?(t.eat("#")?t.eat("x")?t.eatWhile(/[a-fA-F\d]/)&&t.eat(";"):t.eatWhile(/[\d]/)&&t.eat(";"):t.eatWhile(/[\w\.\-:]/)&&t.eat(";"))?"atom":"error":(t.eatWhile(/[^&<]/),null)}function d(t,e){var n=t.next();if(">"==n||"/"==n&&t.eat(">"))return e.tokenize=p,i=">"==n?"endTag":"selfcloseTag","tag bracket";if("="==n)return i="equals",null;if("<"==n){e.tokenize=p,e.state=_,e.tagName=e.tagStart=null;var o=e.tokenize(t,e);return o?o+" tag error":"tag error"}return/[\'\"]/.test(n)?(e.tokenize=f(n),e.stringStartCol=t.column(),e.tokenize(t,e)):(t.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/),"word")}function f(t){var e=function(e,n){for(;!e.eol();)if(e.next()==t){n.tokenize=d;break}return"string"};return e.isInAttribute=!0,e}function h(t,e){return function(n,o){for(;!n.eol();){if(n.match(e)){o.tokenize=p;break}n.next()}return t}}function v(t){return function(e,n){for(var o;null!=(o=e.next());){if("<"==o)return n.tokenize=v(t+1),n.tokenize(e,n);if(">"==o){if(1==t){n.tokenize=p;break}return n.tokenize=v(t-1),n.tokenize(e,n)}}return"meta"}}function g(t){return t&&t.toLowerCase()}function y(t,e,n){this.prev=t.context,this.tagName=e||"",this.indent=t.indented,this.startOfLine=n,(l.doNotIndent.hasOwnProperty(e)||t.context&&t.context.noIndent)&&(this.noIndent=!0)}function m(t){t.context&&(t.context=t.context.prev)}function b(t,e){for(var n;1;){if(!t.context)return;if(n=t.context.tagName,!l.contextGrabbers.hasOwnProperty(g(n))||!l.contextGrabbers[g(n)].hasOwnProperty(g(e)))return;m(t)}}function _(t,e,n){return"openTag"==t?(n.tagStart=e.column(),w):"closeTag"==t?x:_}function w(t,e,n){return"word"==t?(n.tagName=e.current(),a="tag",O):l.allowMissingTagName&&"endTag"==t?(a="tag bracket",O(t,e,n)):(a="error",w)}function x(t,e,n){if("word"==t){var o=e.current();return n.context&&n.context.tagName!=o&&l.implicitlyClosed.hasOwnProperty(g(n.context.tagName))&&m(n),n.context&&n.context.tagName==o||!1===l.matchClosing?(a="tag",C):(a="tag error",S)}return l.allowMissingTagName&&"endTag"==t?(a="tag bracket",C(t,e,n)):(a="error",S)}function C(t,e,n){return"endTag"!=t?(a="error",C):(m(n),_)}function S(t,e,n){return a="error",C(t,e,n)}function O(t,e,n){if("word"==t)return a="attribute",T;if("endTag"==t||"selfcloseTag"==t){var o=n.tagName,r=n.tagStart;return n.tagName=n.tagStart=null,"selfcloseTag"==t||l.autoSelfClosers.hasOwnProperty(g(o))?b(n,o):(b(n,o),n.context=new y(n,o,r==n.indented)),_}return a="error",O}function T(t,e,n){return"equals"==t?P:(l.allowMissing||(a="error"),O(t,e,n))}function P(t,e,n){return"string"==t?E:"word"==t&&l.allowUnquoted?(a="string",O):(a="error",O(t,e,n))}function E(t,e,n){return"string"==t?E:O(t,e,n)}return p.isInText=!0,{startState:function(t){var e={tokenize:p,state:_,indented:t||0,tagName:null,tagStart:null,context:null};return null!=t&&(e.baseIndent=t),e},token:function(t,e){if(!e.tagName&&t.sol()&&(e.indented=t.indentation()),t.eatSpace())return null;i=null;var n=e.tokenize(t,e);return(n||i)&&"comment"!=n&&(a=null,e.state=e.state(i||n,t,e),a&&(n="error"==a?n+" error":a)),n},indent:function(e,n,o){var r=e.context;if(e.tokenize.isInAttribute)return e.tagStart==e.indented?e.stringStartCol+1:e.indented+s;if(r&&r.noIndent)return t.Pass;if(e.tokenize!=d&&e.tokenize!=p)return o?o.match(/^(\s*)/)[0].length:0;if(e.tagName)return!1!==l.multilineTagIndentPastTag?e.tagStart+e.tagName.length+2:e.tagStart+s*(l.multilineTagIndentFactor||1);if(l.alignCDATA&&/$/,blockCommentStart:"\x3c!--",blockCommentEnd:"--\x3e",configuration:l.htmlMode?"html":"xml",helperType:l.htmlMode?"html":"xml",skipAttribute:function(t){t.state==P&&(t.state=O)},xmlCurrentTag:function(t){return t.tagName?{name:t.tagName,close:"closeTag"==t.type}:null},xmlCurrentContext:function(t){for(var e=[],n=t.context;n;n=n.prev)e.push(n.tagName);return e.reverse()}}})),t.defineMIME("text/xml","xml"),t.defineMIME("application/xml","xml"),t.mimeModes.hasOwnProperty("text/html")||t.defineMIME("text/html",{name:"xml",htmlMode:!0})}(n(4408))},7058:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var o,r=n(9156),i=void 0&&(void 0).__extends||(o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},o(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});const a=function(t){function e(e,n,o){var r=t.call(this,n,o)||this;return r._module=e,r}return i(e,t),Object.defineProperty(e.prototype,"module",{get:function(){return this._module},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"config",{get:function(){return this._module.config},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"em",{get:function(){return this._module.em},enumerable:!1,configurable:!0}),e}(r.Kx)},179:(t,e,n)=>{"use strict";n.d(e,{A:()=>s,F:()=>r});var o,r,i=n(7058),a=void 0&&(void 0).__extends||(o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},o(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});!function(t){t["Select"]="select",t["Hover"]="hover",t["Spacing"]="spacing",t["Target"]="target",t["Resize"]="resize"}(r||(r={}));const s=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return a(e,t),e.prototype.defaults=function(){return{id:'',type:''}},Object.defineProperty(e.prototype,"type",{get:function(){return this.get('type')||''},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"component",{get:function(){var t;return this.get('component')||(null===(t=this.get('componentView'))||void 0===t?void 0:t.model)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"componentView",{get:function(){var t;return this.get('componentView')||(null===(t=this.get('component'))||void 0===t?void 0:t.getView())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"el",{get:function(){var t;return null===(t=this.componentView)||void 0===t?void 0:t.el},enumerable:!1,configurable:!0}),e.prototype.getBoxRect=function(t){var e=this.el,n=this.em.Canvas.getCanvasView(),o=this.get('boxRect');return o||(e&&n?n.getElBoxRect(e,t):{x:0,y:0,width:0,height:0})},e.prototype.getStyle=function(t){void 0===t&&(t={});var e=t.boxRect||this.getBoxRect(t),n=e.width,o=e.height,r=e.x,i=e.y;return{width:"".concat(n,"px"),height:"".concat(o,"px"),top:'0',left:'0',position:'absolute',translate:"".concat(r,"px ").concat(i,"px")}},e.prototype.isType=function(t){return this.type===t},e}(i.A)},1738:(t,e,n)=>{"use strict";var o;n.d(e,{A:()=>r}),function(t){t["run"]="command:run",t["runCommand"]="command:run:",t["runBeforeCommand"]="command:run:before:",t["abort"]="command:abort:",t["stop"]="command:stop",t["stopCommand"]="command:stop:",t["stopBeforeCommand"]="command:stop:before:",t["call"]="command:call",t["callCommand"]="command:call:"}(o||(o={}));const r=o},9484:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});const o={run:function(t){t.Components.clear(),t.Css.clear()}}},9516:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>a});var o=n(5706),r=n(9966),i=n(6294);const a={run:function(t){(0,o.bindAll)(this,'onKeyUp','enableDragger','disableDragger'),this.editor=t,this.canvasModel=this.canvas.getCanvasView().model,this.toggleMove(1)},stop:function(t){this.toggleMove(),this.disableDragger()},onKeyUp:function(t){' '===(0,i.Ch)(t)&&this.editor.stopCommand(this.id)},enableDragger:function(t){this.toggleDragger(1,t)},disableDragger:function(t){this.toggleDragger(0,t)},toggleDragger:function(t,e){var n=this.canvasModel,o=this.em,i=this.dragger,a=t?'add':'remove';this.getCanvas().classList[a]("".concat(this.ppfx,"is__grabbing")),i||(i=new r.A({getPosition:function(){return{x:n.get('x'),y:n.get('y')}},setPosition:function(t){var e=t.x,o=t.y;n.set({x:e,y:o})},onStart:function(t,e){o.trigger('canvas:move:start',e)},onDrag:function(t,e){o.trigger('canvas:move',e)},onEnd:function(t,e){o.trigger('canvas:move:end',e)}}),this.dragger=i),t?i.start(e):i.stop()},toggleMove:function(t){var e=this.ppfx,n=t?'add':'remove',o=t?'on':'off',r={on:i.on,off:i.AU},a=this.getCanvas(),s=["".concat(e,"is__grab")];!t&&s.push("".concat(e,"is__grabbing")),s.forEach((function(t){return a.classList[n](t)})),r[o](document,'keyup',this.onKeyUp),r[o](a,'mousedown',this.enableDragger),r[o](document,'mouseup',this.disableDragger)}}},9946:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>c,defineCommand:()=>l});var o,r=n(9156),i=n(1738),a=void 0&&(void 0).__extends||(o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},o(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),s=void 0&&(void 0).__assign||function(){return s=Object.assign||function(t){for(var e,n=1,o=arguments.length;n{"use strict";n.r(e),n.d(e,{default:()=>i});var o=n(5706),r=void 0&&(void 0).__spreadArray||function(t,e,n){if(n||2===arguments.length)for(var o,r=0,i=e.length;r{"use strict";n.r(e),n.d(e,{default:()=>l});var o=n(5706),r=n(9966),i=n(1166),a=void 0&&(void 0).__assign||function(){return a=Object.assign||function(t){for(var e,n=1,o=arguments.length;n\n
\n ");(a=document.createElement('div')).className="".concat(p,"guides"),d.className="".concat(p,"guide-info ").concat(p,"guide-info__x"),f.className="".concat(p,"guide-info ").concat(p,"guide-info__y"),d.innerHTML=h,f.innerHTML=h,a.appendChild(d),a.appendChild(f),null===(e=l.Canvas.getGlobalToolsEl())||void 0===e||e.appendChild(a),this.guidesEl=a,this.elGuideInfoX=d,this.elGuideInfoY=f,this.elGuideInfoContentX=null!==(n=d.querySelector(".".concat(p,"guide-info__content")))&&void 0!==n?n:void 0,this.elGuideInfoContentY=null!==(r=f.querySelector(".".concat(p,"guide-info__content")))&&void 0!==r?r:void 0,c.on('canvas:update frame:scroll',(0,o.debounce)((function(){var t;i.updateGuides(),u.debug&&(null===(t=i.guides)||void 0===t||t.forEach((function(t){return i.renderGuide(t)})))}),200))}return a},getGuidesStatic:function(){var t=this,e=[],n=this.target.getEl(),r=null==n?void 0:n.parentElement;return r?((0,o.each)(r.children,(function(o){return e=e.concat(n!==o?t.getElementGuides(o):[])})),e.concat(this.getElementGuides(r))):[]},getGuidesTarget:function(){return this.getElementGuides(this.target.getEl())},updateGuides:function(t){var e,n,r,i=this;(null!==(e=null!=t?t:this.guides)&&void 0!==e?e:[]).forEach((function(t){var e=t.origin,a=n===e?r:i.getElementPos(e);n=e,r=a,(0,o.each)(i.getGuidePosUpdate(t,a),(function(e,n){t[n]=e})),t.originRect=a}))},getGuidePosUpdate:function(t,e){var n={},o=e.top,r=e.height,i=e.left,a=e.width;switch(t.type){case't':n.y=o;break;case'b':n.y=o+r;break;case'l':n.x=i;break;case'r':n.x=i+a;break;case'x':n.x=i+a/2;break;case'y':n.y=o+r/2}return n},renderGuide:function(t){var e,n;if(!this.opts.skipGuidesRender){var o=null!==(e=t.guide)&&void 0!==e?e:document.createElement('div'),r='px',i=t.active?2:1;if(o.style.cssText="position: absolute; background-color: ".concat(t.active?'green':'red',";"),!o.children.length){var a=document.createElement('div');a.style.cssText='position: absolute; color: red; padding: 5px; top: 0; left: 0;',o.appendChild(a)}return t.y?(o.style.width='100%',o.style.height="".concat(i).concat(r),o.style.top="".concat(t.y).concat(r),o.style.left='0'):(o.style.width="".concat(i).concat(r),o.style.height='100%',o.style.left="".concat(t.x).concat(r),o.style.top="0".concat(r)),!t.guide&&(null===(n=this.guidesContainer)||void 0===n||n.appendChild(o)),o}},getElementPos:function(t){return this.editor.Canvas.getElementPos(t,{noScroll:1})},getElementGuides:function(t){var e=this,n=this.opts,o=t,r=this.getElementPos(t),s=(0,i.getComponentModel)(t),l=(0,i.getComponentView)(t),c=r.top,u=r.height,p=r.left,d=r.width,f=[{type:'t',y:c},{type:'b',y:c+u},{type:'l',x:p},{type:'r',x:p+d},{type:'x',x:p+d/2},{type:'y',y:c+u/2}].map((function(t){var i=n.debug?e.renderGuide(t):void 0;return a(a({},t),{component:s,componentView:l,componentEl:o,origin:o,componentElRect:r,originRect:r,guideEl:i,guide:i})}));return f.forEach((function(t){var n;return null===(n=e.guides)||void 0===n?void 0:n.push(t)})),f},getTranslate:function(t,e){void 0===e&&(e='x');var n=0;return(t||'').split(' ').forEach((function(t){var o=t.trim(),r="translate".concat(e.toUpperCase(),"(");0===o.indexOf(r)&&(n=parseFloat(o.replace(r,'')))})),n},setTranslate:function(t,e,n){var o="translate".concat(e.toUpperCase(),"("),r="".concat(o).concat(n,")"),i=(t||'').split(' ').map((function(t){return 0===t.trim().indexOf(o)&&(t=r),t})).join(' ');return i.indexOf(o)<0&&(i+=" ".concat(r)),i},getPosition:function(){var t=this.target,e=this.isTran,n=t.getStyle(),o=n.transform,r=n.left,i=n.top,a=0,s=0;return e&&o?(a=this.getTranslate(o),s=this.getTranslate(o,'y')):(a=parseFloat(null!=r?r:'0'),s=parseFloat(null!=i?i:'0')),{x:a,y:s}},setPosition:function(t){var e,n,r=t.x,i=t.y,a=t.end,s=t.position,l=t.width,c=t.height,u=this,p=u.target,d=u.isTran,f=u.em,h=u.opts,v='px',g=!a,y="".concat(parseInt("".concat(r),10)).concat(v),m="".concat(parseInt("".concat(i),10)).concat(v),b={};if(d){var _=null!==(n=null===(e=p.getStyle())||void 0===e?void 0:e.transform)&&void 0!==n?n:'';_=this.setTranslate(_,'x',y),b={transform:_=this.setTranslate(_,'y',m),__p:g}}else{var w={position:s,width:l,height:c},x={left:y,top:m,__p:g};(0,o.keys)(w).forEach((function(t){var e=w[t];e&&(x[t]=e)})),b=x}h.addStyle?h.addStyle({component:p,styles:b,partial:!a}):p.addStyle(b,{avoidStore:!a}),f.Styles.__emitCmpStyleUpdate(b,{components:f.getSelected()})},_getDragData:function(){var t=this.target;return{target:t,parent:t.parent(),index:t.index()}},onStart:function(t){var e,n=this,o=n.target,r=n.editor,i=n.isTran,a=n.opts,s=r.Canvas,l=o.getStyle(),c='absolute',u=[c,'relative'];if(null===(e=a.onStart)||void 0===e||e.call(a,this._getDragData()),!i){if(l.position!==c){var p=s.offset(o.getEl()),d=p.left,f=p.top,h=p.width,v=p.height,g=o.parent(),y=null;do{var m=null==g?void 0:g.getStyle(),b=null==m?void 0:m.position;b&&(y=u.indexOf(b)>=0?g:null),g=null==g?void 0:g.parent()}while(g&&!y);if(a.center){var _=s.getMouseRelativeCanvas(t);d=_.x,f=_.y}else if(y){var w=s.offset(y.getEl());d-=w.left,f-=w.top}this.setPosition({x:d,y:f,width:"".concat(h,"px"),height:"".concat(v,"px"),position:c})}this.guidesStatic=this.getGuidesStatic()}},onDrag:function(t){var e,n,o=this,r=this.guidesTarget,i=this.opts;this.updateGuides(r),i.debug&&(null==r||r.forEach((function(t){return o.renderGuide(t)}))),i.guidesInfo&&this.renderGuideInfo(null!==(e=null==r?void 0:r.filter((function(t){return t.active})))&&void 0!==e?e:[]),null===(n=i.onDrag)||void 0===n||n.call(i,this._getDragData()),this.opts.event=t,this.em.trigger("".concat(s,":move"),this.getEventOpts())},onEnd:function(t,e,n){var o,r=this,i=r.editor,l=r.opts,c=r.id;null===(o=l.onEnd)||void 0===o||o.call(l,t,n,a(a({event:t},n),this._getDragData())),i.stopCommand("".concat(c)),this.hideGuidesInfo(),this.em.trigger("".concat(s,":end"),this.getEventOpts())},hideGuidesInfo:function(){var t=this;['X','Y'].forEach((function(e){var n=t["elGuideInfo".concat(e)];n&&(n.style.display='none')}))},renderGuideInfo:function(t){var e=this;void 0===t&&(t=[]),this.hideGuidesInfo(),this.getGuidesMatched(t).forEach((function(t){e.opts.skipGuidesRender||e.renderSingleGuideInfo(t),e.em.trigger("".concat(s,":active"),a(a({},e.getEventOpts()),t))}))},renderSingleGuideInfo:function(t){var e=t.posFirst,n=t.posSecond,r=t.size,i=t.sizeRaw,a=t.guide,s=t.elGuideInfo,l=t.elGuideInfoCnt,c='y'===((0,o.isUndefined)(a.x)?'y':'x'),u=s.style;u.display='',u[c?'top':'left']="".concat(e,"px"),u[c?'left':'top']="".concat(n,"px"),u[c?'width':'height']="".concat(r,"px"),l.innerHTML="".concat(Math.round(i),"px")},getGuidesMatched:function(t){var e=this;void 0===t&&(t=[]);var n=this.guidesStatic,r=void 0===n?[]:n;return t.map((function(t){var n=t.origin,i=t.x,a=e.getElementPos(n),s=(0,o.isUndefined)(i)?'y':'x',l='y'===s,c=a[l?'left':'top'],u=a.rect[l?'left':'top'],p=l?c+a.width:c+a.height,d=l?u+a.rect.width:u+a.rect.height,f=r.filter((function(e){var n;return e.type===t.type||(null===(n={l:['r','x'],r:['l','x'],x:['l','r'],t:['b','y'],b:['t','y'],y:['t','b']}[t.type])||void 0===n?void 0:n.includes(e.type))})).map((function(t){var e=t.originRect,n=e.left,o=e.width,r=e.top,i=e.height,a=l?n+o:r+i;return{gap:a0})).sort((function(t,e){return t.gap-e.gap})).map((function(t){return t.guide})).filter((function(e){switch(t.type){case'l':case'r':case'x':return Math.abs(e.x-t.x)<1;case't':case'b':case'y':return Math.abs(e.y-t.y)<1;default:return!1}})),h=f[0];if(h){var v=h.originRect,g=v.left,y=v.width,m=v.top,b=v.height,_=v.rect,w=l?g{"use strict";n.r(e),n.d(e,{default:()=>o});const o={run:function(t){if(t.Canvas.hasFocus()){var e=[];t.getSelectedAll().forEach((function(t){var n=t.components(),o=n&&n.filter((function(t){return t.get('selectable')}))[0];o&&e.push(o)})),e.length&&t.select(e)}}}},914:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});const o={run:function(t,e,n){if(void 0===n&&(n={}),t.Canvas.hasFocus()||n.force){var o=[];t.getSelectedAll().forEach((function(t){for(var e=t.parent();e&&!e.get('selectable');)e=e.parent();e&&o.push(e)})),o.length&&t.select(o)}}}},5547:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});const o={run:function(t){if(t.Canvas.hasFocus()){var e=[];t.getSelectedAll().forEach((function(t){var n=t.parent();if(n){var o,r=n.components().length,i=0,a=0;do{i++,o=(a=t.index()+i)<=r?n.getChildAt(a):null}while(o&&!o.get('selectable'));e.push(o||t)}})),e.length&&t.select(e)}}}},8655:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});const o={run:function(t){if(t.Canvas.hasFocus()){var e=[];t.getSelectedAll().forEach((function(t){var n=t.parent();if(n){var o,r=0,i=0;do{r++,o=(i=t.index()-r)>=0?n.getChildAt(i):null}while(o&&!o.get('selectable'));e.push(o||t)}})),e.length&&t.select(e)}}}},7640:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>r});var o=n(5706);const r={run:function(t,e,n){void 0===n&&(n={});var r=n.target,i=[];if(!r.get('styles'))return i;var a=r.get('type'),s=t.Pages.getAllWrappers();if(!(0,o.flatten)(s.map((function(t){return t.findType(a)}))).length){var l=t.CssComposer.getAll();i=l.filter((function(t){return t.get('group')==="cmp:".concat(a)})),l.remove(i)}return i}}},5837:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>r});var o=void 0&&(void 0).__spreadArray||function(t,e,n){if(n||2===arguments.length)for(var o,r=0,i=e.length;r{"use strict";n.r(e),n.d(e,{default:()=>r});var o=n(6294);const r={run:function(t,e,n){var r=this;void 0===n&&(n={}),e&&e.set&&e.set('active',0);var i=t.getConfig(),a=t.Modal,s=i.stylePrefix;if(this.cm=t.CodeManager||null,!this.editors){var l=this.buildEditor('htmlmixed','hopscotch','HTML'),c=this.buildEditor('css','hopscotch','CSS');this.htmlEditor=l.model,this.cssEditor=c.model;var u=(0,o.a_)('div',{class:"".concat(s,"export-dl")});u.appendChild(l.el),u.appendChild(c.el),this.editors=u}a.open({title:i.textViewCode,content:this.editors}).getModel().once('change:open',(function(){return t.stopCommand("".concat(r.id))})),this.htmlEditor.setContent(t.getHtml(n.optsHtml)),this.cssEditor.setContent(t.getCss(n.optsCss))},stop:function(t){var e=t.Modal;e&&e.close()},buildEditor:function(t,e,n){var o=this.em.CodeManager,r=o.createViewer({label:n,codeName:t,theme:e});return{model:r,el:new o.EditorView({model:r,config:o.getConfig()}).render().el}}}},1772:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>r});var o=n(5706);const r={isEnabled:function(){var t=document;return!!(t.fullscreenElement||t.webkitFullscreenElement||t.mozFullScreenElement)},enable:function(t){var e='';return t.requestFullscreen?t.requestFullscreen():t.webkitRequestFullscreen?(e='webkit',t.webkitRequestFullscreen()):t.mozRequestFullScreen?(e='moz',t.mozRequestFullScreen()):t.msRequestFullscreen&&t.msRequestFullscreen(),e},disable:function(){var t=document;this.isEnabled()&&(t.exitFullscreen?t.exitFullscreen():t.webkitExitFullscreen?t.webkitExitFullscreen():t.mozCancelFullScreen?t.mozCancelFullScreen():t.msExitFullscreen&&t.msExitFullscreen())},fsChanged:function(t){this.isEnabled()||(this.stopCommand({sender:this.sender}),document.removeEventListener("".concat(t||'',"fullscreenchange"),this.fsChanged))},run:function(t,e,n){void 0===n&&(n={}),this.sender=e;var r=n.target,i=(0,o.isElement)(r)?r:document.querySelector(r),a=this.enable(i||t.getContainer());this.fsChanged=this.fsChanged.bind(this,a),document.addEventListener(a+'fullscreenchange',this.fsChanged)},stop:function(t,e){e&&e.set&&e.set('active',!1),this.disable()}}},741:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>l});var o=n(5706),r=n(7774),i=n(6294),a=n(9317),s=n(1406);const l=(0,o.extend)({},s["default"],a["default"],{init:function(t){a["default"].init.apply(this,arguments),(0,o.bindAll)(this,'initSorter','rollback','onEndMove'),this.opt=t,this.hoverClass=this.ppfx+'highlighter-warning',this.badgeClass=this.ppfx+'badge-warning',this.noSelClass=this.ppfx+'no-select'},enable:function(){for(var t=[],e=0;e{"use strict";n.r(e),n.d(e,{default:()=>i});var o=n(5706),r=n(6294);const i={open:function(t){var e=this,n=this,r=n.editor,i=n.title,a=n.config,s=n.am,l=a.custom;if((0,o.isFunction)(l.open))return l.open(s.__customData());r.Modal.open({title:i,content:t}).onceClose((function(){return r.stopCommand(e.id)}))},close:function(){var t=this.config.custom;if((0,o.isFunction)(t.close))return t.close(this.am.__customData());var e=this.editor.Modal;e&&e.close()},run:function(t,e,n){void 0===n&&(n={});var o=t.AssetManager,i=o.getConfig(),a=n.types,s=void 0===a?[]:a,l=n.accept,c=n.select;if(this.title=n.modalTitle||t.t('assetManager.modalTitle')||'',this.editor=t,this.config=i,this.am=o,o.setTarget(n.target),o.onClick(n.onClick),o.onDblClick(n.onDblClick),o.onSelect(n.onSelect),o.__behaviour({select:c,types:s,options:n}),i.custom)this.rendered=this.rendered||(0,r.a_)('div'),this.rendered.className="".concat(i.stylePrefix,"custom-wrp"),o.__behaviour({container:this.rendered}),o.__trgCustom();else{if(!this.rendered||s){var u=o.getAll().filter((function(t){return t}));s&&s.length&&(u=u.filter((function(t){return-1!==s.indexOf(t.get('type'))}))),o.render(u),this.rendered=o.getContainer()}if(l){var p=this.rendered.querySelector("input#".concat(i.stylePrefix,"uploadFile"));p&&p.setAttribute('accept',l)}}return this.open(this.rendered),this},stop:function(t){this.editor=t,this.close(this.rendered)}}},3963:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>i});var o=n(5706),r=n(6294);const i={open:function(){var t=this,e=t.container,n=t.editor,r=t.bm,i=t.config,a=i.custom,s=i.appendTo;if((0,o.isFunction)(a.open))return a.open(r.__customData());if(this.firstRender&&!s){var l='views-container',c=n.Panels;(c.getPanel(l)||c.addPanel({id:l})).set('appendContent',e).trigger('change:appendContent'),a||e.appendChild(r.render())}e&&(e.style.display='block')},close:function(){var t=this.container,e=this.config.custom;if((0,o.isFunction)(e.close))return e.close(this.bm.__customData());t&&(t.style.display='none')},run:function(t){var e=t.Blocks;this.config=e.getConfig(),this.firstRender=!this.container,this.container=this.container||(0,r.a_)('div'),this.editor=t,this.bm=e;var n=this.container;e.__behaviour({container:n}),this.config.custom&&e.__trgCustom(),this.open()},stop:function(){this.close()}}},1479:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});const o={run:function(t){var e=t.LayerManager,n=t.Panels,o=e.getConfig();if(!o.appendTo){if(!this.layers){var r='views-container',i=document.createElement('div'),a=n.getPanel(r)||n.addPanel({id:r});o.custom?e.__trgCustom({container:i}):i.appendChild(e.render()),a.set('appendContent',i).trigger('change:appendContent'),this.layers=i}this.layers.style.display='block'}},stop:function(){var t=this.layers;t&&(t.style.display='none')}}},3473:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>r});var o=n(7774);const r={run:function(t,e){if(this.sender=e,!this.$cnt){var n=t.getConfig(),r=t.Panels,i=t.DeviceManager,a=t.SelectorManager,s=t.StyleManager,l='change:appendContent',c=(0,o["default"])('
'),u=(0,o["default"])('
'),p=(0,o["default"])('
'),d=(0,o["default"])('
');if(this.$cnt=c,this.$cntInner=u,u.append(p),u.append(d),c.append(u),i&&n.showDevices){var f=r.addPanel({id:'devices-c'}),h=i.render();f.set('appendContent',h).trigger(l)}var v=a.getConfig();v.custom?a.__trgCustom({container:p.get(0)}):v.appendTo||p.append(a.render([])),this.sm=s;var g=s.getConfig(),y=g.stylePrefix;this.$header=(0,o["default"])("
").concat(t.t('styleManager.empty'),"
")),c.append(this.$header),g.custom?s.__trgCustom({container:d.get(0)}):g.appendTo||d.append(s.render());var m='views-container';(r.getPanel(m)||r.addPanel({id:m})).set('appendContent',c).trigger(l);var b=t.getModel();this.listenTo(b,s.events.target,this.toggleSm)}this.toggleSm()},toggleSm:function(){var t=this,e=t.sender,n=t.sm,o=t.$cntInner,r=t.$header;e&&e.get&&!e.get('active')||!n||(n.getSelected()?(null==o||o.show(),null==r||r.hide()):(null==o||o.hide(),null==r||r.show()))},stop:function(){var t,e;null===(t=this.$cntInner)||void 0===t||t.hide(),null===(e=this.$header)||void 0===e||e.hide()}}},5054:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>r});var o=n(7774);const r={run:function(t,e){this.sender=e;var n,r=t.getModel(),i=t.Config.stylePrefix,a=t.TraitManager,s=a.getConfig();if(!s.appendTo){if(!this.$cn){this.$cn=(0,o["default"])('
'),this.$cn2=(0,o["default"])('
'),this.$cn.append(this.$cn2),this.$header=(0,o["default"])('
').append("
").concat(r.t('traitManager.empty'),"
")),this.$cn.append(this.$header),s.custom?a.__trgCustom({container:this.$cn2.get(0)}):(this.$cn2.append("
").concat(r.t('traitManager.label'),"
")),this.$cn2.append(a.render()));var l=t.Panels;null==(n=l.getPanel('views-container')?l.getPanel('views-container'):l.addPanel({id:'views-container'}))||n.set('appendContent',this.$cn.get(0)).trigger('change:appendContent'),this.target=t.getModel(),this.listenTo(this.target,'component:toggled',this.toggleTm)}this.toggleTm()}},toggleTm:function(){var t=this.sender;t&&t.get&&!t.get('active')||(1===this.target.getSelectedAll().length?(this.$cn2.show(),this.$header.hide()):(this.$cn2.hide(),this.$header.show()))},stop:function(){this.$cn2&&this.$cn2.hide(),this.$header&&this.$header.hide()}}},6979:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>r});var o=n(5706);const r={run:function(t,e,n){void 0===n&&(n={});var r=t.getModel(),a=r.get('clipboard'),s=t.getSelected();(null==a?void 0:a.length)&&s&&(t.getSelectedAll().forEach((function(e){var s,l,c,u,p=(null===(l=null===(s=e.delegate)||void 0===s?void 0:s.copy)||void 0===l?void 0:l.call(s,e))||e,d=p.collection;if(d){var f={at:p.index()+1,action:n.action||'paste-component'};u=(0,o.contains)(a,p)&&p.get('copyable')?d.add(p.clone(),f):i(t,a,p.parent(),f)}else{var h=null===(c=r.Pages.getSelected())||void 0===c?void 0:c.getMainComponent();f={at:(null==h?void 0:h.components().length)||0,action:n.action||'paste-component'};u=i(t,a,h,f)}(u=(0,o.isArray)(u)?u:[u]).forEach((function(e){return t.trigger('component:paste',e)}))})),s.emitUpdate())}};function i(t,e,n,o){var r=e.filter((function(t){return t.get('copyable')})).filter((function(e){return t.Components.canMove(n,e).result}));return n.components().add(r.map((function(t){return t.clone()})),o)}},4457:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>a});var o=n(5706),r=void 0&&(void 0).__spreadArray||function(t,e,n){if(n||2===arguments.length)for(var o,r=0,i=e.length;r{"use strict";n.r(e),n.d(e,{ConvertUnitsToPx:()=>o,default:()=>l});var o,r=n(2225),i=n(1166),a=void 0&&(void 0).__assign||function(){return a=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=0,O=['cl','cr'].indexOf(f)>=0,E=!p,j={};if(!S){var M=(null===(s=u.getBody())||void 0===s?void 0:s.offsetWidth)||0,D=n.w{"use strict";n.r(e),n.d(e,{default:()=>S});var o,r=n(5706),i=n(179),a=n(9156),s=void 0&&(void 0).__extends||(o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},o(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});const l=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return s(e,t),e.prototype.defaults=function(){return{command:'',attributes:{}}},e}(a.Kx);var c=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),u=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return c(e,t),e}(a.pM);const p=u;u.prototype.model=l;var d=n(2225),f=n(8242),h=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),v=void 0&&(void 0).__assign||function(){return v=Object.assign||function(t){for(var e,n=1,o=arguments.length;n").concat(l,"
"):'',"\n
").concat(r.getName(),"
");i.innerHTML=p?p(r):d}var f='px';a.display='block';var h=o.getTargetToElementFixed(t,i,{pos:e}).top,v=n.leftOff<0?-n.leftOff:0;a.top=h+f,a.left=v+f}else a.display='none'},showHighlighter:function(t){this.canvas.getHighlighter(t).style.opacity=''},initResize:function(t){var e,n=this,o=this.em,a=this.canvas,s=o.Editor,l=!(0,r.isElement)(t)&&(0,w.GW)(t)?t:o.getSelected(),c=null===(e=null==l?void 0:l.get)||void 0===e?void 0:e.call(l,'resizable'),u=i.F.Resize,p=a.hasCustomSpot(u);a.removeSpots({type:u});var f={component:l,hasCustomResize:p,resizable:c};l&&o.trigger(d.I.resizeInit,f);var h=f.resizable;if(l&&h){a.addSpot({type:u,component:l});var v=(0,r.isElement)(t)?t:l.getEl(),g=(0,x.isObject)(h)?h:{};if(p||!v||this.activeResizer)return;this.resizer=s.runCommand('resize',C(C({},g),{el:v,component:l,force:!0,afterStart:function(){_=!1,n.activeResizer=!0},afterEnd:function(){_=!0,n.activeResizer=!1}}))}else{if(p)return;s.stopCommand('resize'),this.resizer=null}},updateToolbar:function(t){var e=this.canvas,n=this.config.em,o=t===n?n.getSelected():t,r=e.getToolbarEl(),a=r.style,s=o.get('toolbar'),l=n.config.showToolbar,c=!e.hasCustomSpot(i.F.Select);if(o&&l&&s&&s.length&&c){if(a.display='',!this.toolbar){r.innerHTML='',this.toolbar=new p(s);var u=new b({collection:this.toolbar,em:n});r.appendChild(u.render().el)}this.toolbar.reset(s),a.top='-100px',a.left='0'}else a.display='none'},updateToolbarPos:function(t){var e='px',n=this.canvas.getToolbarEl().style;n.top="".concat(t.top).concat(e),n.left="".concat(t.left).concat(e),n.opacity=''},getCanvasPosition:function(){return this.canvas.getCanvasView().getPosition()},getBadge:function(t){return void 0===t&&(t={}),this.canvas.getBadgeEl(t.view)},onCanvasScroll:function(t){this.onFrameScroll(t),this.onContainerChange()},onFrameScroll:function(){this.updateTools(),this.canvas.refreshSpots()},onFrameResize:function(){this.canvas.refresh({all:!0})},updateTools:function(){this.updateLocalPos(),this.updateGlobalPos()},isCompSelected:function(t){return t&&'selected'===t.get('status')},updateToolsLocal:function(t){var e=this.em.getConfig(),n=t||this.getElHovered(),o=n.el,r=n.pos,a=n.view,s=n.component;if(o){var l=s.get('hoverable'),c=this.lastHovered!==o,u=c?{}:{posOnly:1},p=this.canvas.hasCustomSpot(i.F.Hover);c&&l&&(this.lastHovered=o,p?this.hideHighlighter(a):this.showHighlighter(a),this.showElementOffset(o,r,{view:a})),this.isCompSelected(s)&&(this.hideHighlighter(a),!e.showOffsetsSelected&&this.hideElementOffset(a));var d='px',f=this.toggleToolsEl(1,a),h=f.style,v=this.canvas.canvasRectOffset(o,r),g=v.top,y=v.left;!p&&this.updateBadge(o,r,C(C({},u),{view:a,topOff:g,leftOff:y})),h.top=g+d,h.left=y+d,h.width=r.width+d,h.height=r.height+d,this._trgToolUp('local',{component:s,el:f,top:g,left:y,width:r.width,height:r.height})}else this.lastHovered=0},_upToolbar:(0,r.debounce)((function(){this.updateToolsGlobal({force:1})}),0),_trgToolUp:function(t,e){void 0===e&&(e={}),this.em.trigger('canvas:tools:update',C({type:t},e))},updateToolsGlobal:function(t){void 0===t&&(t={});var e=this.getElSelected(),n=e.el,o=e.pos,r=e.component;if(!n)return this.toggleToolsEl(),void(this.lastSelected=0);var i=this.canvas;(this.lastSelected!==n||t.force)&&(this.lastSelected=n,this.updateToolbar(r));var a='px',s=this.toggleToolsEl(1),l=s.style,c=i.getTargetToElementFixed(n,i.getToolbarEl(),{pos:o}),u=c.canvasOffsetTop,p=c.canvasOffsetLeft;l.top=u+a,l.left=p+a,l.width=o.width+a,l.height=o.height+a,this.updateToolbarPos({top:c.top,left:c.left}),this._trgToolUp('global',{component:r,el:s,top:u,left:p,width:o.width,height:o.height})},updateAttached:(0,r.debounce)((function(){this.updateGlobalPos()}),0),onContainerChange:(0,r.debounce)((function(){this.em.refreshCanvas()}),150),getElementPos:function(t){return this.canvas.getCanvasView().getElementPos(t,{noScroll:!0})},hideBadge:function(){this.getBadge().style.display='none'},cleanPrevious:function(t){t&&t.set({status:'',state:''})},getContentWindow:function(){return this.canvas.getWindow()},run:function(t){(0,x.hasWin)()&&(this.editor=t&&t.get('Editor'),this.enable())},stop:function(t,e,n){if(void 0===n&&(n={}),(0,x.hasWin)()){var o=this.em,r=this.editor;this.onHovered(),this.stopSelectComponent(),!n.preserveSelected&&o.setSelected(),this.toggleToolsEl(),this.updateAttached.cancel(),r&&r.stopCommand('resize')}}}},1406:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>a});var o=n(7774),r=n(1447),i=n(8433);const a={startSelectPosition:function(t,e,n){void 0===n&&(n={}),this.isPointed=!1;var o=this.em.Utils,a=t[0].ownerDocument.body;o&&(this.sorter=new o.ComponentSorter({em:this.em,treeClass:r.A,containerContext:{container:a,containerSel:'*',itemSel:'*',pfx:this.ppfx,document:e,placeholderElement:this.canvas.getPlacerEl()},positionOptions:{windowMargin:1,canvasRelative:!0},dragBehavior:{dragDirection:i.A.BothDirections,nested:!0}})),n.onStart&&(this.sorter.eventHandlers.legacyOnStartSort=n.onStart),t&&t.length>0&&this.sorter.startSort(t.map((function(t){return{element:t}})))},getOffsetDim:function(){var t=this.offset(this.canvas.getFrameEl()),e=this.offset(this.canvas.getElement());return{top:t.top-e.top,left:t.left-e.left}},stopSelectPosition:function(){this.posTargetCollection=null,this.posIndex='after'==this.posMethod&&0!==this.cDim.length?this.posIndex+1:this.posIndex,this.sorter&&this.sorter.cancelDrag(),this.cDim&&(this.posIsLastEl=0!==this.cDim.length&&'after'==this.posMethod&&this.posIndex==this.cDim.length,this.posTargetEl=0===this.cDim.length?(0,o["default"])(this.outsideElem):!this.posIsLastEl&&this.cDim[this.posIndex]?(0,o["default"])(this.cDim[this.posIndex][5]).parent():(0,o["default"])(this.outsideElem),this.posTargetModel=this.posTargetEl.data('model'),this.posTargetCollection=this.posTargetEl.data('model-comp'))},enable:function(){this.startSelectPosition()},nearFloat:function(t,e,n){var o=t||0,r=e||'before',i=n.length,a=0!==i&&'after'==r&&o==i;return 0!==i&&(!a&&!n[o][4]||n[o-1]&&!n[o-1][4]||a&&!n[o-1][4])?1:0},run:function(){this.enable()},stop:function(){this.stopSelectPosition(),this.$wrapper.css('cursor',''),this.$wrapper.unbind()}}},9395:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>s});var o=n(5706),r=n(179),i=n(7774),a=void 0&&(void 0).__assign||function(){return a=Object.assign||function(t){for(var e,n=1,o=arguments.length;n")).get(0),A=(0,i["default"])("
")).get(0),j=v+E+'-el',M="".concat(v+P+'-el'," ").concat(v+P),D="".concat(j," ").concat(v+E);m=(0,i["default"])("
")).get(0),b=(0,i["default"])("
")).get(0),_=(0,i["default"])("
")).get(0),w=(0,i["default"])("
")).get(0),x=(0,i["default"])("
")).get(0),C=(0,i["default"])("
")).get(0),S=(0,i["default"])("
")).get(0),O=(0,i["default"])("
")).get(0),this['marginT'+c]=m,this['marginB'+c]=b,this['marginL'+c]=_,this['marginR'+c]=w,this['padT'+c]=x,this['padB'+c]=C,this['padL'+c]=S,this['padR'+c]=O,k.appendChild(m),k.appendChild(b),k.appendChild(_),k.appendChild(w),A.appendChild(x),A.appendChild(C),A.appendChild(S),A.appendChild(O),y.appendChild(k),y.appendChild(A),this[g]='1'}var L='px',I=parseFloat(h.marginLeft.replace(L,''))*p,N=parseFloat(h.marginRight.replace(L,''))*p,R=parseFloat(h.marginTop.replace(L,''))*p,V=parseFloat(h.marginBottom.replace(L,''))*p,F=m.style,H=b.style,U=_.style,z=w.style,B=x.style,W=C.style,$=S.style,q=O.style,G=parseFloat(f.left),K=parseFloat(h.width)*p+L;F.height=R+L,F.width=K,F.top=f.top-R+L,F.left=G+L,H.height=V+L,H.width=K,H.top=f.top+f.height+L,H.left=G+L;var Y=f.height+R+V+L,J=f.top-R+L;U.height=Y,U.width=I+L,U.top=J,U.left=G-I+L,z.height=Y,z.width=N+L,z.top=J,z.left=G+f.width+L;var X=parseFloat(h.paddingTop)*p;B.height=X+L;var Z=parseFloat(h.paddingBottom)*p;W.height=Z+L;var Q=f.height-Z-X+L,tt=f.top+X+L;$.height=Q,$.width=parseFloat(h.paddingLeft)*p+L,$.top=tt;var et=parseFloat(h.paddingRight)*p;q.height=Q,q.width=et+L,q.top=tt}}else t.stopCommand("".concat(this.id),n)},stop:function(t,e,n){void 0===n&&(n={});var o=(n||{}).state||'',r=this.getOffsetMethod(o),i=n.view;this.canvas[r](i).style.opacity=0}}},7285:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>i});var o=n(5706),r=n(1166);const i={init:function(){(0,o.bindAll)(this,'_onFramesChange')},run:function(t){this.toggleVis(t,!0)},stop:function(t){this.toggleVis(t,!1)},toggleVis:function(t,e){if(void 0===e&&(e=!0),!t.Commands.isActive('preview')){var n=t.Canvas,o=e?'on':'off';n.getModel()[o]('change:frames',this._onFramesChange),this.handleFrames(n.getFrames(),e)}},handleFrames:function(t,e){var n=this;t.forEach((function(t){var o;(null===(o=t.view)||void 0===o?void 0:o.loaded)&&n._upFrame(t,e),t.__ol||(t.on('loaded',(function(){return n._upFrame(t)})),t.__ol=!0)}))},_onFramesChange:function(t,e){this.handleFrames(e)},_upFrame:function(t,e){var n,o=this,i=o.ppfx,a=o.em,s=o.id,l=((0,r.isDef)(e)?e:a.Commands.isActive(s))?'add':'remove',c="".concat(i,"dashed");null===(n=t.view)||void 0===n||n.getBody().classList[l](c)}}},9156:(t,e,n)=>{"use strict";n.d(e,{Kx:()=>u,Ss:()=>d,e2:()=>c,lK:()=>f,pM:()=>p,x2:()=>r});var o,r,i=n(4193),a=n.n(i),s=void 0&&(void 0).__extends||(o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},o(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),l=void 0&&(void 0).__assign||function(){return l=Object.assign||function(t){for(var e,n=1,o=arguments.length;n{"use strict";var o,r;n.d(e,{I:()=>r,t:()=>o}),function(t){t["remove"]="component:remove",t["add"]="component:add",t["move"]="component:move"}(o||(o={})),function(t){t["add"]="component:add",t["remove"]="component:remove",t["removeBefore"]="component:remove:before",t["removed"]="component:removed",t["create"]="component:create",t["update"]="component:update",t["updateInside"]="component:update-inside",t["styleUpdate"]="component:styleUpdate",t["styleUpdateProperty"]="component:styleUpdate:",t["select"]="component:select",t["selectBefore"]="component:select:before",t["mount"]="component:mount",t["scriptMount"]="component:script:mount",t["scriptMountBefore"]="component:script:mount:before",t["scriptUnmount"]="component:script:unmount",t["render"]="component:render",t["input"]="component:input",t["resize"]="component:resize",t["resizeStart"]="component:resize:start",t["resizeMove"]="component:resize:move",t["resizeEnd"]="component:resize:end",t["resizeUpdate"]="component:resize:update",t["resizeInit"]="component:resize:init",t["symbolMainAdd"]="symbol:main:add",t["symbolMainUpdate"]="symbol:main:update",t["symbolMainUpdateDeep"]="symbol:main:update-deep",t["symbolMainRemove"]="symbol:main:remove",t["symbolMain"]="symbol:main",t["symbolInstanceAdd"]="symbol:instance:add",t["symbolInstanceRemove"]="symbol:instance:remove",t["symbolInstance"]="symbol:instance",t["symbol"]="symbol"}(r||(r={}))},8242:(t,e,n)=>{"use strict";n.d(e,{A:()=>l});var o,r=n(5706),i=n(9156),a=void 0&&(void 0).__extends||(o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},o(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),s=function(t){function e(e,n,o){void 0===e&&(e={}),void 0===o&&(o=!1);var r=t.call(this,e)||this;return r.itemsView='',r.itemType='type',r.reuseView=!1,r.config=n||e.config||{},o&&r.listenTo(r.collection,'add',r.addTo),r.items=[],r}return a(e,t),e.prototype.addTo=function(t){this.add(t)},e.prototype.itemViewNotFound=function(t){var e=this.config,n=this.ns,o=e.em,r="".concat(n?"[".concat(n,"]: "):'',"'").concat(t,"' type not found");o&&o.logWarning(r)},e.prototype.add=function(t,e){var n,o=this,i=o.config,a=o.reuseView,s=o.items,l=this.itemsView||{},c=e||null,u=this.itemView,p=t.get(this.itemType);l[p]?u=l[p]:!p||l[p]||(0,r.includes)(['button','checkbox','color','date','datetime-local','email','file','hidden','image','month','number','password','radio','range','reset','search','submit','tel','text','time','url','week'],p)||this.itemViewNotFound(p),n=t.view&&a?t.view:new u({model:t,config:i},i),s&&s.push(n);var d=n.render().el;c?c.appendChild(d):this.$el.append(d)},e.prototype.render=function(){var t=document.createDocumentFragment();return this.clearItems(),this.$el.empty(),this.collection.length&&this.collection.each((function(e){this.add(e,t)}),this),this.$el.append(t),this.onRender(),this},e.prototype.onRender=function(){},e.prototype.onRemoveBefore=function(t,e){},e.prototype.onRemove=function(t,e){},e.prototype.remove=function(e){void 0===e&&(e={});var n=this.items;return this.onRemoveBefore(n,e),this.clearItems(),t.prototype.remove.call(this),this.onRemove(n,e),this},e.prototype.clearItems=function(){this.items},e}(i.Ss);const l=s;s.prototype.itemView=''},9966:(t,e,n)=>{"use strict";n.d(e,{A:()=>s});var o=n(5706),r=n(6294),i=void 0&&(void 0).__assign||function(){return i=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=e&&t<=e+f||t<=e&&t>=e-f)},t.prototype.setGuideLock=function(t,e){var n=(0,o.isUndefined)(t.x)?'Y':'X',r="trg".concat(n);return null!==e?(t.active=!0,t.lock=e,this[r]=t):(delete t.active,delete t.lock,delete this[r]),t},t.prototype.stop=function(t,e){void 0===e&&(e={});var n=this.delta,r=!!e.cancel,i=r?0:n.x,a=r?0:n.y;this.toggleDrag(),this.move(i,a,!0);var s=this.opts.onEnd;(0,o.isFunction)(s)&&s(t,this,{cancelled:r})},t.prototype.keyHandle=function(t){(0,r.v$)(t)&&this.stop(t,{cancel:!0})},t.prototype.move=function(t,e,n){var r=this.el,i=this.opts,a=this.startPosition;if(a){var s=i.setPosition,l=a.x+t,c=a.y+e;this.position={x:l,y:c,end:n},(0,o.isFunction)(s)&&s(this.position),r&&(r.style.left="".concat(l,"px"),r.style.top="".concat(c,"px"))}},t.prototype.getContainerEl=function(){var t=this.opts.container;return t?[t]:this.getDocumentEl()},t.prototype.getWindowEl=function(){return this.getContainerEl().map((function(t){var e=t.ownerDocument||t;return e.defaultView||e.parentWindow}))},t.prototype.getDocumentEl=function(t){var e=this.opts.doc;if(t=t||this.el,!this.docs.length){var n=[document];t&&n.push(t.ownerDocument),e&&n.push(e),this.docs=n}return this.docs},t.prototype.getPointerPos=function(t){var e=this.opts.getPointerPosition,n=(0,r.G2)(t);return e?e(t):{x:n.clientX,y:n.clientY}},t.prototype.getStartPosition=function(){var t=this.el,e=this.opts.getPosition,n={x:0,y:0};return(0,o.isFunction)(e)?n=e():t&&(n={x:parseFloat(t.style.left),y:parseFloat(t.style.top)}),n},t.prototype.getScrollInfo=function(){var t=this.opts.doc,e=t&&t.body;return{y:e?e.scrollTop:0,x:e?e.scrollLeft:0}},t.prototype.detectAxisLock=function(t,e){var n=t,o=e,r=Math.abs(n),i=Math.abs(o);return o>=r||o<=-r?'x':n>i||n<-i?'y':void 0},t}()},7774:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>gt});var o='undefined'!=typeof document?document:null,r='undefined'!=typeof window?window:null,i=Array.prototype,a=i.filter,s=i.indexOf,l=i.map,c=i.push,u=i.reverse,p=i.slice,d=i.splice,f=/^#[\w-]*$/,h=/^\.[\w-]*$/,v=/<.+>/,g=/^\w+$/;function y(t,e){return void 0===e&&(e=o),h.test(t)?e.getElementsByClassName(t.slice(1)):g.test(t)?e.getElementsByTagName(t):e.querySelectorAll(t)}function m(t,e){if(void 0===e&&(e=o),t){if(t.__cash)return t;var n=t;if(E(t)){if(e.__cash&&(e=e[0]),!(n=f.test(t)?e.getElementById(t.slice(1)):v.test(t)?ft(t):y(t,e)))return}else if(P(t))return this.ready(t);(n.nodeType||n===r)&&(n=[n]),this.length=n.length;for(var i=0,a=this.length;i=0})):n.value=r}))},_.clone=function(){return this.map((function(t,e){return e.cloneNode(!0)}))},_.detach=function(){return this.each((function(t,e){e.parentNode&&e.parentNode.removeChild(e)}))};var ut,pt=/^\s*<(\w+)[^>]*>/,dt=/^\s*<(\w+)\s*\/?>(?:<\/\1>)?\s*$/;function ft(t){if(function(){if(!ut){var t=o.createElement('table'),e=o.createElement('tr');ut={'*':o.createElement('div'),tr:o.createElement('tbody'),td:e,th:e,thead:t,tbody:t,tfoot:t}}}(),!E(t))return[];if(dt.test(t))return[o.createElement(RegExp.$1)];var e=pt.test(t)&&RegExp.$1,n=ut[e]||ut['*'];return n.innerHTML=t,b(n.childNodes).detach().get()}function ht(t,e,n){if(void 0!==e){var o=E(e);!o&&e.length?S(e,(function(e){return ht(t,e,n)})):S(t,o?function(t){t.insertAdjacentHTML(n?'afterbegin':'beforeend',e)}:function(t,o){return function(t,e,n){n?t.insertBefore(e,t.childNodes[0]):t.appendChild(e)}(t,o?e.cloneNode(!0):e,n)})}}b.parseHTML=ft,_.empty=function(){var t=this[0];if(t)for(;t.firstChild;)t.removeChild(t.firstChild);return this},_.append=function(){var t=this;return S(arguments,(function(e){ht(t,e)})),this},_.appendTo=function(t){return ht(b(t),this),this},_.html=function(t){if(void 0===t)return this[0]&&this[0].innerHTML;var e=t.nodeType?t[0].outerHTML:t;return this.each((function(t,n){n.innerHTML=e}))},_.insertAfter=function(t){var e=this;return b(t).each((function(t,n){var o=n.parentNode;e.each((function(e,r){o.insertBefore(t?r.cloneNode(!0):r,n.nextSibling)}))})),this},_.after=function(){var t=this;return S(u.apply(arguments),(function(e){u.apply(b(e).slice()).insertAfter(t)})),this},_.insertBefore=function(t){var e=this;return b(t).each((function(t,n){var o=n.parentNode;e.each((function(e,r){o.insertBefore(t?r.cloneNode(!0):r,n)}))})),this},_.before=function(){var t=this;return S(arguments,(function(e){b(e).insertBefore(t)})),this},_.prepend=function(){var t=this;return S(arguments,(function(e){ht(t,e,!0)})),this},_.prependTo=function(t){return ht(b(t),u.apply(this.slice()),!0),this},_.remove=function(){return this.detach().off()},_.replaceWith=function(t){var e=this;return this.each((function(n,o){var r=o.parentNode;if(r){var i=n?b(t).clone():b(t);if(!i[0])return e.remove(),!1;r.replaceChild(i[0],o),b(i[0]).after(i.slice(1))}}))},_.replaceAll=function(t){return b(t).replaceWith(this),this},_.text=function(t){return void 0===t?this[0]?this[0].textContent:'':this.each((function(e,n){n.textContent=t}))};var vt=o&&o.documentElement;_.offset=function(){var t=this[0];if(t){var e=t.getBoundingClientRect();return{top:e.top+r.pageYOffset-vt.clientTop,left:e.left+r.pageXOffset-vt.clientLeft}}},_.offsetParent=function(){return b(this[0]&&this[0].offsetParent)},_.position=function(){var t=this[0];if(t)return{left:t.offsetLeft,top:t.offsetTop}},_.children=function(t){var e=[];return this.each((function(t,n){c.apply(e,n.children)})),e=b(L(e)),t?e.filter((function(e,n){return T(n,t)})):e},_.contents=function(){var t=[];return this.each((function(e,n){c.apply(t,'IFRAME'===n.tagName?[n.contentDocument]:n.childNodes)})),b(t.length&&L(t))},_.find=function(t){for(var e=[],n=0,o=this.length;n{"use strict";n.d(e,{AU:()=>L,BC:()=>g,C8:()=>C,Ch:()=>T,Ci:()=>k,D8:()=>s,G2:()=>P,GW:()=>x,GZ:()=>m,I6:()=>p,LJ:()=>j,Sc:()=>v,X6:()=>d,Xy:()=>S,YZ:()=>c,ZQ:()=>l,_I:()=>I,a_:()=>y,af:()=>_,bG:()=>h,cx:()=>u,ir:()=>w,kk:()=>M,on:()=>D,rp:()=>A,v$:()=>E,yL:()=>b,zN:()=>f});var o=n(5706),r=void 0&&(void 0).__spreadArray||function(t,e,n){if(n||2===arguments.length)for(var o,r=0,i=e.length;r=i?t.appendChild(e):t.insertBefore(e,r[a])},g=function(t,e){return v(t,e)},y=function(t,e,n){void 0===e&&(e={});var r=document.createElement(t);return e&&(0,o.each)(e,(function(t,e){return r.setAttribute(e,t)})),n&&((0,o.isString)(n)?r.innerHTML=n:r.appendChild(n)),r},m=function(t){return document.createTextNode(t)},b=function(t,e){var n,o=t.type;try{n=new window[e](o,t)}catch(t){(n=document.createEvent(e)).initEvent(o,!0,!0)}return n._parentEvent=t,0===o.indexOf('key')&&(n.keyCodeVal=t.keyCode,['keyCode','which'].forEach((function(t){Object.defineProperty(n,t,{get:function(){return this.keyCodeVal}})}))),n},_=function(t,e){void 0===e&&(e=[]),(Array.isArray(e)?e:[e]).forEach((function(e){var n=e[i]||'div',r=e[a]||{},s=document.createElement(n);(0,o.each)(r,(function(t,e){s.setAttribute(e,t)})),t.appendChild(s)}))},w=function(t){return(null==t?void 0:t.nodeType)===Node.TEXT_NODE},x=function(t){return t&&!w(t)&&!function(t){return(null==t?void 0:t.nodeType)===Node.COMMENT_NODE}(t)},C=function(t){var e,n={top:0,left:0,width:0,height:0};if(!t)return n;if(w(t)){var o=document.createRange();o.selectNode(t),e=o.getBoundingClientRect(),o.detach()}return e||(t.getBoundingClientRect?t.getBoundingClientRect():n)},S=function(t){var e=(null==t?void 0:t.ownerDocument)||document,n=e.documentElement,o=e.defaultView||window;return{x:(o.pageXOffset||n.scrollLeft||0)-(n.clientLeft||0),y:(o.pageYOffset||n.scrollTop||0)-(n.clientTop||0)}},O=function(t){return t.which||t.keyCode},T=function(t){return String.fromCharCode(O(t))},P=function(t){return t.touches&&t.touches[0]?t.touches[0]:t},E=function(t){return 27===O(t)},k=function(t){return 13===O(t)},A=function(t){return function(t){return t.ctrlKey}(t)||t.metaKey},j=function(t){if(!t)return'';var e=t.name,n=t.publicId,o=t.systemId,r=n?" PUBLIC \"".concat(n,"\""):'',i=!n&&o?" SYSTEM \"".concat(o,"\""):'';return"")},M=function(t){void 0===t&&(t={});var e=[];return(0,o.each)(t,(function(t,n){return e.push("".concat(n,"=\"").concat(t,"\""))})),e.join(' ')},D=function(t,e,n,r){var i=e.split(/\s+/),a=(0,o.isArray)(t)?t:[t];i.forEach((function(t){a.forEach((function(e){return null==e?void 0:e.addEventListener(t,n,r)}))}))},L=function(t,e,n,r){var i=e.split(/\s+/),a=(0,o.isArray)(t)?t:[t];i.forEach((function(t){a.forEach((function(e){return null==e?void 0:e.removeEventListener(t,n,r)}))}))},I=function(t){return t.replace(/-([a-zA-Z0-9])/g,(function(t,e){return e.toUpperCase()}))}},1166:(t,e,n)=>{"use strict";n.r(e),n.d(e,{appendStyles:()=>C,buildBase64UrlFromSvg:()=>K,camelCase:()=>P,capitalize:()=>H,createId:()=>G,deepMerge:()=>N,escape:()=>M,escapeAltQuoteAttrValue:()=>I,escapeAttrValue:()=>L,escapeNodeContent:()=>D,find:()=>j,get:()=>p,getComponentModel:()=>$,getComponentView:()=>W,getElement:()=>A,getGlobal:()=>m,getModel:()=>R,getUiClass:()=>x,getUnitFromValue:()=>O,getViewEl:()=>z,hasDnd:()=>k,hasWin:()=>y,isBultInMethod:()=>f,isComponent:()=>B,isDef:()=>g,isEmptyObj:()=>F,isObject:()=>V,isRule:()=>U,matches:()=>w,normalizeFloat:()=>E,normalizeKey:()=>h,serialize:()=>d,setViewEl:()=>q,shallowDiff:()=>S,stringToPath:()=>u,toLowerCase:()=>b,upFirst:()=>T,wait:()=>v});var o=n(5706),r=n(6294),i=void 0&&(void 0).__assign||function(){return i=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=0?a!==s&&(n[i]=s):n[i]=null}for(var i in e)e.hasOwnProperty(i)&&(0,o.isUndefined)(t[i])&&(n[i]=e[i]);return n},O=function(t){return t.replace(parseFloat(t),'')},T=function(t){return t[0].toUpperCase()+t.toLowerCase().slice(1)},P=function(t){return t.replace(/-./g,(function(t){return t[1].toUpperCase()}))},E=function(t,e,n){void 0===e&&(e=1),void 0===n&&(n=0);var o=0;if(isNaN(t))return n;if(t=parseFloat(t),Math.floor(t)!==t){var r=e.toString().split('.')[1];o=r?r.length:0}return o?parseFloat(t.toFixed(o)):t},k=function(t){return'draggable'in document.createElement('i')&&(!t||t.config.nativeDnD)},A=function(t){return(0,o.isElement)(t)||(0,r.ir)(t)?t:t&&t.getEl?t.getEl():void 0},j=function(t,e){var n=null;return t.some((function(o,r){return e(o,r,t)?(n=o,1):0})),n},M=function(t){return void 0===t&&(t=''),"".concat(t).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"').replace(/'/g,''').replace(/`/g,'`')},D=function(t){return void 0===t&&(t=''),"".concat(t).replace(/&/g,'&').replace(//g,'>')},L=function(t){return void 0===t&&(t=''),"".concat(t).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"')},I=function(t){return void 0===t&&(t=''),"".concat(t).replace(/&/g,'&').replace(//g,'>').replace(/'/g,''')},N=function(){for(var t=[],e=0;e{"use strict";n.d(e,{h:()=>a});var o,r=n(3178),i=void 0&&(void 0).__extends||(o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},o(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),a=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.displayCache=new Map,e}return i(e,t),e.prototype.getChildren=function(){return this.getDisplayedChildren()},e.prototype.getDisplayedChildren=function(){var t=this;return this.model.components().filter((function(e){return t.isChildDisplayed(e)})).map((function(e){return new t.constructor(e)}))},e.prototype.isChildDisplayed=function(t){if(this.displayCache.has(t))return this.displayCache.get(t);var e=function(t){return!!t&&('object'==typeof t&&t.nodeType===Node.ELEMENT_NODE&&'none'!==window.getComputedStyle(t).display&&t.offsetWidth>0&&t.offsetHeight>0)}(t.getEl());return this.displayCache.set(t,e),e},e.prototype.getParent=function(){var t=this.model.parent();return t?new this.constructor(t):null},e.prototype.addChildAt=function(t,e,n){var o,r,i,a,s,l,c,u;if(void 0===n&&(n={action:'add-component'}),(null===(r=null===(o=this.model)||void 0===o?void 0:o.isInstanceOf)||void 0===r?void 0:r.call(o,'text'))&&(null===(a=null===(i=null==t?void 0:t.model)||void 0===i?void 0:i.get)||void 0===a?void 0:a.call(i,'textable')))return null===(u=null===(c=null===(l=null===(s=this.model)||void 0===s?void 0:s.getView)||void 0===l?void 0:l.call(s))||void 0===c?void 0:c.insertComponent)||void 0===u?void 0:u.call(c,null==t?void 0:t.model,{action:n.action});var p=this.model.components().add(t.model,{at:this.getRealIndex(e),action:n.action});return new this.constructor(p)},e.prototype.removeChildAt=function(t,e){void 0===e&&(e={temporary:!1});var n=this.model.components().at(this.getRealIndex(t));n&&this.model.components().remove(n,e)},e.prototype.indexOfChild=function(t){return this.getDisplayIndex(t)},e.prototype.getDisplayIndex=function(t){var e=this.getDisplayedChildren();return e?e.findIndex((function(e){return e.model===t.model})):-1},e.prototype.getRealIndex=function(t){if(-1===t)return-1;for(var e=0,n=this.model.components(),o=0;o{"use strict";n.d(e,{A:()=>a});var o,r=n(6756),i=void 0&&(void 0).__extends||(o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},o(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});const a=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._dropAreaConfig={ratio:.8,minUndroppableDimension:1,maxUndroppableDimension:15},e}return i(e,t),Object.defineProperty(e.prototype,"view",{get:function(){var t,e;return null===(e=(t=this.model).getView)||void 0===e?void 0:e.call(t)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"element",{get:function(){var t,e;return null===(e=(t=this.model).getEl)||void 0===e?void 0:e.call(t)},enumerable:!1,configurable:!0}),e}(r.h)},3178:(t,e,n)=>{"use strict";n.d(e,{$:()=>o});var o=function(){function t(t,e){void 0===e&&(e={}),this._dropAreaConfig={ratio:1,minUndroppableDimension:0,maxUndroppableDimension:0},this._model=t,this._dragSource=e}return Object.defineProperty(t.prototype,"model",{get:function(){return this._model},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dragSource",{get:function(){return this._dragSource},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dropArea",{get:function(){var t,e;return this.getParent()?null===(e=this.nodeDimensions)||void 0===e?void 0:e.getDropArea(this._dropAreaConfig):null===(t=this.nodeDimensions)||void 0===t?void 0:t.clone()},enumerable:!1,configurable:!0}),t.prototype.isWithinDropBounds=function(t,e){return!!this.dropArea&&this.dropArea.isWithinBounds(t,e)},t.prototype.equals=function(t){return!!(null==t?void 0:t._model)&&this._model===t._model},t.prototype.adjustDimensions=function(t){var e,n;0===t.topDifference&&0===t.leftDifference||(null===(e=this.nodeDimensions)||void 0===e||e.adjustDimensions(t),null===(n=this.childrenDimensions)||void 0===n||n.forEach((function(e){return e.adjustDimensions(t)})))},t}()},8433:(t,e,n)=>{"use strict";var o;n.d(e,{A:()=>o}),function(t){t["Vertical"]="Vertical",t["Horizontal"]="Horizontal",t["BothDirections"]="BothDirections"}(o||(o={}))},585:(t,e,n)=>{var o={"./CanvasClear":9484,"./CanvasClear.ts":9484,"./CanvasMove":9516,"./CanvasMove.ts":9516,"./CommandAbstract":9946,"./CommandAbstract.ts":9946,"./ComponentDelete":7801,"./ComponentDelete.ts":7801,"./ComponentDrag":4864,"./ComponentDrag.ts":4864,"./ComponentEnter":6134,"./ComponentEnter.ts":6134,"./ComponentExit":914,"./ComponentExit.ts":914,"./ComponentNext":5547,"./ComponentNext.ts":5547,"./ComponentPrev":8655,"./ComponentPrev.ts":8655,"./ComponentStyleClear":7640,"./ComponentStyleClear.ts":7640,"./CopyComponent":5837,"./CopyComponent.ts":5837,"./ExportTemplate":6477,"./ExportTemplate.ts":6477,"./Fullscreen":1772,"./Fullscreen.ts":1772,"./MoveComponent":741,"./MoveComponent.ts":741,"./OpenAssets":2924,"./OpenAssets.ts":2924,"./OpenBlocks":3963,"./OpenBlocks.ts":3963,"./OpenLayers":1479,"./OpenLayers.ts":1479,"./OpenStyleManager":3473,"./OpenStyleManager.ts":3473,"./OpenTraitManager":5054,"./OpenTraitManager.ts":5054,"./PasteComponent":6979,"./PasteComponent.ts":6979,"./Preview":4457,"./Preview.ts":4457,"./Resize":5493,"./Resize.ts":5493,"./SelectComponent":9317,"./SelectComponent.ts":9317,"./SelectPosition":1406,"./SelectPosition.ts":1406,"./ShowOffset":9395,"./ShowOffset.ts":9395,"./SwitchVisibility":7285,"./SwitchVisibility.ts":7285};function r(t){var e=i(t);return n(e)}function i(t){if(!n.o(o,t)){var e=new Error("Cannot find module '"+t+"'");throw e.code='MODULE_NOT_FOUND',e}return o[t]}r.keys=function(){return Object.keys(o)},r.resolve=i,t.exports=r,r.id=585},5706:(t,e,n)=>{"use strict";n.r(e),n.d(e,{VERSION:()=>r,after:()=>Ie,all:()=>en,allKeys:()=>gt,any:()=>nn,assign:()=>It,before:()=>Ne,bind:()=>Ce,bindAll:()=>Te,chain:()=>be,chunk:()=>Fn,clone:()=>Ft,collect:()=>Ye,compact:()=>En,compose:()=>Le,constant:()=>Z,contains:()=>on,countBy:()=>gn,create:()=>Vt,debounce:()=>je,default:()=>Wn,defaults:()=>Nt,defer:()=>ke,delay:()=>Ee,detect:()=>qe,difference:()=>An,drop:()=>Tn,each:()=>Ke,escape:()=>se,every:()=>en,extend:()=>Lt,extendOwn:()=>It,filter:()=>Qe,find:()=>qe,findIndex:()=>He,findKey:()=>Ve,findLastIndex:()=>Ue,findWhere:()=>Ge,first:()=>On,flatten:()=>kn,foldl:()=>Xe,foldr:()=>Ze,forEach:()=>Ke,functions:()=>Mt,get:()=>Wt,groupBy:()=>hn,has:()=>$t,head:()=>On,identity:()=>qt,include:()=>on,includes:()=>on,indexBy:()=>vn,indexOf:()=>We,initial:()=>Sn,inject:()=>Xe,intersection:()=>Ln,invert:()=>jt,invoke:()=>rn,isArguments:()=>Y,isArray:()=>q,isArrayBuffer:()=>R,isBoolean:()=>E,isDataView:()=>$,isDate:()=>D,isElement:()=>k,isEmpty:()=>lt,isEqual:()=>vt,isError:()=>I,isFinite:()=>J,isFunction:()=>H,isMap:()=>Ot,isMatch:()=>ct,isNaN:()=>X,isNull:()=>T,isNumber:()=>M,isObject:()=>O,isRegExp:()=>L,isSet:()=>Pt,isString:()=>j,isSymbol:()=>N,isTypedArray:()=>rt,isUndefined:()=>P,isWeakMap:()=>Tt,isWeakSet:()=>Et,iteratee:()=>Xt,keys:()=>st,last:()=>Pn,lastIndexOf:()=>$e,map:()=>Ye,mapObject:()=>Qt,matcher:()=>Gt,matches:()=>Gt,max:()=>ln,memoize:()=>Pe,methods:()=>Mt,min:()=>cn,mixin:()=>Un,negate:()=>De,noop:()=>te,now:()=>re,object:()=>Rn,omit:()=>Cn,once:()=>Re,pairs:()=>At,partial:()=>xe,partition:()=>yn,pick:()=>xn,pluck:()=>an,property:()=>Kt,propertyOf:()=>ee,random:()=>oe,range:()=>Vn,reduce:()=>Xe,reduceRight:()=>Ze,reject:()=>tn,rest:()=>Tn,restArguments:()=>S,result:()=>ge,sample:()=>un,select:()=>Qe,shuffle:()=>pn,size:()=>_n,some:()=>nn,sortBy:()=>dn,sortedIndex:()=>ze,tail:()=>Tn,take:()=>On,tap:()=>Ht,template:()=>ve,templateSettings:()=>ce,throttle:()=>Ae,times:()=>ne,toArray:()=>bn,toPath:()=>Ut,transpose:()=>In,unescape:()=>le,union:()=>Dn,uniq:()=>Mn,unique:()=>Mn,uniqueId:()=>me,unzip:()=>In,values:()=>kt,where:()=>sn,without:()=>jn,wrap:()=>Me,zip:()=>Nn});var o={};n.r(o),n.d(o,{VERSION:()=>r,after:()=>Ie,all:()=>en,allKeys:()=>gt,any:()=>nn,assign:()=>It,before:()=>Ne,bind:()=>Ce,bindAll:()=>Te,chain:()=>be,chunk:()=>Fn,clone:()=>Ft,collect:()=>Ye,compact:()=>En,compose:()=>Le,constant:()=>Z,contains:()=>on,countBy:()=>gn,create:()=>Vt,debounce:()=>je,default:()=>zn,defaults:()=>Nt,defer:()=>ke,delay:()=>Ee,detect:()=>qe,difference:()=>An,drop:()=>Tn,each:()=>Ke,escape:()=>se,every:()=>en,extend:()=>Lt,extendOwn:()=>It,filter:()=>Qe,find:()=>qe,findIndex:()=>He,findKey:()=>Ve,findLastIndex:()=>Ue,findWhere:()=>Ge,first:()=>On,flatten:()=>kn,foldl:()=>Xe,foldr:()=>Ze,forEach:()=>Ke,functions:()=>Mt,get:()=>Wt,groupBy:()=>hn,has:()=>$t,head:()=>On,identity:()=>qt,include:()=>on,includes:()=>on,indexBy:()=>vn,indexOf:()=>We,initial:()=>Sn,inject:()=>Xe,intersection:()=>Ln,invert:()=>jt,invoke:()=>rn,isArguments:()=>Y,isArray:()=>q,isArrayBuffer:()=>R,isBoolean:()=>E,isDataView:()=>$,isDate:()=>D,isElement:()=>k,isEmpty:()=>lt,isEqual:()=>vt,isError:()=>I,isFinite:()=>J,isFunction:()=>H,isMap:()=>Ot,isMatch:()=>ct,isNaN:()=>X,isNull:()=>T,isNumber:()=>M,isObject:()=>O,isRegExp:()=>L,isSet:()=>Pt,isString:()=>j,isSymbol:()=>N,isTypedArray:()=>rt,isUndefined:()=>P,isWeakMap:()=>Tt,isWeakSet:()=>Et,iteratee:()=>Xt,keys:()=>st,last:()=>Pn,lastIndexOf:()=>$e,map:()=>Ye,mapObject:()=>Qt,matcher:()=>Gt,matches:()=>Gt,max:()=>ln,memoize:()=>Pe,methods:()=>Mt,min:()=>cn,mixin:()=>Un,negate:()=>De,noop:()=>te,now:()=>re,object:()=>Rn,omit:()=>Cn,once:()=>Re,pairs:()=>At,partial:()=>xe,partition:()=>yn,pick:()=>xn,pluck:()=>an,property:()=>Kt,propertyOf:()=>ee,random:()=>oe,range:()=>Vn,reduce:()=>Xe,reduceRight:()=>Ze,reject:()=>tn,rest:()=>Tn,restArguments:()=>S,result:()=>ge,sample:()=>un,select:()=>Qe,shuffle:()=>pn,size:()=>_n,some:()=>nn,sortBy:()=>dn,sortedIndex:()=>ze,tail:()=>Tn,take:()=>On,tap:()=>Ht,template:()=>ve,templateSettings:()=>ce,throttle:()=>Ae,times:()=>ne,toArray:()=>bn,toPath:()=>Ut,transpose:()=>In,unescape:()=>le,union:()=>Dn,uniq:()=>Mn,unique:()=>Mn,uniqueId:()=>me,unzip:()=>In,values:()=>kt,where:()=>sn,without:()=>jn,wrap:()=>Me,zip:()=>Nn});var r='1.13.1',i='object'==typeof self&&self.self===self&&self||'object'==typeof global&&global.global===global&&global||Function('return this')()||{},a=Array.prototype,s=Object.prototype,l='undefined'!=typeof Symbol?Symbol.prototype:null,c=a.push,u=a.slice,p=s.toString,d=s.hasOwnProperty,f='undefined'!=typeof ArrayBuffer,h='undefined'!=typeof DataView,v=Array.isArray,g=Object.keys,y=Object.create,m=f&&ArrayBuffer.isView,b=isNaN,_=isFinite,w=!{toString:null}.propertyIsEnumerable('toString'),x=['valueOf','isPrototypeOf','toString','propertyIsEnumerable','hasOwnProperty','toLocaleString'],C=Math.pow(2,53)-1;function S(t,e){return e=null==e?t.length-1:+e,function(){for(var n=Math.max(arguments.length-e,0),o=Array(n),r=0;r=0&&n<=C}}function tt(t){return function(e){return null==e?void 0:e[t]}}const et=tt('byteLength'),nt=Q(et);var ot=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;const rt=f?function(t){return m?m(t)&&!$(t):nt(t)&&ot.test(p.call(t))}:Z(!1),it=tt('length');function at(t,e){e=function(t){for(var e={},n=t.length,o=0;o':'>','"':'"',"'":''','`':'`'},se=ie(ae),le=ie(jt(ae)),ce=ut.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var ue=/(.)^/,pe={"'":"'",'\\':'\\','\r':'r','\n':'n','\u2028':'u2028','\u2029':'u2029'},de=/\\|'|\r|\n|\u2028|\u2029/g;function fe(t){return'\\'+pe[t]}var he=/^\s*(\w|\$)+\s*$/;function ve(t,e,n){!e&&n&&(e=n),e=Nt({},e,ut.templateSettings);var o=RegExp([(e.escape||ue).source,(e.interpolate||ue).source,(e.evaluate||ue).source].join('|')+'|$','g'),r=0,i="__p+='";t.replace(o,(function(e,n,o,a,s){return i+=t.slice(r,s).replace(de,fe),r=s+e.length,n?i+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'":o?i+="'+\n((__t=("+o+"))==null?'':__t)+\n'":a&&(i+="';\n"+a+"\n__p+='"),e})),i+="';\n";var a,s=e.variable;if(s){if(!he.test(s))throw new Error('variable is not a bare identifier: '+s)}else i='with(obj||{}){\n'+i+'}\n',s='obj';i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+'return __p;\n';try{a=new Function(s,'_',i)}catch(t){throw t.source=i,t}var l=function(t){return a.call(this,t,ut)};return l.source='function('+s+'){\n'+i+'}',l}function ge(t,e,n){var o=(e=zt(e)).length;if(!o)return H(n)?n.call(t):n;for(var r=0;r1)Oe(s,e-1,n,o),r=o.length;else for(var l=0,c=s.length;le?(o&&(clearTimeout(o),o=null),s=c,a=t.apply(r,i),o||(r=i=null)):o||!1===n.trailing||(o=setTimeout(l,u)),a};return c.cancel=function(){clearTimeout(o),s=0,o=r=i=null},c}function je(t,e,n){var o,r,i,a,s,l=function(){var c=re()-r;e>c?o=setTimeout(l,e-c):(o=null,n||(a=t.apply(s,i)),o||(i=s=null))},c=S((function(c){return s=this,i=c,r=re(),o||(o=setTimeout(l,e),n&&(a=t.apply(s,i))),a}));return c.cancel=function(){clearTimeout(o),o=i=s=null},c}function Me(t,e){return xe(e,t)}function De(t){return function(){return!t.apply(this,arguments)}}function Le(){var t=arguments,e=t.length-1;return function(){for(var n=e,o=t[e].apply(this,arguments);n--;)o=t[n].call(this,o);return o}}function Ie(t,e){return function(){if(--t<1)return e.apply(this,arguments)}}function Ne(t,e){var n;return function(){return--t>0&&(n=e.apply(this,arguments)),t<=1&&(e=null),n}}const Re=xe(Ne,2);function Ve(t,e,n){e=Zt(e,n);for(var o,r=st(t),i=0,a=r.length;i0?0:r-1;i>=0&&i0?a=i>=0?i:Math.max(i+s,a):s=i>=0?Math.min(i+1,s):i+s+1;else if(n&&i&&s)return o[i=n(o,r)]===r?i:-1;if(r!=r)return(i=e(u.call(o,a,s),X))>=0?i+a:-1;for(i=t>0?a:s-1;i>=0&&i=3;return function(e,n,o,r){var i=!Se(e)&&st(e),a=(i||e).length,s=t>0?0:a-1;for(r||(o=e[i?i[s]:s],s+=t);s>=0&&s=0}const rn=S((function(t,e,n){var o,r;return H(e)?r=e:(e=zt(e),o=e.slice(0,-1),e=e[e.length-1]),Ye(t,(function(t){var i=r;if(!i){if(o&&o.length&&(t=Bt(t,o)),null==t)return;i=t[e]}return null==i?i:i.apply(t,n)}))}));function an(t,e){return Ye(t,Kt(e))}function sn(t,e){return Qe(t,Gt(e))}function ln(t,e,n){var o,r,i=-1/0,a=-1/0;if(null==e||'number'==typeof e&&'object'!=typeof t[0]&&null!=t)for(var s=0,l=(t=Se(t)?t:kt(t)).length;si&&(i=o);else e=Zt(e,n),Ke(t,(function(t,n,o){((r=e(t,n,o))>a||r===-1/0&&i===-1/0)&&(i=t,a=r)}));return i}function cn(t,e,n){var o,r,i=1/0,a=1/0;if(null==e||'number'==typeof e&&'object'!=typeof t[0]&&null!=t)for(var s=0,l=(t=Se(t)?t:kt(t)).length;so||void 0===n)return 1;if(n1&&(o=Yt(o,e[1])),e=gt(t)):(o=wn,e=Oe(e,!1,!1),t=Object(t));for(var r=0,i=e.length;r1&&(n=e[1])):(e=Ye(Oe(e,!1,!1),String),o=function(t,n){return!on(e,n)}),xn(t,o,n)}));function Sn(t,e,n){return u.call(t,0,Math.max(0,t.length-(null==e||n?1:e)))}function On(t,e,n){return null==t||t.length<1?null==e||n?void 0:[]:null==e||n?t[0]:Sn(t,t.length-e)}function Tn(t,e,n){return u.call(t,null==e||n?1:e)}function Pn(t,e,n){return null==t||t.length<1?null==e||n?void 0:[]:null==e||n?t[t.length-1]:Tn(t,Math.max(0,t.length-e))}function En(t){return Qe(t,Boolean)}function kn(t,e){return Oe(t,e,!1)}const An=S((function(t,e){return e=Oe(e,!0,!0),Qe(t,(function(t){return!on(e,t)}))})),jn=S((function(t,e){return An(t,e)}));function Mn(t,e,n,o){E(e)||(o=n,n=e,e=!1),null!=n&&(n=Zt(n,o));for(var r=[],i=[],a=0,s=it(t);a{var e=t&&t.__esModule?()=>t['default']:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var o in e)n.o(e,o)&&!n.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:e[o]})},n.g=function(){if('object'==typeof globalThis)return globalThis;try{return this||new Function('return this')()}catch(t){if('object'==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{'undefined'!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:'Module'}),Object.defineProperty(t,'__esModule',{value:!0})};var o={};return(()=>{"use strict";n.d(o,{default:()=>sm});var t=n(5706),e=n(1166);function r(t){for(var n=[],o=1;o',move:'',plus:'',caret:'',delete:'',copy:'',arrowUp:'',chevron:'',eye:'',eyeOff:''},i18n:{},undoManager:{},assetManager:{},canvas:{},layerManager:{},storageManager:{},richTextEditor:{},domComponents:{},modal:{},codeManager:{},panels:{},commands:{},cssComposer:{},selectorManager:{},deviceManager:{},styleManager:{},blockManager:{},traitManager:{},textViewCode:'Code',keepUnusedStyles:!1,customUI:!1,telemetry:!0}};var a=n(4193),s=n.n(a),l=n(7774);var c,u=n(9156),p=void 0&&(void 0).__extends||(c=function(t,e){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},c(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}c(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),d=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return p(e,t),e}(u.Kx);const f=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return p(n,e),n.prototype.getByComponent=function(t){var e=this;return this.filter((function(n){return e.getComponent(n)===t}))[0]},n.prototype.addComponent=function(e,n){var o=this,r=((0,t.isArray)(e)?e:[e]).filter((function(t){return!o.hasComponent(t)})).map((function(t){return new d({component:t})}))[0];return this.push(r,n)},n.prototype.getComponent=function(t){return t.get('component')},n.prototype.hasComponent=function(t){var e=this.getByComponent(t);return e&&this.contains(e)},n.prototype.lastComponent=function(){var t=this.last();return t?this.getComponent(t):void 0},n.prototype.allComponents=function(){var t=this;return this.map((function(e){return t.getComponent(e)})).filter((function(t){return t}))},n.prototype.removeComponent=function(e,n){var o=this,r=((0,t.isArray)(e)?e:[e]).map((function(t){return o.getByComponent(t)}));return this.remove(r,n)},n}(u.pM);var h=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),v=void 0&&(void 0).__assign||function(){return v=Object.assign||function(t){for(var e,n=1,o=arguments.length;n',frameStyle:"\n body { background-color: #fff }\n * ::-webkit-scrollbar-track { background: rgba(0, 0, 0, 0.1) }\n * ::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.2) }\n * ::-webkit-scrollbar { width: 10px }\n ",notTextable:['button','a','input[type=checkbox]','input[type=radio]'],allowExternalDrop:!0}};var w,x=n(7058);!function(t){t["add"]="device:add",t["addBefore"]="device:add:before",t["remove"]="device:remove",t["removeBefore"]="device:remove:before",t["select"]="device:select",t["selectBefore"]="device:select:before",t["update"]="device:update",t["all"]="device"}(w||(w={}));const C=w;var S;!function(t){t["add"]="page:add",t["addBefore"]="page:add:before",t["remove"]="page:remove",t["removeBefore"]="page:remove:before",t["select"]="page:select",t["selectBefore"]="page:select:before",t["update"]="page:update",t["all"]="page"}(S||(S={}));const O=S;var T=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),P=function(e){function n(t,n,o){return e.call(this,n,{module:t,modelConstructor:o})||this}return T(n,e),n.prototype.add=function(n,o){var r,i=this,a=(0,t.isArray)(n)?n:(0,t.isUndefined)(n)?void 0:[n];return a=null!==(r=null==a?void 0:a.map((function(t){return t instanceof i.newModel?t:new i.newModel(i.module,t)})))&&void 0!==r?r:[void 0],e.prototype.add.call(this,(0,t.isArray)(n)?a:a[0],o)},n.prototype.preinitialize=function(t,e){this.newModel=e.modelConstructor,this.module=e.module},n}(u.pM);const E=P;var k;!function(t){t["dragEnter"]="canvas:dragenter",t["dragOver"]="canvas:dragover",t["dragEnd"]="canvas:dragend",t["dragData"]="canvas:dragdata",t["drop"]="canvas:drop",t["spot"]="canvas:spot",t["spotAdd"]="canvas:spot:add",t["spotUpdate"]="canvas:spot:update",t["spotRemove"]="canvas:spot:remove",t["coords"]="canvas:coords",t["zoom"]="canvas:zoom",t["pointer"]="canvas:pointer",t["refresh"]="canvas:refresh",t["frameLoad"]="canvas:frame:load",t["frameLoadHead"]="canvas:frame:load:head",t["frameLoadBody"]="canvas:frame:load:body",t["frameUnload"]="canvas:frame:unload"}(k||(k={}));const A=k;var j=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),M=void 0&&(void 0).__assign||function(){return M=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=0&&this.head.splice(r,1)},o.prototype.addLink=function(t){var e='link';!this.getHeadByAttr('href',t,e)&&this.addHeadItem({tag:e,attributes:{href:t,rel:'stylesheet'}})},o.prototype.removeLink=function(t){this.removeHeadByAttr('href',t,'link')},o.prototype.addScript=function(t){var e='script';!this.getHeadByAttr('src',t,e)&&this.addHeadItem({tag:e,attributes:{src:t}})},o.prototype.removeScript=function(t){this.removeHeadByAttr('src',t,'script')},o.prototype.getPage=function(){var t;return null===(t=this.collection)||void 0===t?void 0:t.page},o.prototype._emitUpdated=function(t){void 0===t&&(t={}),this.em.trigger('frame:updated',M({frame:this},t))},o.prototype._emitUnload=function(){this._emitWithEditor(A.frameUnload,{frame:this})},o.prototype._emitWithEditor=function(t,e){[this.em,this].forEach((function(n){return null==n?void 0:n.trigger(t,e)}))},o.prototype.hasAutoHeight=function(){return!('auto'!==this.attributes.height&&!this.config.infiniteCanvas)},o.prototype.toJSON=function(e){void 0===e&&(e={});var n=x.A.prototype.toJSON.call(this,e),o=(0,t.result)(this,'defaults');return e.fromUndo&&delete n.component,delete n.styles,delete n.changesCount,n[L]&&delete n.width,n[I]&&delete n.height,n.refFrame&&(n.refFrame=n.refFrame.id,delete n.component),(0,t.forEach)(n,(function(t,e){0===e.indexOf('_')&&delete n[e]})),(0,t.forEach)(o,(function(t,e){n[e]===t&&delete n[e]})),(0,t.forEach)(['attributes','head'],(function(e){(0,t.isEmpty)(n[e])&&delete n[e]})),n},o}(x.A);const V=R;var F=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}();const H=function(e){function n(n,o){void 0===o&&(o=[]);var r=e.call(this,n,o,V)||this;return r.loadedItems=0,r.itemsToLoad=0,(0,t.bindAll)(r,'itemLoaded'),r.on('add',r.onAdd),r.on('reset',r.onReset),r.on('remove',r.onRemove),r.forEach((function(t){return r.onAdd(t)})),r}return F(n,e),n.prototype.onAdd=function(t){this.module.framesById[t.id]=t},n.prototype.onReset=function(t,e){var n=this;((null==e?void 0:e.previousModels)||[]).map((function(t){return n.onRemove(t)}))},n.prototype.onRemove=function(t){t.onRemove(),delete this.module.framesById[t.id]},n.prototype.initRefs=function(){this.forEach((function(t){return t.initRefs()}))},n.prototype.itemLoaded=function(){this.loadedItems++,this.loadedItems>=this.itemsToLoad&&(this.trigger('loaded:all'),this.listenToLoadItems(!1))},n.prototype.listenToLoad=function(){this.loadedItems=0,this.itemsToLoad=this.length,this.listenToLoadItems(!0)},n.prototype.listenToLoadItems=function(t){var e=this;this.forEach((function(n){return n[t?'on':'off']('loaded',e.itemLoaded)}))},n}(E);var U=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),z=function(t){function e(e){var n=this,o=e.em,r=e.config,i=r.scripts,a=r.styles;return(n=t.call(this,e,{scripts:i,styles:a})||this).set('frames',new H(e)),n.on('change:zoom',n.onZoomChange),n.on('change:x change:y',n.onCoordsChange),n.on('change:pointer change:pointerScreen',n.onPointerChange),n.listenTo(o,"change:device ".concat(C.update),n.updateDevice),n.listenTo(o,O.select,n._pageUpdated),n}return U(e,t),e.prototype.defaults=function(){return{frame:'',frames:[],rulers:!1,zoom:100,x:0,y:0,scripts:[],styles:[],pointer:u.lK,pointerScreen:u.lK}},Object.defineProperty(e.prototype,"frames",{get:function(){return this.get('frames')},enumerable:!1,configurable:!0}),e.prototype.init=function(){var t=this.em.Pages._initPage();this.set('frames',t.getFrames()),this.updateDevice({frame:t.getMainFrame()})},e.prototype._pageUpdated=function(t,e){var n=this.em;n.setSelected(),n.get('readyCanvas')&&n.stopDefault(),null==e||e.getFrames().map((function(t){t.disable(),t._emitUnload()})),this.set('frames',t.getFrames()),this.updateDevice({frame:t.getMainFrame()})},e.prototype.updateDevice=function(t){void 0===t&&(t={});var e=this.em,n=e.getDeviceModel(),o=t.frame||e.getCurrentFrameModel();if(o&&n){var r=n.attributes,i=r.width,a=r.height,s=r.minHeight;o.set({width:i,height:a,minHeight:s},{noUndo:1})}},e.prototype.onZoomChange=function(t,e,n){var o=this.em,r=this.module;this.get('zoom')<1&&this.set('zoom',1),o.trigger(r.events.zoom,{options:n})},e.prototype.onCoordsChange=function(){var t=this.em,e=this.module;t.trigger(e.events.coords)},e.prototype.onPointerChange=function(){var t=this.em,e=this.module;t.trigger(e.events.pointer)},e.prototype.getPointerCoords=function(t){void 0===t&&(t=u.x2.World);var e=this.attributes,n=e.pointer,o=e.pointerScreen;return t===u.x2.World?n:o},e}(x.A);const B=z;var W=n(179),$=n(2225),q=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),G=function(e){function n(n,o){void 0===o&&(o=[]);var r=e.call(this,n,o,W.A)||this;r.on('add',r.onAdd),r.on('change',r.onChange),r.on('remove',r.onRemove);var i=r.em;r.refreshDbn=(0,t.debounce)((function(){return r.refresh()}),0);var a="".concat($.I.resize," styleable:change ").concat($.I.input," ").concat($.I.update," frame:updated undo redo");return r.listenTo(i,a,(function(){return r.refreshDbn()})),r}return q(n,e),Object.defineProperty(n.prototype,"em",{get:function(){return this.module.em},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"events",{get:function(){return this.module.events},enumerable:!1,configurable:!0}),n.prototype.refresh=function(){var t=this.em,e=this.events;t.trigger(e.spot)},n.prototype.onAdd=function(t){this.__trgEvent(this.events.spotAdd,{spot:t})},n.prototype.onChange=function(t){this.__trgEvent(this.events.spotUpdate,{spot:t})},n.prototype.onRemove=function(t){this.__trgEvent(this.events.spotRemove,{spot:t})},n.prototype.__trgEvent=function(t,e){this.module.em.trigger(t,e),this.refreshDbn()},n}(E);const K=G;var Y=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),J=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Y(e,t),Object.defineProperty(e.prototype,"pfx",{get:function(){return this.ppfx+this.config.stylePrefix||''},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ppfx",{get:function(){return this.em.config.stylePrefix||''},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"module",{get:function(){var t,e;return null!==(e=null===(t=this.model)||void 0===t?void 0:t.module)&&void 0!==e?e:this.collection.module},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"em",{get:function(){return this.module.em},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"config",{get:function(){return this.module.config},enumerable:!1,configurable:!0}),e.prototype.preinitialize=function(t){this.className=''},e}(u.Ss);const X=J;var Z=n(6294),Q=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}();const tt=function(t){function e(e,n){void 0===e&&(e={}),void 0===n&&(n=!1);var o=t.call(this,e)||this;return o.itemsView='',o.itemType='type',o.reuseView=!1,o.viewCollection=[],n&&o.listenTo(o.collection,'add',o.addTo),o}return Q(e,t),e.prototype.addTo=function(t){this.add(t)},e.prototype.itemViewNotFound=function(t){},e.prototype.add=function(t,e){var n,o=this.reuseView,r=this.viewCollection,i=e||null,a=t.get(this.itemType);n=t.view&&o?t.view:this.renderView(t,a),r.push(n);var s=n.render().el;i?i.appendChild(s):this.$el.append(s)},e.prototype.render=function(){var t=this,e=document.createDocumentFragment();return this.clearItems(),this.$el.empty(),this.collection.length&&this.collection.each((function(n){return t.add(n,e)})),this.$el.append(e),this.onRender(),this},e.prototype.onRender=function(){},e.prototype.onRemoveBefore=function(t,e){},e.prototype.onRemove=function(t,e){},e.prototype.remove=function(t){void 0===t&&(t={});var e=this.viewCollection;return this.onRemoveBefore(e,t),this.clearItems(),u.Ss.prototype.remove.apply(this,t),this.onRemove(e,t),this},e.prototype.clearItems=function(){this.viewCollection},e}(X);var et;!function(t){t["mount"]="css:mount",t["mountBefore"]="css:mount:before"}(et||(et={}));var nt=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),ot=function(t){function e(e){void 0===e&&(e={});var n=t.call(this,e)||this;n.config=e.config||{};var o=n.model;return n.listenTo(o,'change',n.render),n.listenTo(o,'destroy remove',n.remove),n.listenTo(o.get('selectors'),'change',n.render),o.setView(n),n}return nt(e,t),Object.defineProperty(e.prototype,"frameView",{get:function(){return this.config.frameView},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"em",{get:function(){return this.model.em},enumerable:!1,configurable:!0}),e.prototype.remove=function(){return t.prototype.remove.call(this),this.model.removeView(this),this},e.prototype.updateStyles=function(){this.render()},e.prototype.tagName=function(){return'style'},e.prototype.render=function(){var t=this,e=t.model,n=t.el,o=t.em,r=e.get('important'),i=e.toCSS({important:r}),a={rule:e,ruleView:this,css:i};return null==o||o.trigger(et.mountBefore,a),n.innerHTML=a.css,null==o||o.trigger(et.mount,a),this},e}(u.Ss);const rt=ot;var it=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}();const at=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return it(e,t),e.prototype._createElement=function(){return document.createTextNode('')},e.prototype.render=function(){var t=this.model,e=t.get('important');return this.el.textContent=t.getDeclaration({important:e}),this},e}(rt);var st=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),lt=function(t,e){return"".concat(t).concat(e?"-".concat(parseFloat(e)):'')},ct=function(e){function n(n){var o=e.call(this,n)||this;(0,t.bindAll)(o,'sortRules');var r=n.config||{};o.atRules={},o.config=r,o.em=r.em,o.pfx=r.stylePrefix||'',o.className=o.pfx+'rules';var i=o.collection;return o.listenTo(i,'add',o.addTo),o.listenTo(i,'reset',o.render),o}return st(n,e),n.prototype.addTo=function(t){this.addToCollection(t)},n.prototype.addToCollection=function(t,e){if(this.renderStarted){var n,o,r=e||null,i={model:t,config:this.config};if('keyframes'===t.get('atRuleType')){var a=t.getAtRule(),s=this.atRules[a];if(!s){var l=document.createElement('style');s=document.createTextNode(''),l.appendChild(document.createTextNode("".concat(a,"{"))),l.appendChild(s),l.appendChild(document.createTextNode('}')),this.atRules[a]=s,n=l}o=new at(i),s.appendData(o.render().el.textContent)}else n=(o=new rt(i)).render().el;var c=this.className,u=t.get('mediaText'),p=lt(c),d=p;if(u&&(d=lt(c,this.getMediaWidth(u))),n){var f=r||this.el,h=void 0;try{h=f.querySelector("#".concat(d))}catch(t){}h||(h=f.querySelector("#".concat(p))),null==h||h.appendChild(n)}return n}},n.prototype.getMediaWidth=function(t){return t&&t.replace("(".concat(this.em.getConfig().mediaCondition,": "),'').replace(')','')},n.prototype.sortRules=function(t,e){var n=-1!==(this.em.getConfig().mediaCondition||'').indexOf('min-width');return n?(n?t:e)-(n?e:t):0},n.prototype.render=function(){var t=this;this.renderStarted=!0,this.atRules={};var e=this,n=e.em,o=e.$el,r=e.collection,i=this.className,a=document.createDocumentFragment();o.empty();var s=n.Devices.getAll().pluck('priority').sort(this.sortRules);return s.every((function(t){return t}))&&s.unshift(0),s.forEach((function(t){return a.appendChild((0,Z.a_)('div',{id:lt(i,t)}))})),r.each((function(e){return t.addToCollection(e,a)})),o.append(a),o.attr('class',i),this},n}(u.Ss);const ut=ct;var pt='text/html',dt=pt;var ft;!function(t){t["html"]="parse:html",t["htmlRoot"]="parse:html:root",t["htmlBefore"]="parse:html:before",t["css"]="parse:css",t["cssBefore"]="parse:css:before",t["all"]="parse"}(ft||(ft={}));var ht=void 0&&(void 0).__assign||function(){return ht=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=0;){var o=e.indexOf('/*'),r=e.indexOf('*/'),i=r>-1?r+2:void 0;e=e.replace(e.slice(o,i),'')}for(var a=e.split(';'),s=0,l=a.length;s'!=="".concat(t.outerHTML).slice(-2)||(a.void=!0),i&&!a.components&&!e.skipChildren){var c=r[0];1===i&&3===c.nodeType?(!a.type&&(a.type='text'),a.components={type:'textnode',content:c.nodeValue}):a.components=this.parseNodes(t,ht(ht({},e),{inSvg:e.inSvg||'svg'===a.type}))}var u=a.components;if(!a.type&&(null==u?void 0:u.length)){for(var p=o.textTypes,d=void 0===p?[]:p,f=o.textTags,h=void 0===f?[]:f,v=!0,g=!1,y=0;y".concat(e,"
"),l=r.parseFromString(s,i);if(a){if(n.asDocument)return l;var c=l.head,u=l.body,p=c.querySelectorAll('script');(0,t.each)(p,(function(t){return u.appendChild(t)}));var d=[];(0,t.each)(c.children,(function(t){return d.push(t)})),(0,t.each)(d,(function(t,e){return u.insertBefore(t,u.children[e])})),o=u}else o=l.firstChild;return o}(m,f),_=b,w=b;g&&(_=w.documentElement,p.doctype=(0,Z.LJ)(w.doctype));var x=_.querySelectorAll('script'),C=x.length;if(!((0,t.isUndefined)(c.allowScripts)?f.allowScripts:c.allowScripts))for(;C--;)null===(s=x[C].parentNode)||void 0===s||s.removeChild(x[C]);if(f.allowUnsafeAttr&&f.allowUnsafeAttrValue||this.__sanitizeNode(_,f),r){for(var S=_.querySelectorAll('style'),O=S.length,T='';O--;)T=S[O].innerHTML+T,null===(l=S[O].parentNode)||void 0===l||l.removeChild(S[O]);T&&(p.css=r.parse(T))}null==u||u.__emitEvent(ft.htmlRoot,{input:m,root:_});var P=[];if(g)p.head=this.parseNode(w.head,h),p.root=this.parseNodeAttr(_),P=this.parseNode(w.body,h);else{var E=this.parseNodes(_,h);P=1!==E.length||h.returnArray?E:E[0]}return p.html=P,null==u||u.__emitEvent(ft.html,{input:m,output:p,options:f}),p},__sanitizeNode:function(e,n){var o=this,r=e.attributes||[],i=e.childNodes||[],a=[];(0,t.each)(r,(function(t){var e=t.nodeName||'',o=t.nodeValue||'';!n.allowUnsafeAttr&&e.startsWith('on')&&a.push(e),!n.allowUnsafeAttrValue&&o.startsWith('javascript:')&&a.push(e)})),a.map((function(t){return e.removeAttribute(t)})),(0,t.each)(i,(function(t){return o.__sanitizeNode(t,n)}))},__checkAsDocument:function(n,o){return(0,e.isDef)(o.asDocument)?o.asDocument:(0,t.isFunction)(o.detectDocument)?!!o.detectDocument(n):o.detectDocument?n.toLowerCase().trim().startsWith('",t["lessThan"]="<",t["greaterThanOrEqual"]=">=",t["lessThanOrEqual"]="<=",t["equals"]="=",t["notEquals"]="!="}(Et||(Et={}));var jt,Mt=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.operationsEnum=Et,e}return At(e,t),e.prototype.evaluate=function(t,e){if('number'!=typeof t)return!1;switch(this.operationString){case Et.greaterThan:return t>e;case Et.lessThan:return t=e;case Et.lessThanOrEqual:return t<=e;case Et.equals:return t===e;case Et.notEquals:return t!==e;default:return this.em.logWarning("Unsupported number operation: ".concat(this.operationString)),!1}},e}(Ct),Dt=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}();!function(t){t["contains"]="contains",t["startsWith"]="startsWith",t["endsWith"]="endsWith",t["matchesRegex"]="matchesRegex",t["equalsIgnoreCase"]="equalsIgnoreCase",t["trimEquals"]="trimEquals"}(jt||(jt={}));var Lt=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.operationsEnum=jt,e}return Dt(e,t),e.prototype.evaluate=function(t,e){if('string'!=typeof t)return!1;switch(this.operationString){case jt.contains:return t.includes(e);case jt.startsWith:return t.startsWith(e);case jt.endsWith:return t.endsWith(e);case jt.matchesRegex:return e||this.em.logWarning('Regex pattern must be provided.'),new RegExp(null!=e?e:'').test(t);case jt.equalsIgnoreCase:return t.toLowerCase()===e.toLowerCase();case jt.trimEquals:return t.trim()===e.trim();default:return this.em.logWarning("Unsupported string operation: ".concat(this.operationString)),!1}},e}(Ct),It=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Nt=function(e){function n(t,n){var o,r=e.call(this,t)||this;return r.collectionsStateMap={},r.em=n.em,r.collectionsStateMap=null!==(o=n.collectionsStateMap)&&void 0!==o?o:{},r}return It(n,e),n.prototype.evaluate=function(){var e=this.get('condition');if(!e||(0,t.isBoolean)(e))return!!e;var n=this.getOperator();return!!n&&n.evaluate(this.getResolvedLeftValue(),this.getResolvedRightValue())},n.prototype.getDependentDataVariables=function(){var t=this.get('condition');return t?this.extractDataVariables(t):[]},n.prototype.getOperations=function(){var t=this.getOperator();return!t||t instanceof xt?[]:t.getOperations()},n.prototype.updateCollectionStateMap=function(t){this.collectionsStateMap=t},n.prototype.getOperator=function(){var e={em:this.em,collectionsStateMap:this.collectionsStateMap},n=this.get('condition');if(n&&!(0,t.isBoolean)(n)){var o;if(this.isLogicGroup(n)){var r=n.logicalOperator,i=n.statements,a=new kt(r,e);o=new xt(a,i,e)}if(this.isExpression(n)){var s=n.left,l=(a=n.operator,ue(s,e));o=this.resolveOperator(l,a)}return o}},n.prototype.resolveOperator=function(t,e){var n=this.em;return this.isOperatorInEnum(e,mt)?new Tt(e,{em:n}):'number'==typeof t?new Mt(e,{em:n}):'string'==typeof t?new Lt(e,{em:n}):void 0},n.prototype.extractDataVariables=function(t){var e=this,n=[];return this.isExpression(t)?(ce(t.left)&&n.push(t.left),ce(t.right)&&n.push(t.right)):this.isLogicGroup(t)&&t.statements.forEach((function(t){return n.push.apply(n,e.extractDataVariables(t))})),n},n.prototype.isLogicGroup=function(t){return t&&void 0!==t.logicalOperator&&Array.isArray(t.statements)},n.prototype.isExpression=function(t){return t&&void 0!==t.left&&'string'==typeof t.operator},n.prototype.isOperatorInEnum=function(t,e){return Object.values(e).includes(t)},n.prototype.resolveExpressionSide=function(t){var e=this.get('condition'),n=this.em,o=this.collectionsStateMap;return e&&'boolean'!=typeof e?e&&'object'==typeof e&&t in e?ue(e[t],{em:n,collectionsStateMap:o}):void 0:e},n.prototype.getResolvedLeftValue=function(){return this.resolveExpressionSide('left')},n.prototype.getResolvedRightValue=function(){return this.resolveExpressionSide('right')},n.prototype.toJSON=function(t){var e=this.get('condition');return'object'==typeof e?JSON.parse(JSON.stringify(e)):e},n}(u.Kx),Rt=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Vt='data-condition',Ft='data-condition-evaluation-changed',Ht='data-condition-output-changed',Ut=function(t){function e(e,n){var o,r=t.call(this,e,n)||this;r.collectionsStateMap={},r.resolverListeners=[],r._previousEvaluationResult=null,r.em=n.em,r.collectionsStateMap=null!==(o=n.collectionsStateMap)&&void 0!==o?o:{};var i=e.condition,a=new Nt({condition:void 0===i?{}:i},{em:r.em});return r._conditionEvaluator=a,r.listenToDataVariables(),r.listenToPropsChange(),r}return Rt(e,t),e.prototype.defaults=function(){return{type:Vt,condition:{left:'',operator:jt.equalsIgnoreCase,right:''},ifTrue:{},ifFalse:{}}},e.prototype.getCondition=function(){return this._conditionEvaluator.get('condition')},e.prototype.getIfTrue=function(){return this.get('ifTrue')},e.prototype.getIfFalse=function(){return this.get('ifFalse')},e.prototype.getOperations=function(){return this._conditionEvaluator.getOperations()},e.prototype.setCondition=function(t){this.set('condition',t),this._conditionEvaluator.set('condition',t),this.trigger(Ht,this.getDataValue())},e.prototype.setIfTrue=function(t){this.set('ifTrue',t)},e.prototype.setIfFalse=function(t){this.set('ifFalse',t)},e.prototype.isTrue=function(){return this._conditionEvaluator.evaluate()},e.prototype.getDataValue=function(t){void 0===t&&(t=!1);var e={em:this.em,collectionsStateMap:this.collectionsStateMap},n=this.getIfTrue(),o=this.getIfFalse(),r=this.isTrue();return t?r?n:o:ue(r?n:o,e)},e.prototype.resolvesFromCollection=function(){return!1},e.prototype.updateCollectionsStateMap=function(t){this.collectionsStateMap=t,this._conditionEvaluator.updateCollectionStateMap(t),this.listenToDataVariables(),this.emitConditionEvaluationChange()},e.prototype.listenToPropsChange=function(){var t=this;this.on('change:condition',this.handleConditionChange.bind(this)),this.on('change:condition change:ifTrue change:ifFalse',(function(){t.listenToDataVariables()}))},e.prototype.handleConditionChange=function(){this.setCondition(this.get('condition'))},e.prototype.listenToDataVariables=function(){this.cleanupListeners(),this.setupConditionDataVariableListeners(),this.setupOutputDataVariableListeners()},e.prototype.setupConditionDataVariableListeners=function(){var t=this;this._conditionEvaluator.getDependentDataVariables().forEach((function(e){t.addListener(e,(function(){t.emitConditionEvaluationChange()}))}))},e.prototype.setupOutputDataVariableListeners=function(){var t=this.isTrue();this.setupOutputVariableListener(this.getIfTrue(),t),this.setupOutputVariableListener(this.getIfFalse(),!t)},e.prototype.setupOutputVariableListener=function(t,e){var n=this;ce(t)&&this.addListener(t,(function(){e&&n.trigger(Ht,t)}))},e.prototype.addListener=function(t,e){var n=new _e({em:this.em,resolver:new me(t,{em:this.em,collectionsStateMap:this.collectionsStateMap}),onUpdate:e});this.resolverListeners.push(n)},e.prototype.emitConditionEvaluationChange=function(){var t=this.isTrue();this._previousEvaluationResult!==t&&(this._previousEvaluationResult=t,this.trigger(Ft,t),this.emitOutputValueChange())},e.prototype.emitOutputValueChange=function(){var t=this.getDataValue();this.trigger(Ht,t)},e.prototype.cleanupListeners=function(){this.resolverListeners.forEach((function(t){return t.destroy()})),this.resolverListeners=[]},e.prototype.toJSON=function(){var t=this.getIfTrue(),e=this.getIfFalse();return{type:Vt,condition:this._conditionEvaluator.toJSON(),ifTrue:t,ifFalse:e}},e}(u.Kx),zt='data-condition-true-content',Bt='data-condition-false-content',Wt=void 0&&(void 0).__assign||function(){return Wt=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=0}))},te=function(t,e){void 0===e&&(e={});var n=[],o=e.changed;if(e.fromInstance||e.noPropagate||e.fromUndo||o&&Qt(t,o))return n;var r=Zt(t)||[],i=Xt(t);return n=(i?$t([i],Zt(i)||[],!0):r).filter((function(e){return e!==t})).filter((function(t){return!(o&&Qt(t,o))}))},ee=function(t,e){for(var n=t,o=t.parent(e);o&&Kt(o);)n=o,o=o.parent(e);return n},ne=function(t,e){void 0===e&&(e={});var n=Xt(t),o=n&&Zt(n);!e.skipRefs&&o&&n.set(Tn,o.filter((function(e){return e!==t}))),t.set(Pn,0),t.components().forEach((function(t){return ne(t,e)}))},oe=function(t,e,n,o){void 0===o&&(o={});var r=Xt(t),i=Zt(t);(r||i)&&t.em.log(e,{model:t,toUp:n,context:'symbols',opts:o})},re=function(t){var n,o;['status','open',Tn,Pn,En].forEach((function(e){return delete t[e]})),null===(n=t.attributes)||void 0===n||delete n.id,(0,e.isEmptyObj)(null!==(o=t.attributes)&&void 0!==o?o:{})&&delete t.attributes},ie=function(e,n){var o=Wt({},e);return(0,t.keys)(e).forEach((function(t){ae(e,t,n)||delete o[t]})),o},ae=function(t,e,n){var o=function(){var n;if('attributes'===e){var o=t['attributes'];return Object.values(o).some((function(t){return!!(null==t?void 0:t.collectionId)}))}return!!(null===(n=t[e])||void 0===n?void 0:n.collectionId)}();return!Qt(n,e)||o},se=function(t,e,n,o){var r=o||n||{},i={fromInstance:r.fromInstance,fromUndo:r.fromUndo},a=e.opt.temporary;if(o)if(o.add){var s=[],l=!!Zt(t);if((m=te(t,Wt(Wt({},i),{changed:'components:add'}))).length){var c=Xt(e);s=Zt(c||e)||[],(s=$t([],s,!0)).push(c||e)}!a&&oe(t,'add',m,{opts:o,addedInstances:s.map((function(t){return t.cid})),added:e.cid}),m.forEach((function(n){var r=ee(n),i=s.filter((function(t){var e=ee(t,{prev:1});return r&&e&&e===r}))[0]||e.clone({symbol:!0,symbolInv:l});n.append(i,Wt({fromInstance:t},o))}))}else{var u=Xt(e);if(u&&!o.temporary&&u.set(Tn,Zt(u).filter((function(t){return t!==e}))),!Yt(e)&&!o.skipRefsUp){var p='components:remove',d=o.index,f=e.parent(),h=Wt({fromInstance:e},o),v=Yt(e),g=function(t){var e=t.parent();e&&!Qt(e,p)&&t.remove(h)};m=Qt(f,p)?[]:te(e,i);v&&(m=f&&te(f,Wt(Wt({},i),{changed:p})),g=function(t){var e=t.components().at(d);e&&e.remove(Wt({fromInstance:f},h))}),!a&&oe(t,'remove',m,{opts:o,removed:e.cid,isSymbNested:v}),m.forEach(g)}}else{var y=e,m=te(t,Wt(Wt({},i),{changed:'components:reset'})),b=y.models,_=new Set;oe(t,'reset',m,{components:b}),m.forEach((function(e){var o=e.components(),r=b.map((function(e,n){return t.get(wt)?e.clone({symbol:Kt(e)}):!Kt(e)||_.has(e)?(_.add(e),e.clone({symbol:!0})):o.at(n)}));o.reset(r,Wt({fromInstance:t},n))}))}t.__changesUp(r)};function le(t){return'object'==typeof t&&[ge,Vt].includes(null==t?void 0:t.type)}function ce(t){return(null==t?void 0:t.type)===ge}function ue(t,e){return le(t)?(ce(t)&&me.resolveDataResolver(t,e),de(t,e)):t}function pe(t,e){var n,o,r=t.type;switch(r){case ge:o=new me(t,e);break;case Vt:o=new Ut(t,e);break;default:return void(null===(n=e.em)||void 0===n||n.logWarning("Unsupported resolver type: ".concat(r)))}return o}function de(t,e){var n=pe(t,e);return null==n?void 0:n.getDataValue()}function fe(t){var e=function(t){var e=t.collectionsStateMap;if(!e)return!1;var n=Object.keys(e);if(!n.length)return!1;var o=Xt(t);if(!o||o===t)return!1;var r=o.collectionsStateMap;return Object.keys(r).every((function(t){return n.includes(t)}))}(t),n=e?function(t){var e=Xt(t);return e?e.getId():''}(t):null;return{shouldSync:e,itemId:n}}var he=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),ve=void 0&&(void 0).__assign||function(){return ve=Object.assign||function(t){for(var e,n=1,o=arguments.length;n0,s=r&&Object.keys(o.getAllDataResolvers()).length>0;return i||a||s},e.prototype.updateSymbolOverride=function(){var t,e=this.model;if(this.isComponent(e)&&!!Object.keys(null!==(t=null==e?void 0:e.collectionsStateMap)&&void 0!==t?t:{}).length){var n=this.propertyWatcher.getValuesResolvingFromCollections(),o=this.attributeWatcher.getValuesResolvingFromCollections(),r=Se(['locked','layerable',Te],n,!0);Object.keys(o).length&&r.push('attributes'),te(e).forEach((function(t){t.setSymbolOverride(r,{fromDataSource:!0})})),e.setSymbolOverride(r,{fromDataSource:!0})}},e.prototype.filterProps=function(t){var e=['components','dataResolver',Te],n=Object.fromEntries(Object.entries(t).filter((function(t){var n=t[0];return!e.includes(n)})));return n},e.prototype.processAttributes=function(t,e,n){var o;return void 0===n&&(n={}),this.attributeWatcher.setDataValues(Ce(Ce({},t.attributes),null!==(o=e.attributes)&&void 0!==o?o:{}),n)},e.prototype.processStyles=function(t,e,n){var o;return void 0===n&&(n={}),'string'==typeof t?(this.styleWatcher.removeListeners(),t):this.styleWatcher.setDataValues(Ce(Ce({},t.style),null!==(o=e.style)&&void 0!==o?o:{}),n)},e}(),Ee=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),ke=void 0&&(void 0).__assign||function(){return ke=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=0:r;if('__'===e.substring(0,2))return"continue";var a=o[e];((0,t.isArray)(a)?a:[a]).forEach((function(t){var o="".concat(t).concat(i?' !important':'');o&&n.push("".concat(e,":").concat(o,";"))}))};for(var a in o)i(a);return n.join('')},o.prototype.getSelectors=function(){return this.get('selectors')||this.get('classes')},o.prototype.getSelectorsString=function(t){return this.selectorsToString?this.selectorsToString(t):this.getSelectors().getFullString()},o.prototype.onCollectionsStateMapUpdate=function(t){this.collectionsStateMap=t,this.dataResolverWatchers.onCollectionsStateMapUpdate()},o.prototype.clone=function(t,e){var n=this.dataResolverWatchers.getProps(this.attributes),o=ke(ke({},n),t),r=ke(ke({},this.opt),e);return new(0,this.constructor)(o,r)},o.prototype.toJSON=function(t,e){if(null==t?void 0:t.fromUndo)return ke({},n.prototype.toJSON.call(this,t));var o=ke(ke({},this.attributes),e);return this.dataResolverWatchers.getProps(o)},o}(u.Kx);const De=Me;var Le=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Ie=void 0&&(void 0).__assign||function(){return Ie=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=0}));e.keepIds=(e.keepIds||[]).concat(s),i.forEach((function(t){return n.removeChildren(t,o,e)})),t.each((function(t){return n.onAdd(t)}))},n.prototype.resetFromString=function(t,e){var n,o;void 0===t&&(t=''),void 0===e&&(e={}),e.keepIds=Ve(this);var r=this,i=r.domc,a=r.em,s=r.parent,l=null==a?void 0:a.Css,c=(null==i?void 0:i.allById())||{},u=this.parseString(t,e),p=Fe(u,c,e),d=e.visitedCmps,f=void 0===d?{}:d;Object.keys(f).forEach((function(t){var e=f[t];if(e.length){var n=(null==l?void 0:l.getRules("#".concat(t)))||[];n.length&&e.forEach((function(t){n.forEach((function(e){var n=e.clone();n.set('selectors',["#".concat(t.attributes.id)]),l.getAll().add(n)}))}))}})),this.reset(p,e),null==a||a.trigger('component:content',s,e,t),null===(o=(n=s).__checkInnerChilds)||void 0===o||o.call(n)},n.prototype.removeChildren=function(t,e,n){var o=this;if(void 0===n&&(n={}),t){var r=this.domc,i=this.em,a=n.temporary||n.fromUndo;if(t.prevColl=this,!a){var s=t.getId(),l=i.Selectors.getAll(),c=i.Css.getAll(),u=(n.keepIds||[]).indexOf(s)<0;delete(r?r.allById():{})[s];var p=u?c.remove(c.filter((function(t){return t.getSelectors().getFullString()==="#".concat(s)})),n):[];l.remove(p.map((function(t){return t.getSelectors().at(0)}))),t.opt.temporary||(i.Commands.run('core:component-style-clear',{target:t}),t.views.forEach((function(e){e.scriptContainer&&t.emitWithEditor($.I.scriptUnmount,{component:t,view:e,el:e.el})})),t.removed(),t.trigger('removed'),i.trigger($.I.remove,t),r&&Gt(t)&&Yt(t)&&r.symbols.__trgEvent(r.events.symbolInstanceRemove,{component:t},!0));var d=t.components();d.forEach((function(t){se(t,t,d,Ie(Ie({},n),{skipRefsUp:!0})),o.removeChildren(t,e,n)}))}var f=t.components();if(i.stopListening(f),i.stopListening(t),i.stopListening(t.get('classes')),t.__postRemove(),!t.opt.temporary){var h=function(t){t.emitWithEditor($.I.removed,t,{removeOptions:n}),t.components().forEach((function(t){return h(t)}))};h(t)}}},n.prototype.model=function(t,e){var n,o=e.collection.opt,r=o.em,i=r.Components.componentTypes;e.em=r,e.config=o.config,e.componentTypes=i,e.domc=o.domc;for(var a=0;a=0&&i.set('void',!0),r.em=a,i.opt=r,i.em=a,i.config=r.config||{};var d=_n(_n({},(0,t.result)(i,'defaults').attributes||{}),i.get('attributes')||{}),f=i.dataResolverWatchers.getValueOrResolver('attributes',d);if(i.setAttributes(f),i.ccid=o.createId(i,r),i.preInit(),i.initClasses(),i.initComponents(),i.initTraits(),i.initToolbar(),i.initScriptProps(),i.listenTo(i,'change:script',i.scriptUpdated),i.listenTo(i,'change:tagName',i.tagUpdated),i.listenTo(i,'change:attributes',i.attrUpdated),i.listenTo(i,'change:attributes:id',i._idUpdated),i.on('change:toolbar',i.__emitUpdateTlb),i.on('change',i.__onChange),i.on(An,i.__propToParent),i.set('status',''),i.views=[],['classes','traits','components'].forEach((function(t){var e="add remove reset ".concat('components'!==t?'change':'');i.listenTo(i.get(t),e.trim(),(function(){for(var e=[],n=0;n").concat(r);return!i&&(a+="")),a},o.prototype.getInnerHTML=function(t){return this.__innerHTML(t)},o.prototype.__innerHTML=function(t){void 0===t&&(t={});var e=this.components();return e.length?e.map((function(e){return e.toHTML(t)})).join(''):this.content},o.prototype.__attrToString=function(n){void 0===n&&(n={});var o=[],r=n.attributes,i=this.getAttrToHTML(n);if(r&&((0,t.isFunction)(r)?i=r(this,i)||{}:(0,e.isObject)(r)&&(i=r)),n.withProps){var a=this.toJSON();(0,t.forEach)(a,(function(n,o){'_'!==o[0]&&['classes','attributes','components'].indexOf(o)<0&&(i["data-gjs-".concat(o)]=(0,t.isArray)(n)||(0,e.isObject)(n)?JSON.stringify(n):(0,t.isBoolean)(n)?"".concat(n):n)}))}for(var s in i){var l=i[s];if(!(0,t.isUndefined)(l)&&null!==l)if((0,t.isBoolean)(l))l&&o.push(s);else{var c='';if(n.altQuoteAttr&&(0,t.isString)(l)&&l.indexOf('"')>=0)c="'".concat((0,e.escapeAltQuoteAttrValue)(l),"'");else{var u=(0,t.isString)(l)?(0,e.escapeAttrValue)(l):l;c="\"".concat(u,"\"")}o.push("".concat(s,"=").concat(c))}}return o.join(' ')},o.prototype.getAttrToHTML=function(t){var e=this.getAttributes();return Sn(this.em)&&!0!==(null==t?void 0:t.keepInlineStyle)&&delete e.style,e},o.prototype.toJSON=function(e){void 0===e&&(e={});var o=n.prototype.toJSON.call(this,e,{attributes:this.getAttributes()});if(delete o.dataResolverWatchers,delete o.attributes.class,delete o.toolbar,delete o.traits,delete o.status,delete o.open,delete o._undoexc,delete o.delegate,this.collectionsStateMap&&Object.getOwnPropertyNames(this.collectionsStateMap).length>0&&(delete o[Pn],delete o[En],delete o[Tn],delete o.attributes.id),!e.fromUndo){var r=o[Pn],i=o[Tn];i&&(0,t.isArray)(i)&&(o[Tn]=i.filter((function(t){return t})).map((function(t){return t.getId?t.getId():t}))),r&&!(0,t.isString)(r)&&(o[Pn]=r.getId())}return this.em.getConfig().avoidDefaults&&this.getChangedProps(o),o},o.prototype.getChangedProps=function(e){var n=e||a.Model.prototype.toJSON.apply(this),o=(0,t.result)(this,'defaults');return(0,t.forEach)(o,(function(t,e){-1===['type'].indexOf(e)&&n[e]===t&&delete n[e]})),(0,t.isEmpty)(n.type)&&delete n.type,(0,t.forEach)(['attributes','style'],(function(e){(0,t.isEmpty)(o[e])&&(0,t.isEmpty)(n[e])&&delete n[e]})),(0,t.forEach)(['classes','components'],(function(e){(!n[e]||(0,t.isEmpty)(o[e])&&!n[e].length)&&delete n[e]})),n},o.prototype.getId=function(){var t=this.get('attributes')||{},e=fe(this),n=e.shouldSync,o=e.itemId;return n&&(t.id=o),t.id||this.ccid||this.cid},o.prototype.setId=function(t,e){return this.addAttributes({id:t},e),this},o.prototype.getEl=function(t){var e=this.getView(t);return e&&e.el},o.prototype.getView=function(t){var e=this,n=e.view,o=e.views,r=e.em,i=t||(null==r?void 0:r.getCurrentFrameModel());return i&&(n=o.filter((function(t){return t.frameView===i.view}))[0]),n},o.prototype.getCurrentView=function(){var t=this.em.getCurrentFrame(),e=null==t?void 0:t.model;return this.getView(e)},o.prototype.__getScriptProps=function(){var t=this.props();return(this.get('script-props')||[]).reduce((function(e,n){return e[n]=t[n],e}),{})},o.prototype.getScriptString=function(e){var n=this,o=e||this.get('script')||'';if(!o)return o;if(this.get('script-props'))o=o.toString().trim();else{if((0,t.isFunction)(o)){var r=o.toString().trim();o=(r=r.slice(r.indexOf('{')+1,r.lastIndexOf('}'))).trim()}var i=this.em.getConfig(),a=Cn(i.tagVarStart||'{[ '),s=Cn(i.tagVarEnd||' ]}'),l=new RegExp("".concat(a,"([\\w\\d-]*)").concat(s),'g');o=o.replace(l,(function(e,o){n.scriptUpdated();var r=n.attributes[o]||'';return(0,t.isArray)(r)||'object'==typeof r?JSON.stringify(r):r}))}return o},o.prototype.emitUpdate=function(t){for(var e,n=[],o=1;o=0&&this.__propSelfToParent({component:this,changed:(e={},e[t]=a,e),options:n[2]||n[1]||{}})},o.prototype.emitWithEditor=function(t,e,n){[this.em,this].forEach((function(o){return null==o?void 0:o.trigger(t,e,n)}))},o.prototype.onAll=function(e){return(0,t.isFunction)(e)&&(e(this),this.components().forEach((function(t){return t.onAll(e)}))),this},o.prototype.forEachChild=function(e){(0,t.isFunction)(e)&&this.components().forEach((function(t){e(t),t.forEachChild(e)}))},o.prototype.remove=function(t){var e=this;void 0===t&&(t={});var n=this.em,o=this.collection,r=function(){o&&o.remove(e,_n({action:$.t.remove},t)),o||(e.components('',t),e.components().removeChildren(e,void 0,t))},i=_n({},t);return[this,n].map((function(t){return t.trigger($.I.removeBefore,e,r,i)})),!i.abort&&r(),this},o.prototype.destroy=function(t){return this.stopListening(this.components(),'add remove reset',this.syncOnComponentChange),this.dataResolverWatchers.destroy(),this.__onDestroy(),n.prototype.destroy.call(this,t)},o.prototype.move=function(t,e){if(void 0===e&&(e={}),t){var n=e.at,o=this.index(),r=t===this.parent();if(!r||!(o===n||o===n-1)){r&&n&&n>o&&(e.at=n-1);var i=$.t.move;this.remove({action:i,temporary:1}),t.append(this,_n({action:i},e)),this.emitUpdate()}}return this},o.prototype.isInstanceOf=function(t){var e,n,o=null===(n=null===(e=this.em)||void 0===e?void 0:e.Components.getType(t))||void 0===n?void 0:n.model;if(!o)return!1;var r=this.constructor.typeExtends;return this instanceof o||r.has(t)},o.prototype.isChildOf=function(e){for(var n=(0,t.isString)(e),o=this.parent();o;){if(n){if(o.isInstanceOf(e))return!0}else if(o===e)return!0;o=o.parent()}return!1},o.prototype.resetId=function(t){void 0===t&&(t={});var e=this.em,n=this.getId();if(!n)return this;var r=o.createId(this);this.setId(r);var i=null==e?void 0:e.Css.getIdRule(n),a=null==i?void 0:i.get('selectors').at(0);return null==a||a.set('name',r),this},o.prototype._getStyleRule=function(t){var e=(void 0===t?{}:t).id,n=this.em,o=e||this.getId();return null==n?void 0:n.Css.getIdRule(o)},o.prototype._getStyleSelector=function(t){var e=this._getStyleRule(t);return null==e?void 0:e.get('selectors').at(0)},o.prototype._moveInlineStyleToRule=function(){var n=this.get('style'),o=(0,t.isString)(n)&&n.length>0||(0,e.isObject)(n)&&Object.keys(n).length>0;Sn(this.em)&&o&&this.addStyle((0,e.isObject)(n)?this.dataResolverWatchers.getValueOrResolver('styles',n):n,{avoidStore:!0,noUndo:!0})},o.prototype._idUpdated=function(t,e,n){if(void 0===n&&(n={}),!n.idUpdate){var r=this.ccid,i=(this.get('attributes')||{}).id,a=(this.previous('attributes')||{}).id||r,s=o.getList(this);if(s[i]||!i&&a)return this.setId(a,{idUpdate:!0});delete s[a],s[i]=this,this.ccid=i;var l=this._getStyleSelector({id:a});l&&l.set({name:i,label:i})}},o.getDefaults=function(){return(0,t.result)(this.prototype,'defaults')},o.isComponent=function(t,n){return{tagName:(0,e.toLowerCase)(t.tagName)}},o.ensureInList=function(t){var e=o.getList(t),n=t.getId(),r=e[n];if(r){if(r!==t){var i=o.getIncrementId(n,e);t.setId(i),e[i]=t}}else e[n]=t;t.components().forEach((function(t){return o.ensureInList(t)}))},o.createId=function(t,e){void 0===e&&(e={});var n,r=o.getList(t),i=e.idMap,a=void 0===i?{}:i,s=t.get('attributes').id;return s?(n=o.getIncrementId(s,r,e),t.setId(n),s!==n&&(a[s]=n)):n=o.getNewId(r),r[n]=t,n},o.getNewId=function(t){for(var e=Object.keys(t).length.toString().length+2,n=(Math.random()+1.1).toString(36).slice(-e),r="i".concat(n);t[r];)r=o.getNewId(t);return r},o.getIncrementId=function(t,e,n){void 0===n&&(n={});var o=n.keepIds,r=1,i=t;if((void 0===o?[]:o).indexOf(t)<0)for(;e[i];)r++,i="".concat(t,"-").concat(r);return i},o.getList=function(t){var e,n=t.em,o=null==n?void 0:n.Components;return null!==(e=null==o?void 0:o.componentsById)&&void 0!==e?e:{}},o.checkId=function(e,n,r,i){void 0===n&&(n=[]),void 0===r&&(r={}),void 0===i&&(i={});var a=(0,t.isArray)(e)?e:[e],s=i.keepIds,l=void 0===s?[]:s,c=i.idMap,u=void 0===c?{}:c;a.forEach((function(e){e.attributes;var a=e.attributes,s=void 0===a?{}:a,c=e.components,p=s.id;if(p&&r[p]&&l.indexOf(p)<0){var d=o.getIncrementId(p,r);u[p]=d,s.id=d,(0,t.isArray)(n)&&n.forEach((function(t){var e=t.selectors;e.forEach((function(t,n){t==="#".concat(p)&&(e[n]="#".concat(d))}))}))}c&&o.checkId(c,n,r,i)}))},o.typeExtends=new Set,o}(De);const Mn=jn;var Dn=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Ln=void 0&&(void 0).__assign||function(){return Ln=Object.assign||function(t){for(var e,n=1,o=arguments.length;na&&(s+=r-a);var l=this.getElScrollTop(o);s=Math.min(s,this.lastMaxHeight-l),0!==(s=Math.max(s,-l))&&(o.scrollBy({top:s,behavior:'auto'}),null===(e=this.onScroll)||void 0===e||e.call(this)),requestAnimationFrame(this.autoscroll)}else setTimeout((function(){requestAnimationFrame(n.autoscroll)}),50)},e.prototype.getEventElHeight=function(){var t=this.eventEl;return t?t.getBoundingClientRect().height:0},e.prototype.updateClientY=function(t){var e=t.target;if(!this.ignoredElement||!this.ignoredElement.contains(e)){var n=this.scrollEl;t.preventDefault();var o=this.rectIsInScrollIframe?0:this.getElScrollTop(n);this.lastClientY=(0,Z.G2)(t).clientY*this.zoom-o}},e.prototype.getElScrollTop=function(t){return(t instanceof HTMLElement?t.scrollTop:null==t?void 0:t.scrollY)||0},e.prototype.toggleAutoscrollFx=function(t){this.dragging=t;var e=this.eventEl;if(e){var n=t?'on':'off',o={on:Z.on,off:Z.AU};o[n](e,'mousemove dragover',this.updateClientY),o[n](e,'mouseup',this.stop)}},e.prototype.stop=function(){this.toggleAutoscrollFx(!1),this.lastClientY=void 0,this.ignoredElement=void 0},e}();const Hn=Fn;var Un=n(1447),zn=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Bn=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return zn(n,e),n.prototype.canMove=function(e,n){var o=this,r=this.getRealIndex(n),i=e._dragSource,a=i.model,s=i.content,l=i.dragDef,c=!a||!this.isSourceSameSymbol(a),u=((0,t.isFunction)(s)?l:s)||e.model;return Array.isArray(u)?c&&u.every((function(t,e){return o.canMoveSingleContent(t,r+e)})):c&&this.canMoveSingleContent(u,r)},n.prototype.canMoveSingleContent=function(t,e){return this.model.em.Components.canMove(this.model,t,e).result},n.prototype.addChildAt=function(e,n){var o=e._dragSource.content,r=this.isTextNode()&&e.isTextable(),i=(0,t.isFunction)(o)?o():o;return Array.isArray(i)?this.addMultipleChildren(i,n,r):this.addSingleChild(i,n,r)},n.prototype.addSingleChild=function(t,e,n){var o,r,i,a,s;return s=n?null===(a=null===(i=null===(r=null===(o=this.model)||void 0===o?void 0:o.getView)||void 0===r?void 0:r.call(o))||void 0===i?void 0:i.insertComponent)||void 0===a?void 0:a.call(i,t,{action:'add-component'}):this.model.components().add(t,{at:this.getRealIndex(e),action:'add-component'}),new this.constructor(s)},n.prototype.addMultipleChildren=function(t,e,n){var o,r=this;return t.forEach((function(t,i){o=r.addSingleChild(t,e+i,n)})),o},n.prototype.isSourceSameSymbol=function(t){if(Kt(this.model)){var e=ee(this.model);if((qt(e)?e:Xt(e))===t)return!0}return!1},Object.defineProperty(n.prototype,"content",{set:function(t){this._dragSource.content=t},enumerable:!1,configurable:!0}),n}(Un.A);const Wn=Bn;var $n=n(8433),qn=void 0&&(void 0).__assign||function(){return qn=Object.assign||function(t){for(var e,n=1,o=arguments.length;n';if(r.stopDefault(),r.inAbsoluteMode()){var p=r.Components.getWrapper(),d=p.append({})[0],f=r.Commands.run('core:component-drag',{event:t,guidesInfo:1,center:1,target:d,onEnd:function(t,e,n){var r;if(!n.cancelled&&u){r=p.append(u)[0];var s=i.getOffset(),l=d.getStyle(),c=l.top,f=l.left,h=l.position,v=(0,Z.Xy)(t.target),g=parseInt("".concat(parseFloat(f)+v.x-s.left),10),y=parseInt("".concat(parseFloat(c)+v.y-s.top),10);r.addStyle({left:g+'px',top:y+'px',position:h})}o.handleDragEnd(r,a),d.remove()}});l=function(e){return f.stop(t,{cancel:e})},this.setAbsoluteDragContent=function(t){return u=t}}else{var h=new c.ComponentSorter({em:r,treeClass:Wn,containerContext:{container:this.el,containerSel:'*',itemSel:'*',pfx:'gjs-',placeholderElement:i.getPlacerEl(),document:this.el.ownerDocument},dragBehavior:{dragDirection:$n.A.BothDirections,nested:!0},positionOptions:{windowMargin:1,canvasRelative:!0},eventHandlers:{legacyOnEndMove:this.handleDragEnd}}),v=null===(e=this.getSorterOptions)||void 0===e?void 0:e.call(this,h);v&&(h.eventHandlers.legacyOnStartSort=v.legacyOnStart,h.eventHandlers.legacyOnEnd=v.legacyOnEnd,h.containerContext.customTarget=v.customTarget);var g=r.Components.getShallowWrapper(),y=null==g?void 0:g.append(u,{temporary:!0})[0],m=[{element:null==y?void 0:y.getEl(),dragSource:qn({model:y},s)}];h.startSort(m),this.sorter=h,this.draggedNode=null===(n=h.sourceNodes)||void 0===n?void 0:n[0],l=function(t){t?h.cancelDrag():h.endDrag()}}this.dragStop=l,r.trigger('canvas:dragenter',a,u)}},e.prototype.handleDragEnd=function(t,e){var n=this.em;this.over=!1,t&&(n.set('dragResult',t),n.trigger('canvas:drop',e,t)),n.runDefault({preserveSelected:1})},e.prototype.handleDragOver=function(t){t.preventDefault(),this.em.trigger('canvas:dragover',t)},e.prototype.handleDrop=function(t){var e;t.preventDefault();var n=t.dataTransfer,o=this.getContentByData(n).content||'';this.draggedNode&&(this.draggedNode.content=o),null===(e=this.setAbsoluteDragContent)||void 0===e||e.call(this,o),this.endDrop(!o,t)},e.prototype.getContentByData=function(e){var n=this.em,o=(null==e?void 0:e.types)||[],r=(null==e?void 0:e.files)||[],i=n.get('dragSource'),a=(null==e?void 0:e.getData('text'))||'';if(r.length){a=[];for(var s=0;s=0)a=e&&e.getData('text/html').replace(/<\/?meta[^>]*>/g,'');else if((0,t.indexOf)(o,'text/uri-list')>=0)a={type:'link',attributes:{href:a},content:a};else if((0,t.indexOf)(o,'text/json')>=0){var u=e&&e.getData('text/json');u&&(a=JSON.parse(u))}else 1===o.length&&'text/plain'===o[0]&&(a="
".concat(a,"
"));var p={content:a,setContent:function(t){p.content=t}};return n.trigger('canvas:dragdata',e,p),p},e}();const Kn=Gn;var Yn=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Jn=void 0&&(void 0).__assign||function(){return Jn=Object.assign||function(t){for(var e,n=1,o=arguments.length;n0){var l=n.shift(),u=(0,Z.a_)('script',Jn({type:'text/javascript'},(0,t.isString)(l)?{src:l}:l));null===(r=o.contentDocument)||void 0===r||r.head.appendChild(u),u.hasAttribute('nomodule')&&'noModule'in HTMLScriptElement.prototype?c(n):u.onerror=u.onload=c.bind(null,n)}else null==i||i.trigger(A.frameLoadHead,s),e.renderBody(),null==i||i.trigger(A.frameLoadBody,s),null==i||i.trigger(a,s)};o.onload=function(){var t=e.config.frameContent;if(t){var n=e.getDoc();n.open(),n.write(t),n.close()}s.window=e.getWindow(),null==i||i.trigger("".concat(a,":before"),s),null==i||i.trigger(A.frameLoad,s),e.renderHead(),c(Xn([],l.get('scripts'),!0))}},o.prototype.renderStyles=function(e){void 0===e&&(e={});var n=this.getHead(),o=this.getCanvasModel(),r=function(e){return void 0===e&&(e=[]),e.map((function(e){return{tag:'link',attributes:Jn({rel:'stylesheet'},(0,t.isString)(e)?{href:e}:e)}}))},i=r(e.prev||o.previous('styles')),a=r(null==o?void 0:o.get('styles')),s=[],l=[],c=function(t,e,n){t.forEach((function(t){var o=t.attributes.href;!e.some((function(t){return t.attributes.href===o}))&&n.push(t)}))};c(a,i,l),c(i,a,s),s.forEach((function(t){var e,o=n.querySelector("link[href=\"".concat(t.attributes.href,"\"]"));null===(e=null==o?void 0:o.parentNode)||void 0===e||e.removeChild(o)})),(0,Z.af)(n,l)},o.prototype.renderHead=function(){var t,e=this.model,n=this.em,o=e.root,r=null===(t=null==n?void 0:n.Components)||void 0===t?void 0:t.getType(In).view;r&&(this.headView=new r({el:this.getHead(),model:o.head,config:Jn(Jn({},o.config),{frameView:this})}).render())},o.prototype.renderBody=function(){var e,n=this,o=this,r=o.config,i=o.em,a=o.model,s=o.ppfx,l=this.getBody(),c=this.getWindow(),u=a.hasAutoHeight(),p=i.config;c._isEditor=!0,this.renderStyles({prev:[]});(0,Z.BC)(l,""));var d=a.root,f=((null===(e=null==i?void 0:i.Components)||void 0===e?void 0:e.getType('wrapper'))||{}).view;f&&((0,t.isFunction)(r.customRenderer)?r.customRenderer({editor:i.Editor,frame:a,window:c,frameView:this,onMount:function(t){n.wrapper=t,n._onRootMount(t)}}):(this.wrapper=new f({model:d,config:Jn(Jn({},d.config),{em:i,frameView:this})}).render(),this._onRootMount(this.wrapper)))},o.prototype._onRootMount=function(t){var n,o=this,r=this,i=r.config,a=r.em,s=r.model,l=this.getDoc(),c=l.body;(0,Z.BC)(c,t.el),(0,Z.BC)(c,new ut({collection:s.getStyles(),config:Jn(Jn({},a.Css.getConfig()),{frameView:this})}).render().el),(0,Z.BC)(c,this.getJsContainer()),(0,Z.on)(c,'click',(function(t){var e;return t&&'A'==(null===(e=t.target)||void 0===e?void 0:e.tagName)&&t.preventDefault()})),(0,Z.on)(c,'submit',(function(t){return t&&t.preventDefault()})),[{event:'keydown keyup keypress',class:'KeyboardEvent'},{event:'mousedown mousemove mouseup',class:'MouseEvent'},{event:'pointerdown pointermove pointerup',class:'PointerEvent'},{event:'wheel',class:'WheelEvent',opts:{passive:!i.infiniteCanvas}}].forEach((function(t){return t.event.split(' ').forEach((function(e){l.addEventListener(e,(function(e){return o.el.dispatchEvent((0,Z.yL)(e,t.class))}),t.opts)}))})),this._toggleEffects(!0),(0,e.hasDnd)(a)&&(this.droppable=new Kn(a,null===(n=this.wrapper)||void 0===n?void 0:n.el)),this.loaded=!0,s.trigger('loaded')},o.prototype._toggleEffects=function(t){var e=t?Z.on:Z.AU,n=this.getWindow();n&&e(n,"".concat(Z.D8," resize"),this._emitUpdate)},o.prototype._emitUpdate=function(){this.model._emitUpdated()},o}(X);const Qn=Zn;var to=n(9966),eo=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),no=void 0&&(void 0).__assign||function(){return no=Object.assign||function(t){for(var e,n=1,o=arguments.length;n\n
\n ").concat(i.get('name')||'',"\n
\n
\n
\n \n
\n
\n \n
\n
\n
\n ")).append(e.el);var l=(0,Z.a_)('div',{class:"".concat(o,"tools"),style:'pointer-events:none; display: none'},"\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n "));this.elTools=l;var c=null==r?void 0:r.toolsWrapper;return c&&c.appendChild(l),s&&s({el:a,elTop:a.querySelector('[data-frame-top]'),elRight:a.querySelector('[data-frame-right]'),elBottom:a.querySelector('[data-frame-bottom]'),elLeft:a.querySelector('[data-frame-left]'),frame:i,frameWrapperView:this,remove:this.remove,startDrag:this.startDrag}),this},n}(X);const ro=oo;var io=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),ao=function(t){function e(e,n){void 0===e&&(e={});var o=t.call(this,e,!0)||this;return o.listenTo(o.collection,'reset',o.render),o.canvasView=n.canvasView,o._module=n.module,o}return io(e,t),e.prototype.onRemoveBefore=function(t,e){void 0===e&&(e={}),t.forEach((function(t){return t.remove(e)}))},e.prototype.onRender=function(){var t=this.$el,e=this.ppfx;t.attr({class:"".concat(e,"frames")})},e.prototype.clearItems=function(){(this.viewCollection||[]).forEach((function(t){return t.remove()})),this.viewCollection=[]},e.prototype.renderView=function(t,e){return new ro(t,this.canvasView)},e}(tt);const so=ao;var lo=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),co=void 0&&(void 0).__assign||function(){return co=Object.assign||function(t){for(var e,n=1,o=arguments.length;n\n
\n \n
\n \n ")},o.prototype._onFramesUpdate=function(){this._initFrames(),this._renderFrames()},o.prototype._initFrames=function(){var t=this,e=t.frames,n=t.model,o=t.config,r=t.em,i=n.frames;r.set('readyCanvas',0),i.once('loaded:all',(function(){return r.set('readyCanvas',1)})),null==e||e.remove(),this.frames=new so({collection:i},co(co({},o),{canvasView:this}))},o.prototype.checkSelected=function(t,e){var n;void 0===e&&(e={});var o=e.scroll,r=this.em.getCurrentFrame();o&&(null===(n=t.views)||void 0===n||n.forEach((function(t){t.frameView===r&&t.scrollIntoView(o)})))},o.prototype.remove=function(){for(var t,e=[],n=0;n=T?T/2-S/2:-x),D=-y.y+P/2-O/2,L=l.getZoomDecimal(),I={x:(M+x)*L,y:(D+C)*L};if(b){var N=l.getZoomMultiplier(),R=(P*N-P)/2;I.y=(-y.y+C)*L-R/N}l.setCoords(I.x,I.y)},o.prototype.isElInViewport=function(t){var n=(0,e.getElement)(t),o=(0,Z.C8)(n),r=this.getFrameOffset(n),i=o.top,a=o.left;return i>=0&&a>=0&&i<=r.height&&a<=r.width},o.prototype.offset=function(t,e){void 0===e&&(e={});var n=e.noScroll,o=(0,Z.C8)(t),r=n?{x:0,y:0}:(0,Z.Xy)(t);return{top:o.top+r.y,left:o.left+r.x,width:o.width,height:o.height}},o.prototype.getRectToScreen=function(t){var e,n,o,r,i=this.getCanvasScroll(),a=this.module.getZoomDecimal(),s=this.module.getCoords(),l=this.getViewportDelta();return{x:(null!==(e=t.x)&&void 0!==e?e:0)*a-i.scrollLeft+s.x+l.x||0,y:(null!==(n=t.y)&&void 0!==n?n:0)*a-i.scrollTop+s.y+l.y||0,width:(null!==(o=t.width)&&void 0!==o?o:0)*a,height:(null!==(r=t.height)&&void 0!==r?r:0)*a}},o.prototype.getElBoxRect=function(t,n){var o,r,i;void 0===n&&(n={});var a=this.module,s=(0,Z.C8)(t),l=s.width,c=s.height,u=s.left,p=s.top,d=null===(o=(0,e.getComponentView)(t))||void 0===o?void 0:o.frameView,f=null==d?void 0:d.getBoxRect(),h=a.getZoomMultiplier(),v=null!==(r=null==f?void 0:f.x)&&void 0!==r?r:0,g=null!==(i=null==f?void 0:f.y)&&void 0!==i?i:0,y=this.el,m=(0,Z.Xy)(),b={x:u+v+(y.scrollLeft+m.x)*h,y:p+g+(y.scrollTop+m.y)*h,width:l,height:c};return n.local&&(b.x=u,b.y=p),n.toScreen?this.getRectToScreen(b):b},o.prototype.getViewportRect=function(t){void 0===t&&(t={});var e=this.getCanvasOffset(),n=e.top,o=e.left,r=e.width,i=e.height,a=this.module;if(t.toWorld){var s=a.getZoomMultiplier(),l=a.getCoords(),c=this.getViewportDelta();return{x:(-l.x-c.x||0)*s,y:(-l.y-c.y||0)*s,width:r*s,height:i*s}}return{x:o,y:n,width:r,height:i}},o.prototype.getViewportDelta=function(t){void 0===t&&(t={});var e=this.module.getZoomMultiplier(),n=this.getCanvasOffset(),o=n.width,r=n.height;return{x:(o*e-o)/2/e,y:(r*e-r)/2/e}},o.prototype.clearOff=function(){this.frmOff=void 0,this.cvsOff=void 0},o.prototype.getFrameOffset=function(t){var e;if(!this.frmOff||t){var n=null===(e=this.frame)||void 0===e?void 0:e.el,o=null==t?void 0:t.ownerDocument.defaultView,r=o?o.frameElement:n;this.frmOff=this.offset(r||n)}return this.frmOff},o.prototype.getCanvasOffset=function(){return this.cvsOff||(this.cvsOff=this.offset(this.el)),this.cvsOff},o.prototype.getElementPos=function(t,e){void 0===e&&(e={});var n=this.module.getZoomDecimal(),o=this.getFrameOffset(t),r=this.el,i=this.getCanvasOffset(),a=this.offset(t,e),s=e.avoidFrameOffset?0:o.top,l=e.avoidFrameOffset?0:o.left,c=e.avoidFrameZoom?a.top:a.top*n,u=e.avoidFrameZoom?a.left:a.left*n;return{top:e.avoidFrameOffset?c:c+s-i.top+r.scrollTop,left:e.avoidFrameOffset?u:u+l-i.left+r.scrollLeft,height:e.avoidFrameZoom?a.height:a.height*n,width:e.avoidFrameZoom?a.width:a.width*n,zoom:n,rect:a}},o.prototype.getElementOffsets=function(t){if(!t||(0,Z.ir)(t))return{};var e={},n=window.getComputedStyle(t),o=this.module.getZoomDecimal();return['marginTop','marginRight','marginBottom','marginLeft','paddingTop','paddingRight','paddingBottom','paddingLeft','borderTopWidth','borderRightWidth','borderBottomWidth','borderLeftWidth'].forEach((function(t){e[t]=parseFloat(n[t])*o})),e},o.prototype.getPosition=function(t){var e;void 0===t&&(t={});var n=null===(e=this.frame)||void 0===e?void 0:e.el.contentDocument;if(!n)return{top:0,left:0,width:0,height:0};var o=n.body,r=this.module.getZoomDecimal(),i=this.getFrameOffset(),a=this.getCanvasOffset(),s=t.noScroll;return{top:i.top+(s?0:o.scrollTop)*r-a.top,left:i.left+(s?0:o.scrollLeft)*r-a.left,width:a.width,height:a.height}},o.prototype.getCanvasScroll=function(){return this.config.scrollableCanvas?{scrollTop:this.el.scrollTop,scrollLeft:this.el.scrollLeft}:{scrollTop:0,scrollLeft:0}},o.prototype.updateScript=function(t){var e=t.model,n=e.getId(),o={component:e,view:t,el:t.el};if(!t.scriptContainer){t.scriptContainer=(0,Z.a_)('div',{'data-id':n});var r=this.getJsContainer();null==r||r.appendChild(t.scriptContainer)}t.el.id=n,t.scriptContainer.innerHTML='';var i=document.createElement('script'),a=e.getScriptString(),s=e.get('script-props')?a:"function(){\n".concat(a,"\n;}"),l=JSON.stringify(e.__getScriptProps());i.innerHTML="\n setTimeout(function() {\n var item = document.getElementById('".concat(n,"');\n if (!item) return;\n var script = (").concat(s,").bind(item);\n script(").concat(l,", { el: item });\n }, 1);"),setTimeout((function(){e.emitWithEditor($.I.scriptMountBefore,o);var n=t.scriptContainer;null==n||n.appendChild(i),e.emitWithEditor($.I.scriptMount,o)}),0)},o.prototype.getJsContainer=function(t){var e=this.getFrameView(t);return null==e?void 0:e.getJsContainer()},o.prototype.getFrameView=function(t){return(null==t?void 0:t.frameView)||this.em.getCurrentFrame()},o.prototype._renderFrames=function(){if(this.ready){var t=this,e=t.model,n=t.frames,o=t.em,r=t.framesArea,i=e.frames;i.listenToLoad(),n.render();var a=i.at(0),s=null==a?void 0:a.view;o.setCurrentFrame(s),null==r||r.appendChild(n.el),this.frame=s,this.updateFramesArea()}},o.prototype.renderFrames=function(){this._renderFrames()},o.prototype.render=function(){var t=this,n=t.el,o=t.$el,r=t.ppfx,i=t.config,a=t.em;o.html(this.template());var s=o.find('[data-frames]');this.framesArea=s.get(0);var l=o.find('[data-tools]');return this.toolsWrapper=l.get(0),l.append("\n
\n
\n
\n
\n
\n
\n ").concat(i.extHl?"
"):'',"\n
\n
\n
\n
\n
\n
\n
\n ")),this.toolsEl=n.querySelector("#".concat(r,"tools")),this.hlEl=n.querySelector(".".concat(r,"highlighter")),this.badgeEl=n.querySelector(".".concat(r,"badge")),this.placerEl=n.querySelector(".".concat(r,"placeholder")),this.ghostEl=n.querySelector(".".concat(r,"ghost")),this.toolbarEl=n.querySelector(".".concat(r,"toolbar")),this.resizerEl=n.querySelector(".".concat(r,"resizer")),this.offsetEl=n.querySelector(".".concat(r,"offset-v")),this.fixedOffsetEl=n.querySelector(".".concat(r,"offset-fixed-v")),this.toolsGlobEl=n.querySelector(".".concat(r,"tools-gl")),this.spotsEl=n.querySelector('[data-spots]'),this.cvStyle=n.querySelector('[data-canvas-style]'),n.className=(0,e.getUiClass)(a,this.className),!0===i.scrollableCanvas&&(n.style.overflow='auto'),this.ready=!0,this._renderFrames(),this},o}(X);const po=uo;var fo=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),ho=void 0&&(void 0).__assign||function(){return ho=Object.assign||function(t){for(var e,n=1,o=arguments.length;ni.top+i.height?i.top+i.height:f,left:d,elementTop:i.top,elementLeft:i.left,elementWidth:i.width,elementHeight:i.height,targetWidth:t.offsetWidth,targetHeight:t.offsetHeight,canvasTop:r.top,canvasLeft:r.left,canvasWidth:r.width,canvasHeight:r.height};return c&&this.em&&this.em.trigger(c,h),h}},o.prototype.canvasRectOffset=function(t,e,n){var o=this;void 0===n&&(n={});var r=function(t,e,r){void 0===e&&(e=1);var i=o.em.getZoomDecimal(),a=e?'top':'left',s=t.ownerDocument,l=n.offset?function(t){var e=t.defaultView;return null==e?void 0:e.frameElement}(s):{},c=l.offsetTop,u=void 0===c?0:c,p=l.offsetLeft,d=void 0===p?0:p,f=s.body||{},h=f.scrollTop,v=void 0===h?0:h,g=f.scrollLeft,y=e?v:void 0===g?0:g,m=e?u:d;return r[a]-(y-m)*i};return{top:r(t,1,e),left:r(t,0,e)}},o.prototype.getTargetToElementFixed=function(e,n,o){void 0===o&&(o={});var r=o.pos||this.getElementPos(e,{noScroll:!0}),i=o.canvasOff||this.canvasRectOffset(e,r),a=n.offsetHeight||0,s=n.offsetWidth||0,l=this.getCanvasView(),c=l.getCanvasScroll(),u=c.scrollTop,p=c.scrollLeft,d=l.getPosition(),f=o.event,h=r.width-s,v=-a,g=(0,t.isUndefined)(o.left)?h:o.left,y=Math.max(-r.left+p,0);g=Math.max(g,y);var m=r.width-s;g=Math.min(g,m);var b=d.width+p-s-r.left;g=Math.min(g,b);var _=v;if(i.top\n \n "),fallback:"\n \n "),file:''})},enumerable:!1,configurable:!0}),o.prototype.initToolbar=function(){n.prototype.initToolbar.call(this);var t=this.em;if(t){var e='image-editor';if(t.Commands.has(e)){for(var o=!1,r=this.get('toolbar'),i=0;i=0)&&delete r.editable}))}return r},o}(Vo);const Go=qo;var Ko=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Yo=void 0&&(void 0).__assign||function(){return Yo=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=0},n}(Mn);var _r=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),wr=void 0&&(void 0).__assign||function(){return wr=Object.assign||function(t){for(var e,n=1,o=arguments.length;n").concat(l).concat(s,""):s},n.prototype.__postAdd=function(){var t,n=null===(t=this.em)||void 0===t?void 0:t.UndoManager;return!this.__hasUm&&(null==n||n.add(this)),e.prototype.__postAdd.call(this)},n.prototype.__postRemove=function(){var t,n=null===(t=this.em)||void 0===t?void 0:t.UndoManager;return null==n||n.remove(this),e.prototype.__postRemove.call(this)},n.isComponent=function(){return!1},n}(Mn);const $r=Wr;var qr=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Gr=function(e){function n(){var t=null!==e&&e.apply(this,arguments)||this;return t.compView=Zr,t}return qr(n,e),n.prototype.initialize=function(t){this.opts=t||{},this.config=t.config||{},this.em=this.config.em;var e=this.collection;this.listenTo(e,'add',this.addTo),this.listenTo(e,'reset',this.resetChildren),this.listenTo(e,'remove',this.removeChildren)},n.prototype.removeChildren=function(t,e,n){var o=this;void 0===n&&(n={}),t.views.forEach((function(t){if(t){var e=t.childrenView,n=t.scriptContainer;e&&e.stopListening(),(0,Z.YZ)(n),t.remove.apply(t)}})),t.components().forEach((function(t){return o.removeChildren(t,e,n)}))},n.prototype.addTo=function(t){this.addToCollection(t,null,this.collection.indexOf(t))},n.prototype.addToCollection=function(e,n,o){for(var r=this,i=r.config,a=r.opts,s=r.em,l=i.frameView,c=(null==l?void 0:l.model)&&e.getView(l.model),u=a.componentTypes||(null==s?void 0:s.Components.getTypes()),p=e.get('type')||'default',d=this.compView,f=0;f=0&&l0&&u=0&&p0&&c<=s)},o.prototype.scrollIntoView=function(t){var e;if(void 0===t&&(t={}),!this.isInViewport()||t.force){var n=this.el;if('smooth'!==t.behavior){var o=this.getOffsetRect();null===(e=n.ownerDocument.defaultView)||void 0===e||e.scrollTo(0,o.top)}else n.scrollIntoView(Jr({behavior:'smooth',block:'nearest'},t))}},o.prototype.reset=function(){var t=this,e=t.el,n=t.model;t.scriptContainer&&n.emitWithEditor($.I.scriptUnmount,{component:n,view:t,el:e}),this.el='',this._ensureElement(),this._setData(),(0,Z.bG)(e,this.el),this.render()},o.prototype._setData=function(){var t=this.model,n=this.el,o=t.components();this.$el.data({model:t,collection:o,view:this}),(0,e.setViewEl)(n,this)},o.prototype._createElement=function(t){return this.createDoc.createElement(t)},o.prototype.renderChildren=function(){this.updateContent();var t=this.getChildrenContainer(),e=this.childrenView||new Kr({collection:this.model.get('components'),config:this.config,componentTypes:this.opts.componentTypes});e.render(t),this.childrenView=e;for(var n=Array.prototype.slice.call(e.el.childNodes),o=0,r=n.length;o0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]0&&(l=Math.max(0,s-i+1)),{startIndex:i,endIndex:s,totalItems:l,isArray:o}},o.prototype.ensureFirstChild=function(){var t=this.em.Components.getType(_t).model;return this.firstChild||new t({type:_t},this.opt)},o.prototype.listenToPropsChange=function(){var t=this;this.on("change:".concat(wt),(function(){t.rebuildChildrenFromCollection(),t.listenToDataSource()})),this.listenToDataSource()},o.prototype.removePropsListeners=function(){var t;this.off("change:".concat(wt)),null===(t=this.dataSourceWatcher)||void 0===t||t.destroy()},o.prototype.onCollectionsStateMapUpdate=function(t){var e=this;n.prototype.onCollectionsStateMapUpdate.call(this,t);var o=this.getDataSourceItems(),r=this.resolveCollectionConfig(o).startIndex;this.components().forEach((function(t,n){var i=e.getCollectionsStateMapForItem(o,r+n);t.onCollectionsStateMapUpdate(i)}))},o.prototype.stopSyncComponentCollectionState=function(){this.stopListening(this.components(),'add remove reset',this.syncOnComponentChange),this.onCollectionsStateMapUpdate({})},o.prototype.syncOnComponentChange=function(t,e,o){var r=this.collectionsStateMap;this.collectionsStateMap={},n.prototype.syncOnComponentChange.call(this,t,e,o),this.collectionsStateMap=r,this.onCollectionsStateMapUpdate(r)},Object.defineProperty(o.prototype,"collectionId",{get:function(){return this.getDataResolver().collectionId},enumerable:!1,configurable:!0}),o.isComponent=function(t){return(0,e.toLowerCase)(t.tagName)===bt},o.prototype.toJSON=function(t){var e,o=n.prototype.toJSON.call(this,t);delete o.droppable,delete o[Pn],null===(e=o.attributes)||void 0===e||delete e.id;var r=this.firstChild;return ha(ha({},o),{components:[r]})},o.prototype.destroy=function(t){return this.removePropsListeners(),n.prototype.destroy.call(this,t)},o}(Mn);const ya=ga;function ma(t,e){t.setSymbolOverride(['locked','layerable',Te]),t.syncComponentsCollectionState(),t.onCollectionsStateMapUpdate(e)}function ba(t,e,n){return!!t||(n.logError("The \"".concat(e,"\" property is required in the collection definition.")),!1)}function _a(t,e){var n=e.DataSources.getValue(t,[]);return Object.keys(n).map((function(e){return{type:ge,path:t+'.'+e}}))}var wa=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}();const xa=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wa(e,t),e}(Zr);var Ca=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Sa=void 0&&(void 0).__assign||function(){return Sa=Object.assign||function(t){for(var e,n=1,o=arguments.length;n-1;return Da(Da({},i),!f||h?{reason:ja.TargetReject}:{result:!0})},o.prototype.allById=function(){return this.componentsById},o.prototype.getById=function(t){return this.componentsById[t]||null},o.prototype.destroy=function(){var t,e=this.allById();Object.keys(e).forEach((function(t){return e[t]&&e[t].remove()})),null===(t=this.componentView)||void 0===t||t.remove(),[this.em,this.componentsById,this.componentView].forEach((function(t){return{}}))},o}(b);const Ra=Na;const Va=function(){return{stylePrefix:'css-',rules:[]}};var Fa=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Ha=Number.MAX_VALUE,Ua=function(n){function o(){var e=n.call(this)||this;return(0,t.bindAll)(e,'sortRules'),e.compCls=[],e.ids=[],e}return Fa(o,n),o.prototype.buildFromModel=function(t,e){var n=this;void 0===e&&(e={});var o='',r=this.em,i=r&&r.getConfig().avoidInlineStyle,a=t.styleToString(),s=t.classes;return this.ids.push("#".concat(t.getId())),s.forEach((function(t){return n.compCls.push(t.getFullName())})),!i&&a&&(o="#".concat(t.getId(),"{").concat(a,"}")),t.components().forEach((function(t){return o+=n.buildFromModel(t,e)})),o},o.prototype.build=function(n,o){var r=this;void 0===o&&(o={});var i=o.json,a=o.em,s=o.cssc||(null==a?void 0:a.Css);this.em=a,this.compCls=[],this.ids=[],this.model=n;var l=[],c=n?this.buildFromModel(n,o):'',u=(0,t.isUndefined)(o.clearStyles)&&a?a.getConfig().clearStyles:o.clearStyles;if(s){var p=o.rules||s.getAll(),d={},f=[];o.onlyMatched&&n&&(0,e.hasWin)()&&(p=this.matchedRules(n,p)),p.forEach((function(t){var e=t.getAtRule();if(e){var n=d[e];n?n.push(t):d[e]=[t]}else{var a=r.buildFromRule(t,f,o);i?l.push(a):c+=a}})),this.sortMediaObject(d).forEach((function(t){var e='',n=t.key;t.value.forEach((function(t){var a=r.buildFromRule(t,f,o);t.get('singleAtRule')?c+="".concat(n,"{").concat(a,"}"):e+=a,i&&l.push(a)})),e&&(c+="".concat(n,"{").concat(e,"}"))})),a&&u&&p.remove&&p.remove(f)}return i?l.filter((function(t){return t})):c},o.prototype.buildFromRule=function(t,e,n){var o,r=this;void 0===n&&(n={});var i,a='',s=this.model,l=t.selectorsToString({skipAdd:1}),c=t.get('selectorsAdd'),u=t.get('singleAtRule');if(null===(o=t.get('selectors'))||void 0===o||o.forEach((function(t){var e=t.getFullName();(r.compCls.indexOf(e)>=0||r.ids.indexOf(e)>=0||n.keepUnusedStyles)&&(i=1)})),l&&i||c||u||!s){var p=t.getDeclaration();p&&(n.json?a=t:a+=p)}else e.push(t);return a},o.prototype.matchedRules=function(t,e){var n=this,o=t.getEl(),r=[];return e.forEach((function(t){try{t.selectorsToString().split(',').some((function(t){return null==o?void 0:o.matches(n.__cleanSelector(t))}))&&r.push(t)}catch(t){}})),t.components().forEach((function(t){r=r.concat(n.matchedRules(t,e))})),r=r.filter((function(t,e){return r.indexOf(t)===e}))},o.prototype.getQueryLength=function(t){var e=/(-?\d*\.?\d+)\w{0,}/.exec(t);return e?parseFloat(e[1]):Ha},o.prototype.sortMediaObject=function(e){var n=this;void 0===e&&(e={});var o=[];return(0,t.each)(e,(function(t,e){return o.push({key:e,value:t})})),o.sort((function(t,e){var o=[t.key,e.key].every((function(t){return-1!==t.indexOf('min-width')})),r=o?t.key:e.key,i=o?e.key:t.key;return n.getQueryLength(r)-n.getQueryLength(i)}))},o.prototype.sortRules=function(t,e){var n=function(t){return t.get('mediaText')||''},o=[n(t),n(e)].every((function(t){return-1!==t.indexOf('min-width')})),r=n(o?t:e),i=n(o?e:t);return this.getQueryLength(r)-this.getQueryLength(i)},o.prototype.__cleanSelector=function(t){return t.split(' ').map((function(t){return t.split(':')[0]})).join(' ')},o}(u.Kx);const za=Ua;var Ba=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Wa=void 0&&(void 0).__assign||function(){return Wa=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=0}))},o.prototype.setIdRule=function(e,n,o){void 0===n&&(n={}),void 0===o&&(o={});var r=o.addOpts,i=void 0===r?{}:r,a=o.mediaText,s=o.state||'',l=(0,t.isUndefined)(a)?this.em.getCurrentMedia():a,c=this.em.Selectors.add({name:e,type:qe.TYPE_ID},i),u=this.add(c,s,l,{},i);return u.setStyle(n,Qa(Qa({},o),i)),u},o.prototype.getIdRule=function(e,n){void 0===n&&(n={});var o=n.mediaText,r=n.state||'',i=(0,t.isUndefined)(o)?this.em.getCurrentMedia():o,a=this.em.Selectors.get(e,qe.TYPE_ID);return a&&this.get(a,r,i)},o.prototype.setClassRule=function(t,e,n){void 0===e&&(e={}),void 0===n&&(n={});var o=n.state||'',r=n.mediaText||this.em.getCurrentMedia(),i=this.em.Selectors.add({name:t,type:qe.TYPE_CLASS}),a=this.add(i,o,r);return a.setStyle(e,n),a},o.prototype.getClassRule=function(t,e){void 0===e&&(e={});var n=e.state||'',o=e.mediaText||this.em.getCurrentMedia(),r=this.em.Selectors.get(t,qe.TYPE_CLASS);return r&&this.get(r,n,o)},o.prototype.remove=function(e,n){var o=(0,t.isString)(e)?this.getRules(e):e,r=this.getAll().remove(o,n);return(0,t.isArray)(r)?r:[r]},o.prototype.clear=function(t){return void 0===t&&(t={}),this.getAll().reset([],t),this},o.prototype.getComponentRules=function(e,n){void 0===n&&(n={});var o=n.state,r=n.mediaText;n.current&&(o=this.em.get('state')||'',r=this.em.getCurrentMedia());var i=e.getId();return this.getAll().filter((function(e){return!(!(0,t.isUndefined)(o)&&e.get('state')!==o)&&(!(!(0,t.isUndefined)(r)&&e.get('mediaText')!==r)&&e.getSelectorsString()==="#".concat(i))}))},o.prototype.render=function(){var t;return null===(t=this.rulesView)||void 0===t||t.remove(),this.rulesView=new ut({collection:this.rules,config:this.config}),this.rulesView.render().el},o.prototype.checkId=function(e,n){void 0===n&&(n={});var o=n.idMap,r=void 0===o?{}:o,i=[];return Object.keys(r).length?((Array.isArray(e)?e:[e]).forEach((function(e){var n=e.selectors;if(n&&1==n.length){var o=n[0];if((0,t.isString)(o)){if('#'===o[0]){var a=o.substring(1),s=r[a];a&&s&&(n[0]="#".concat(s),i.push(e))}}else if(o.name&&o.type===qe.TYPE_ID){(s=r[o.name])&&(o.name=s,i.push(e))}}})),i):i},o.prototype.destroy=function(){var t;this.rules.reset(),this.rules.stopListening(),null===(t=this.rulesView)||void 0===t||t.remove()},o}(b);const ns=es;const os=function(){return{appendTo:'',blocks:[],appendOnClick:!1,custom:!1}};var rs=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}();const is=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return rs(n,e),n.prototype.defaults=function(){return{label:'',content:'',media:'',category:'',activate:!1,select:void 0,resetId:!1,disable:!1,onClick:void 0,attributes:{},dragDef:{}}},Object.defineProperty(n.prototype,"category",{get:function(){var t=this.get('category');return t instanceof Qe?t:void 0},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"parent",{get:function(){return this.collection},enumerable:!1,configurable:!0}),n.prototype.getId=function(){return this.id},n.prototype.getLabel=function(){return this.get('label')},n.prototype.getMedia=function(){return this.get('media')},n.prototype.getContent=function(){return this.get('content')},n.prototype.getDragDef=function(){return this.get('dragDef')},n.prototype.getCategoryLabel=function(){var e=this.get('category');return(0,t.isFunction)(null==e?void 0:e.get)?e.get('label'):(null==e?void 0:e.label)?null==e?void 0:e.label:e},n}(u.Kx);var as=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),ss=function(t){function e(e,n){var o=t.call(this,e)||this;return o.em=n.em,o.on('add',o.handleAdd),o}return as(e,t),e.prototype.getCategories=function(){return this.em.Blocks.getCategories()},e.prototype.handleAdd=function(t){this.initCategory(t)},e}(on);const ls=ss;var cs;ss.prototype.model=is,function(t){t["add"]="block:add",t["remove"]="block:remove",t["removeBefore"]="block:remove:before",t["update"]="block:update",t["dragStart"]="block:drag:start",t["drag"]="block:drag",t["dragEnd"]="block:drag:stop",t["categoryUpdate"]="block:category:update",t["custom"]="block:custom",t["all"]="block"}(cs||(cs={}));var us=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),ps=void 0&&(void 0).__assign||function(){return ps=Object.assign||function(t){for(var e,n=1,o=arguments.length;n").concat(h,""):'',"\n
").concat(d,"
\n "),r.title=c.title||(null===(t=r.textContent)||void 0===t?void 0:t.trim()),r.setAttribute('draggable',"".concat(!(!(0,e.hasDnd)(o)||l)));var g=f&&f({el:r,model:s,className:p,prefix:a});return g&&(r.innerHTML=g),this},o}(u.Ss);const fs=ds;var hs=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),vs=void 0&&(void 0).__makeTemplateObject||function(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t},gs=function(t){function e(e,n,o){var r=t.call(this,e)||this;r.config=n;var i=n.pStylePrefix||'';return r.em=n.em,r.catName=o,r.pfx=i,r.caretR='fa fa-caret-right',r.caretD='fa fa-caret-down',r.iconClass="".concat(i,"caret-icon"),r.activeClass="".concat(i,"open"),r.className="".concat(i).concat(o,"-category"),r.listenTo(r.model,'change:open',r.updateVisibility),r.model.view=r,r}return hs(e,t),e.prototype.events=function(){return{'click [data-title]':'toggle'}},e.prototype.template=function(t){var e=t.pfx,n=t.label,o=t.catName;return r(ms||(ms=vs(["\n
\n \n ","\n
\n
\n "],["\n
\n \n ","\n
\n
\n "])),e,e,n,e,o)},e.prototype.attributes=function(){return this.model.get('attributes')||{}},e.prototype.updateVisibility=function(){this.model.get('open')?this.open():this.close()},e.prototype.open=function(){this.$el.addClass(this.activeClass),this.getIconEl().className="".concat(this.iconClass," ").concat(this.caretD),this.getTypeEl().style.display=''},e.prototype.close=function(){this.$el.removeClass(this.activeClass),this.getIconEl().className="".concat(this.iconClass," ").concat(this.caretR),this.getTypeEl().style.display='none'},e.prototype.toggle=function(){var t=this.model;t.set('open',!t.get('open'))},e.prototype.getIconEl=function(){return this.iconEl||(this.iconEl=this.el.querySelector(".".concat(this.iconClass))),this.iconEl},e.prototype.getTypeEl=function(){return this.typeEl||(this.typeEl=this.el.querySelector(".".concat(this.pfx).concat(this.catName,"s-c"))),this.typeEl},e.prototype.append=function(t){this.getTypeEl().appendChild(t)},e.prototype.render=function(){var t=this,e=t.em,n=t.el,o=t.$el,r=t.model,i=t.pfx,a=t.catName,s=e.t("".concat(a,"Manager.categories.").concat(r.id))||r.get('label');return n.innerHTML=this.template({pfx:i,label:s,catName:a}),o.addClass(this.className),o.css({order:r.get('order')}),this.updateVisibility(),this},e}(u.Ss);const ys=gs;var ms,bs=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),_s=void 0&&(void 0).__assign||function(){return _s=Object.assign||function(t){for(var e,n=1,o=arguments.length;n\n
\n
\n
\n "),this.collection.each((function(e){return t.add(e,n)})),this.append(n);var o="".concat(this.blockContClass,"s ").concat(e,"one-bg ").concat(e,"two-color");return this.$el.addClass(o),this.rendered=!0,this},n}(u.Ss);const xs=ws;var Cs=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Ss=void 0&&(void 0).__assign||function(){return Ss=Object.assign||function(t){for(var e,n=1,o=arguments.length;n',iconSync:'',iconTagOn:'',iconTagOff:'',iconTagRemove:'',componentFirst:!1,custom:!1}};var Es=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),ks=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Es(e,t),e.prototype.defaults=function(){return{name:'',label:''}},e.prototype.getName=function(){return this.get('name')},e.prototype.getLabel=function(){return this.get('label')||this.getName()},e}(u.Kx);const As=ks;ks.prototype.idAttribute='name';var js=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Ms=void 0&&(void 0).__makeTemplateObject||function(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t},Ds='contentEditable',Ls=function(t){function e(e){void 0===e&&(e={});var n=t.call(this,e)||this,o=e.config||{};return n.config=o,n.module=e.module,n.coll=e.coll||null,n.pfx=o.stylePrefix||'',n.ppfx=o.pStylePrefix||'',n.em=o.em,n.listenTo(n.model,'change:active',n.updateStatus),n}return js(e,t),e.prototype.template=function(){var t=this,e=t.pfx,n=t.model,o=t.config,i=n.get('label')||'';return r(Ns||(Ns=Ms(["\n \n ","\n $"," \n "],["\n \n ","\n $"," \n "])),e,e,e,i,e,e,o.iconTagRemove)},e.prototype.events=function(){return{'click [data-tag-remove]':'removeTag','click [data-tag-status]':'changeStatus','dblclick [data-tag-name]':'startEditTag','focusout [data-tag-name]':'endEditTag'}},e.prototype.getInputEl=function(){return this.inputEl||(this.inputEl=this.el.querySelector('[data-tag-name]')),this.inputEl},e.prototype.startEditTag=function(){var t=this.em,e=this.getInputEl();e[Ds]='true',e.focus(),null==t||t.setEditing(!0)},e.prototype.endEditTag=function(){var t=this.model,e=this.em,n=this.getInputEl(),o=n.textContent||'',r=null==e?void 0:e.Selectors;n[Ds]='false',null==e||e.setEditing(!1),r&&r.rename(t,o)!==t&&(n.innerText=t.getLabel())},e.prototype.changeStatus=function(){var t=this.model;t.set('active',!t.getActive())},e.prototype.removeTag=function(){this.module.removeSelected(this.model)},e.prototype.updateStatus=function(){var t=this,e=t.model,n=t.$el,o=t.config,r=o.iconTagOn,i=o.iconTagOff,a=n.find('[data-tag-status]');e.get('active')?(a.html(r),n.removeClass('opac50')):(a.html(i),n.addClass('opac50'))},e.prototype.render=function(){var t=this,e=t.pfx,n=t.ppfx,o=t.$el,r=t.model,i="".concat(e,"tag"),a=["".concat(i," ").concat(n,"three-bg")];return r.get('protected')&&a.push("".concat(i,"-protected")),o.html(this.template()),o.attr('class',a.join(' ')),this.updateStatus(),this},e}(u.Ss);const Is=Ls;var Ns,Rs=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Vs=void 0&&(void 0).__makeTemplateObject||function(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t},Fs=function(e){function n(n){void 0===n&&(n={});var o=e.call(this,n)||this;o.config=n.config||{},o.pfx=o.config.stylePrefix||'',o.ppfx=o.config.pStylePrefix||'',o.className=o.pfx+'tags',o.stateInputId=o.pfx+'states',o.stateInputC=o.pfx+'input-c',o.states=o.config.states||[];var r=o.config.em,i=o.collection;o.target=r;var a=r.Selectors;o.module=a,o.em=r,o.componentChanged=(0,t.debounce)(o.componentChanged.bind(o),0),o.checkSync=(0,t.debounce)(o.checkSync.bind(o),0);var s=$.I.update,l="".concat(s,":classes"),c="component:toggled ".concat(l),u="".concat(l," ").concat(s,":attributes:id change:state");return o.listenTo(r,c,o.componentChanged),o.listenTo(r,'styleManager:update',o.componentChanged),o.listenTo(r,u,o.__handleStateChange),o.listenTo(r,'styleable:change change:device',o.checkSync),o.listenTo(i,'add',o.addNew),o.listenTo(i,'reset',o.renderClasses),o.listenTo(i,'remove',o.tagRemoved),o.listenTo(a.getAll(),a.events.state,(0,t.debounce)((function(){return o.renderStates()}),0)),o.delegateEvents(),o}return Rs(n,e),n.prototype.template=function(t){var e=t.labelInfo,n=t.labelHead,o=t.iconSync,i=t.iconAdd,a=t.pfx,s=t.ppfx;return r(Us||(Us=Vs(["
\n
","
\n
\n \n
\n \n \n \n
\n
\n
\n
\n
\n
\n
\n
\n
\n \n $"," \n $"," \n
\n
\n
",":
\n
\n
"],["
\n
","
\n
\n \n
\n \n \n \n
\n
\n
\n
\n
\n
\n
\n
\n
\n \n $"," \n $"," \n
\n
\n
",":
\n
\n
"])),a,a,a,a,n,a,a,a,s,s,s,a,s,s,a,s,a,a,a,a,a,i,a,a,o,a,a,e,a)},n.prototype.events=function(){return{'change [data-states]':'stateChanged','click [data-add]':'startNewTag','focusout [data-input]':'endNewTag','keyup [data-input]':'onInputKeyUp','click [data-sync-style]':'syncStyle'}},n.prototype.syncStyle=function(){var t,e=this.em,n=this.getTarget(),o=e.Css,r=this.getCommonSelectors({opts:{noDisabled:1}}),i=e.get('state'),a=e.getCurrentMedia(),s=[],l=o.get(r,i,a)||o.add(r,i,a);this.getTargets().forEach((function(e){var n=o.getIdRule(e.getId(),{state:i,mediaText:a});t=n.getStyle(),n.setStyle({}),s.push(n)})),t&&l.addStyle(t),e.trigger('component:toggled'),e.trigger('component:sync-style',{component:n,selectors:r,mediaText:a,rule:l,ruleComponents:s,state:i})},n.prototype.tagRemoved=function(t){this.updateStateVis()},n.prototype.addNew=function(t){this.addToClasses(t)},n.prototype.startNewTag=function(){var t,e;null===(t=this.$addBtn)||void 0===t||t.css({display:'none'}),null===(e=this.$input)||void 0===e||e.show().focus()},n.prototype.endNewTag=function(){var t,e;null===(t=this.$addBtn)||void 0===t||t.css({display:''}),null===(e=this.$input)||void 0===e||e.hide().val('')},n.prototype.onInputKeyUp=function(t){var e;13===t.keyCode?(t.preventDefault(),this.addNewTag(null===(e=this.$input)||void 0===e?void 0:e.val())):27===t.keyCode&&this.endNewTag()},n.prototype.checkStates=function(){var t=this.em.getState(),e=this.getStates();e&&e.val(t)},n.prototype.componentChanged=function(t){var e=(void 0===t?{}:t).targets;this.updateSelection(e)},n.prototype.updateSelection=function(e){var n=e||this.getTargets(),o=[];return(n=(0,t.isArray)(n)?n:[n])&&n.length&&(o=this.getCommonSelectors({targets:n}),this.checkSync({validSelectors:o})),this.collection.reset(o),this.updateStateVis(n),this.module.__trgCustom(),o},n.prototype.getCommonSelectors=function(t){var e=void 0===t?{}:t,n=e.targets,o=e.opts,r=void 0===o?{}:o,i=n||this.getTargets();return this.module.__getCommonSelectors(i,r)},n.prototype._commonSelectors=function(){for(var t,e=[],n=0;n","
"],["",""])),i,e);else{var u=null==e?void 0:e.getSelectors();if(!u)return'';var p=u.getStyleable(),d=s.get('state'),f=e.getId?r(Bs||(Bs=Vs(["","\n #",""],["","\n #",""])),i,e.getName(),i,e.getId()):'';n=(n=this.collection.getFullString(p))?r(Ws||(Ws=Vs(["",""],["",""])),i,n):e.get('selectorsAdd')||f,n=c&&f?f:n,n+=d?r($s||($s=Vs([":",""],[":",""])),i,d):'',n=l?l({result:n,state:d,target:e}):n}return n&&"").concat(n,"")},n.prototype.stateChanged=function(t){var e=this.em,n=t.target.value;e.set('state',n)},n.prototype.addNewTag=function(t){var e=t.trim();e&&(this.module.addSelected({label:e}),this.endNewTag())},n.prototype.addToClasses=function(t,e){var n=e,o=this.getClasses(),r=new Is({model:t,config:this.config,coll:this.collection,module:this.module}).render().el;return n?n.appendChild(r):o.append(r),r},n.prototype.renderClasses=function(){var t=this,e=document.createDocumentFragment(),n=this.getClasses();n.empty(),this.collection.each((function(n){return t.addToClasses(n,e)})),n.append(e)},n.prototype.getClasses=function(){return this.$el.find('[data-selectors]')},n.prototype.getStates=function(){if(!this.$states){var t=this.$el.find('[data-states]');this.$states=t[0]&&t}return this.$states},n.prototype.getStatesC=function(){return this.$statesC||(this.$statesC=this.$el.find('#'+this.stateInputC)),this.$statesC},n.prototype.renderStates=function(){var t=this.module,e=this.em,n=e.t('selectorManager.emptyState'),o=t.getStates().map((function(t){var n=e.t("selectorManager.states.".concat(t.id))||t.getLabel()||t.id;return"")})).join(''),r=this.getStates();r&&r.html("").concat(o)),this.checkStates()},n.prototype.render=function(){var t=this,e=t.em,n=t.pfx,o=t.ppfx,r=t.config,i=t.$el,a=t.el,s=r.render,l={iconSync:r.iconSync,iconAdd:r.iconAdd,labelHead:e.t('selectorManager.label'),labelInfo:e.t('selectorManager.selected'),ppfx:o,pfx:n,el:a};i.html(this.template(l));var c=s&&s(l);return c&&c!==a&&i.empty().append(c),this.$input=i.find('[data-input]'),this.$addBtn=i.find('[data-add]'),this.$classes=i.find('#'+n+'tags-c'),this.$btnSyncEl=i.find('[data-sync-style]'),this.$input.hide(),this.renderStates(),this.renderClasses(),i.attr('class',"".concat(this.className," ").concat(o,"one-bg ").concat(o,"two-color")),this},n}(u.Ss);const Hs=Fs;var Us,zs,Bs,Ws,$s,qs=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Gs=void 0&&(void 0).__assign||function(){return Gs=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=0})):e.slice(1).reduce((function(e,n){return t.__common(e,n)}),e[0]):[]},o.prototype.__updateSelectedByComponents=function(){this.selected.reset(this.__getCommon())},o}(b);const sl=al;const ll=function(){return{textTags:['br','b','i','u','a','ul','ol'],textTypes:['text','textnode','comment'],parserCss:void 0,parserHtml:void 0,optionsHtml:{htmlType:'text/html',allowScripts:!1,allowUnsafeAttr:!1,allowUnsafeAttrValue:!1,keepEmptyTextNodes:!1,convertDataGjsAttributesHyphens:!1}}};var cl,ul=5,pl=6,dl=7,fl=11,hl=12,vl=13,gl=14,yl=15,ml=((cl={})[4]='media',cl[ul]='font-face',cl[pl]='page',cl[dl]='keyframes',cl[fl]='counter-style',cl[hl]='supports',cl[vl]='document',cl[gl]='font-feature-values',cl[yl]='viewport',cl),bl=(0,t.keys)(ml),_l=[ul,pl,fl,yl],wl=bl.filter((function(t){return _l.indexOf(Number(t))<0})).map((function(t){return ml[t]})).concat(['container','layer']),xl=_l.map((function(t){return ml[t]})),Cl=function(t){void 0===t&&(t='');for(var e=[],n=[],o=t.split(','),r=0,i=o.length;r=0&&(o.singleAtRule=!0),l&&(o.atRuleType=l),c&&(o.selectorsAdd=c),u&&(o.mediaText=u),s&&(t[r-1]=a[0],o.state=s,a.splice(a.length-1,1)),o.selectors=t,o.style=e,o},Pl=function(t){var e=t.cssText,n=void 0===e?'':e;return wl.find((function(t){return 0===n.indexOf("@".concat(t))}))},El=function(t){for(var e=[],n=t.cssRules||[],o=0,r=n.length;o=0;if(p)s=!0,l=ml[a],c=Ol(i);else if(bl.indexOf("".concat(a))>=0||!a&&Pl(i)){var d=El(i),f=ml[a]||Pl(i);c=Ol(i);for(var h=0,v=d.length;h0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]").concat(n,"")},o.prototype.templateInput=function(t){var e=this.clsField;return"
")},o.prototype.getClbOpts=function(){return{component:this.target,trait:this.model,elInput:this.getInputElem()}},o.prototype.removeView=function(){this.remove(),this.removed()},o.prototype.init=function(){},o.prototype.removed=function(){},o.prototype.onRender=function(t){},o.prototype.onUpdate=function(t){},o.prototype.onEvent=function(t){},o.prototype.onChange=function(e){var n=this.getInputElem();n&&!(0,t.isUndefined)(n.value)&&this.model.set('value',n.value),this.onEvent(mc(mc({},this.getClbOpts()),{event:e}))},o.prototype.getValueForTarget=function(){return this.model.get('value')},o.prototype.setInputValue=function(t){var e=this.getInputElem();e&&(e.value=t)},o.prototype.onValueChange=function(t,e,n){void 0===n&&(n={});var o=this.model,r=this.getValueForTarget();n.fromTarget?(this.setInputValue(r),this.postUpdate()):o.setValue(r,n)},o.prototype.renderLabel=function(){var t=this.$el,e=this.target,n=this.getLabel(),o=this.templateLabel(e);this.createLabel&&(o=this.createLabel({label:n,component:e,trait:this})||''),t.find('[data-label]').append(o)},o.prototype.getLabel=function(){var t=this.em,n=this.model.attributes,o=n.label,r=n.name;return t.t("traitManager.traits.labels.".concat(r))||(0,e.capitalize)(o||r).replace(/-/g,' ')},o.prototype.getComponent=function(){return this.target},o.prototype.getInputEl=function(){if(!this.$input){var e=this.em,n=this.model,o=n,r=n.attributes.name,i=o.get('placeholder')||o.get('default')||'',a=o.get('type')||'text',s=o.get('min'),c=o.get('max'),u=this.getModelValue(),p=(0,l["default"])("")),d=e.t("traitManager.traits.attributes.".concat(r))||{};p.attr(mc({placeholder:i},d)),(0,t.isUndefined)(u)||(o.set({value:u},{silent:!0}),p.prop('value',u)),s&&p.prop('min',s),c&&p.prop('max',c),this.$input=p}return this.$input.get(0)},o.prototype.getInputElem=function(){var t=this.input,e=this.$input;return t||e&&e.get&&e.get(0)||this.getElInput()},o.prototype.getModelValue=function(){return this.model.getValue()},o.prototype.getElInput=function(){return this.elInput},o.prototype.renderField=function(){var e=this,n=e.$el,o=e.appendInput,r=e.model,i=n.find('[data-input]'),a=i[i.length-1],s=r.el;s||(s=this.createInput?this.createInput(this.getClbOpts()):this.getInputEl()),(0,t.isString)(s)?(a.innerHTML=s,this.elInput=a.firstChild):(o?a.appendChild(s):a.insertBefore(s,a.firstChild),this.elInput=s),r.el=this.elInput},o.prototype.hasLabel=function(){var t=this.model.attributes.label;return!this.noLabel&&!1!==t},o.prototype.rerender=function(){delete this.model.el,this.render()},o.prototype.postUpdate=function(){this.onUpdate(this.getClbOpts())},o.prototype.render=function(){var e=this,n=e.$el,o=e.pfx,r=e.ppfx,i=e.model.attributes,a=i.type,s=i.id,l=this.hasLabel&&this.hasLabel(),c="".concat(o,"trait");delete this.$input;var u="
\n ").concat(l?"
"):'',"\n
\n ").concat(this.templateInput?(0,t.isFunction)(this.templateInput)?this.templateInput(this.getClbOpts()):this.templateInput:'',"\n
\n
");return n.empty().append(u),l&&this.renderLabel(),this.renderField(),this.el.className="".concat(c,"__wrp ").concat(c,"__wrp-").concat(s),this.postUpdate(),this.onRender(this.getClbOpts()),this},o}(u.Ss);const _c=bc;bc.prototype.eventCapture=['change'];var wc=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),xc=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wc(e,t),e.prototype.templateInput=function(){return''},e.prototype.onChange=function(){this.handleClick()},e.prototype.handleClick=function(){this.model.runCommand()},e.prototype.renderLabel=function(){this.model.get('label')&&_c.prototype.renderLabel.apply(this)},e.prototype.getInputEl=function(){var t=this.model,e=this.ppfx,n=t.props(),o=n.labelButton,r=n.text,i=n.full,a=o||r,s="".concat(e,"btn");return"")},e}(_c);const Cc=xc;xc.prototype.eventCapture=['click button'];var Sc=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}();const Oc=function(e){function n(){var t=null!==e&&e.apply(this,arguments)||this;return t.appendInput=!1,t}return Sc(n,e),n.prototype.templateInput=function(){var t=this.ppfx,e=this.clsField;return"")},n.prototype.onChange=function(){this.model.set('value',this.getInputElem().checked)},n.prototype.setInputValue=function(t){var e=this.getInputElem();e&&(e.checked=!!t)},n.prototype.getInputEl=function(){for(var e=[],n=0;n")},e.prototype.inputClass=function(){return"".concat(this.ppfx,"field")},e.prototype.holderClass=function(){return"".concat(this.ppfx,"input-holder")},e.prototype.elementUpdated=function(){this.model.trigger('el:change')},e.prototype.setValue=function(t,e){var n=this.model,o=t||n.get('defaults'),r=this.getInputEl();r&&(r.value=o)},e.prototype.handleModelChange=function(t,e,n){this.setValue(e,n)},e.prototype.handleChange=function(t){t.stopPropagation();var e=this.getInputEl().value;this.__onInputChange(e),this.elementUpdated()},e.prototype.__onInputChange=function(t){this.model.set({value:t},{fromInput:1})},e.prototype.getInputEl=function(){if(!this.inputEl){var t=this.model,e=this.opts.type||'text',n=t.get('placeholder')||t.get('defaults')||t.get('default')||'';this.inputEl=(0,l["default"])(""))}return this.inputEl.get(0)},e.prototype.render=function(){this.inputEl=null;var t=this.$el;return t.addClass(this.inputClass()),t.html(this.template()),t.find(".".concat(this.holderClass())).append(this.getInputEl()),this},e}(u.Ss);const Ec=Pc;Pc.prototype.events={change:'handleChange'};var kc=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Ac=void 0&&(void 0).__assign||function(){return Ac=Object.assign||function(t){for(var e,n=1,o=arguments.length;n","
","
",''].join(''),l=function(){var t='';if(i)for(var e=1;e<=6;e++)t+="
";return["
","
","
","
","",'
','
',"
","
","
","
","
","
","
","
",'
','
','
',"
",'
',"
","
",t,'
','
',"
",'
',"
","",'
',"
","
","","",'
','
','
'].join('')}(),c='spectrum.id';t.fn.spectrum=function(e,n){if('string'==typeof e){var o=this,i=Array.prototype.slice.call(arguments,1);return this.each((function(){var n=r[t(this).data(c)];if(n){var a=n[e];if(!a)throw new Error("Spectrum: no such method: '"+e+"'");'get'==e?o=n.get():'container'==e?o=n.container:'option'==e?o=n.option.apply(n,i):'destroy'==e?(n.destroy(),t(this).removeData(c)):a.apply(n,i)}})),o}return this.spectrum('destroy').each((function(){var n=T(this,t.extend({},e,t(this).data()));t(this).data(c,n.id)}))},t.fn.spectrum.load=!0,t.fn.spectrum.loadOpts={},t.fn.spectrum.draggable=A,t.fn.spectrum.defaults=o,t.fn.spectrum.inputTypeColorSupport=function e(){if(void 0===e._cachedResult){var n=t("")[0];e._cachedResult='color'===n.type&&''!==n.value}return e._cachedResult},t.spectrum={},t.spectrum.localization={},t.spectrum.palettes={},t.fn.spectrum.processNativeColorInputs=function(){var e=t('input[type=color]');e.length&&!j()&&e.spectrum({preferredFormat:'hex6'})};var u=/^[\s,#]+/,p=/\s+$/,d=0,f=Math,h=f.round,v=f.min,g=f.max,y=f.random,m=function(t,e){if(e=e||{},(t=t||'')instanceof m)return t;if(!(this instanceof m))return new m(t,e);var n=function(t){var e={r:0,g:0,b:0},n=1,o=!1,r=!1;'string'==typeof t&&(t=function(t){t=t.replace(u,'').replace(p,'').toLowerCase();var e,n=!1;if(x[t])t=x[t],n=!0;else if('transparent'==t)return{r:0,g:0,b:0,a:0,format:'name'};if(e=S.rgb.exec(t))return{r:e[1],g:e[2],b:e[3]};if(e=S.rgba.exec(t))return{r:e[1],g:e[2],b:e[3],a:e[4]};if(e=S.hsl.exec(t))return{h:e[1],s:e[2],l:e[3]};if(e=S.hsla.exec(t))return{h:e[1],s:e[2],l:e[3],a:e[4]};if(e=S.hsv.exec(t))return{h:e[1],s:e[2],v:e[3]};if(e=S.hsva.exec(t))return{h:e[1],s:e[2],v:e[3],a:e[4]};if(e=S.hex8.exec(t))return{a:et(e[1]),r:Z(e[2]),g:Z(e[3]),b:Z(e[4]),format:n?'name':'hex8'};if(e=S.hex6.exec(t))return{r:Z(e[1]),g:Z(e[2]),b:Z(e[3]),format:n?'name':'hex'};if(e=S.hex3.exec(t))return{r:Z(e[1]+''+e[1]),g:Z(e[2]+''+e[2]),b:Z(e[3]+''+e[3]),format:n?'name':'hex'};return!1}(t));'object'==typeof t&&(t.hasOwnProperty('r')&&t.hasOwnProperty('g')&&t.hasOwnProperty('b')?(i=t.r,a=t.g,s=t.b,e={r:255*J(i,255),g:255*J(a,255),b:255*J(s,255)},o=!0,r='%'===String(t.r).substr(-1)?'prgb':'rgb'):t.hasOwnProperty('h')&&t.hasOwnProperty('s')&&t.hasOwnProperty('v')?(t.s=tt(t.s),t.v=tt(t.v),e=function(t,e,n){t=6*J(t,360),e=J(e,100),n=J(n,100);var o=f.floor(t),r=t-o,i=n*(1-e),a=n*(1-r*e),s=n*(1-(1-r)*e),l=o%6,c=[n,a,i,i,s,n][l],u=[s,n,n,a,i,i][l],p=[i,i,s,n,n,a][l];return{r:255*c,g:255*u,b:255*p}}(t.h,t.s,t.v),o=!0,r='hsv'):t.hasOwnProperty('h')&&t.hasOwnProperty('s')&&t.hasOwnProperty('l')&&(t.s=tt(t.s),t.l=tt(t.l),e=function(t,e,n){var o,r,i;function a(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}if(t=J(t,360),e=J(e,100),n=J(n,100),0===e)o=r=i=n;else{var s=n<.5?n*(1+e):n+e-n*e,l=2*n-s;o=a(l,s,t+1/3),r=a(l,s,t),i=a(l,s,t-1/3)}return{r:255*o,g:255*r,b:255*i}}(t.h,t.s,t.l),o=!0,r='hsl'),t.hasOwnProperty('a')&&(n=t.a));var i,a,s;return n=Y(n),{ok:o,format:t.format||r,r:v(255,g(e.r,0)),g:v(255,g(e.g,0)),b:v(255,g(e.b,0)),a:n}}(t);this._originalInput=t,this._r=n.r,this._g=n.g,this._b=n.b,this._a=n.a,this._roundA=h(100*this._a)/100,this._format=e.format||n.format,this._gradientType=e.gradientType,this._r<1&&(this._r=h(this._r)),this._g<1&&(this._g=h(this._g)),this._b<1&&(this._b=h(this._b)),this._ok=n.ok,this._tc_id=d++};m.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},setAlpha:function(t){return this._a=Y(t),this._roundA=h(100*this._a)/100,this},toHsv:function(){var t=D(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=D(this._r,this._g,this._b),e=h(360*t.h),n=h(100*t.s),o=h(100*t.v);return 1==this._a?'hsv('+e+', '+n+'%, '+o+'%)':'hsva('+e+', '+n+'%, '+o+'%, '+this._roundA+')'},toHsl:function(){var t=M(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=M(this._r,this._g,this._b),e=h(360*t.h),n=h(100*t.s),o=h(100*t.l);return 1==this._a?'hsl('+e+', '+n+'%, '+o+'%)':'hsla('+e+', '+n+'%, '+o+'%, '+this._roundA+')'},toHex:function(t){return L(this._r,this._g,this._b,t)},toHexString:function(t){return'#'+this.toHex(t)},toHex8:function(){return I(this._r,this._g,this._b,this._a)},toHex8String:function(){return'#'+this.toHex8()},toRgb:function(){return{r:h(this._r),g:h(this._g),b:h(this._b),a:this._a}},toRgbString:function(){return 1==this._a?'rgb('+h(this._r)+', '+h(this._g)+', '+h(this._b)+')':'rgba('+h(this._r)+', '+h(this._g)+', '+h(this._b)+', '+this._roundA+')'},toPercentageRgb:function(){return{r:h(100*J(this._r,255))+'%',g:h(100*J(this._g,255))+'%',b:h(100*J(this._b,255))+'%',a:this._a}},toPercentageRgbString:function(){return 1==this._a?'rgb('+h(100*J(this._r,255))+'%, '+h(100*J(this._g,255))+'%, '+h(100*J(this._b,255))+'%)':'rgba('+h(100*J(this._r,255))+'%, '+h(100*J(this._g,255))+'%, '+h(100*J(this._b,255))+'%, '+this._roundA+')'},toName:function(){return 0===this._a?'transparent':!(this._a<1)&&(C[L(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e='#'+I(this._r,this._g,this._b,this._a),n=e,o=this._gradientType?'GradientType = 1, ':'';t&&(n=m(t).toHex8String());return'progid:DXImageTransform.Microsoft.gradient('+o+'startColorstr='+e+',endColorstr='+n+')'},toString:function(t){var e=!!t;t=t||this._format;var n=!1,o=this._a<1&&this._a>=0;return e||!o||'hex'!==t&&'hex6'!==t&&'hex3'!==t&&'name'!==t?('rgb'===t&&(n=this.toRgbString()),'prgb'===t&&(n=this.toPercentageRgbString()),'hex'!==t&&'hex6'!==t||(n=this.toHexString()),'hex3'===t&&(n=this.toHexString(!0)),'hex8'===t&&(n=this.toHex8String()),'name'===t&&(n=this.toName()),'hsl'===t&&(n=this.toHslString()),'hsv'===t&&(n=this.toHsvString()),n||this.toHexString()):'name'===t&&0===this._a?this.toName():this.toRgbString()},_applyModification:function(t,e){var n=t.apply(null,[this].concat([].slice.call(e)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(F,arguments)},brighten:function(){return this._applyModification(H,arguments)},darken:function(){return this._applyModification(U,arguments)},desaturate:function(){return this._applyModification(N,arguments)},saturate:function(){return this._applyModification(R,arguments)},greyscale:function(){return this._applyModification(V,arguments)},spin:function(){return this._applyModification(z,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(G,arguments)},complement:function(){return this._applyCombination(B,arguments)},monochromatic:function(){return this._applyCombination(K,arguments)},splitcomplement:function(){return this._applyCombination(q,arguments)},triad:function(){return this._applyCombination(W,arguments)},tetrad:function(){return this._applyCombination($,arguments)}},m.fromRatio=function(t,e){if('object'==typeof t){var n={};for(var o in t)t.hasOwnProperty(o)&&(n[o]='a'===o?t[o]:tt(t[o]));t=n}return m(t,e)},m.equals=function(t,e){return!(!t||!e)&&m(t).toRgbString()==m(e).toRgbString()},m.random=function(){return m.fromRatio({r:y(),g:y(),b:y()})},m.mix=function(t,e,n){n=0===n?0:n||50;var o,r=m(t).toRgb(),i=m(e).toRgb(),a=n/100,s=2*a-1,l=i.a-r.a,c=1-(o=((o=s*l==-1?s:(s+l)/(1+s*l))+1)/2),u={r:i.r*o+r.r*c,g:i.g*o+r.g*c,b:i.b*o+r.b*c,a:i.a*a+r.a*(1-a)};return m(u)},m.readability=function(t,e){var n=m(t),o=m(e),r=n.toRgb(),i=o.toRgb(),a=n.getBrightness(),s=o.getBrightness(),l=Math.max(r.r,i.r)-Math.min(r.r,i.r)+Math.max(r.g,i.g)-Math.min(r.g,i.g)+Math.max(r.b,i.b)-Math.min(r.b,i.b);return{brightness:Math.abs(a-s),color:l}},m.isReadable=function(t,e){var n=m.readability(t,e);return n.brightness>125&&n.color>500},m.mostReadable=function(t,e){for(var n=null,o=0,r=!1,i=0;i125&&a.color>500,l=3*(a.brightness/125)+a.color/500;(s&&!r||s&&r&&l>o||!s&&!r&&l>o)&&(r=s,o=l,n=m(e[i]))}return n};var b,_,w,x=m.names={aliceblue:'f0f8ff',antiquewhite:'faebd7',aqua:'0ff',aquamarine:'7fffd4',azure:'f0ffff',beige:'f5f5dc',bisque:'ffe4c4',black:'000',blanchedalmond:'ffebcd',blue:'00f',blueviolet:'8a2be2',brown:'a52a2a',burlywood:'deb887',burntsienna:'ea7e5d',cadetblue:'5f9ea0',chartreuse:'7fff00',chocolate:'d2691e',coral:'ff7f50',cornflowerblue:'6495ed',cornsilk:'fff8dc',crimson:'dc143c',cyan:'0ff',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:'f0f',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:'789',lightslategrey:'789',lightsteelblue:'b0c4de',lightyellow:'ffffe0',lime:'0f0',limegreen:'32cd32',linen:'faf0e6',magenta:'f0f',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:'f00',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:'fff',whitesmoke:'f5f5f5',yellow:'ff0',yellowgreen:'9acd32'},C=m.hexNames=function(t){var e={};for(var n in t)t.hasOwnProperty(n)&&(e[t[n]]=n);return e}(x),S=(_='[\\s|\\(]+('+(b='(?:'+'[-\\+]?\\d*\\.\\d+%?'+')|(?:'+'[-\\+]?\\d+%?'+')')+')[,|\\s]+('+b+')[,|\\s]+('+b+')\\s*\\)?',w='[\\s|\\(]+('+b+')[,|\\s]+('+b+')[,|\\s]+('+b+')[,|\\s]+('+b+')\\s*\\)?',{rgb:new RegExp('rgb'+_),rgba:new RegExp('rgba'+w),hsl:new RegExp('hsl'+_),hsla:new RegExp('hsla'+w),hsv:new RegExp('hsv'+_),hsva:new RegExp('hsva'+w),hex3:/^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex8:/^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});window.tinycolor=m,t((function(){t.fn.spectrum.load&&t.fn.spectrum.processNativeColorInputs()}))}function O(e,n,o,r){for(var i=[],s=0;s')}else{i.push(t('
').append(t('').attr('title',r.noColorSelectedText)).html())}}return"
"+i.join('')+'
'}function T(e,c){var u,p,d,f,h=function(e,n){var r=t.extend({},o,e);return r.callbacks={move:k(r.move,n),change:k(r.change,n),show:k(r.show,n),hide:k(r.hide,n),beforeShow:k(r.beforeShow,n)},r}(c,e),v=h.flat,g=h.showSelectionPalette,y=h.localStorageKey,b=h.theme,_=h.callbacks,w=(u=$t,p=10,function(){var t=this,e=arguments,n=function(){f=null,u.apply(t,e)};d&&clearTimeout(f),!d&&f||(f=setTimeout(n,p))}),x=!1,C=!1,S=!0,T=0,P=0,M=0,D=0,L=0,I=0,N=0,R=0,V=0,F=0,H=1,U=[],z=[],B={},W=h.selectionPalette.slice(0),$=h.maxSelectionSize,q='sp-dragging',G=null,K=e.ownerDocument,Y=(K.body,t(e)),J=!1,X=t(l,K).addClass(b),Z=X.find('.sp-picker-container'),Q=X.find('.sp-color'),tt=X.find('.sp-dragger'),et=X.find('.sp-hue'),nt=X.find('.sp-slider'),ot=X.find('.sp-alpha-inner'),rt=X.find('.sp-alpha'),it=X.find('.sp-alpha-handle'),at=X.find('.sp-input'),st=X.find('.sp-palette'),lt=X.find('.sp-initial'),ct=X.find('.sp-cancel'),ut=X.find('.sp-clear'),pt=X.find('.sp-choose'),dt=X.find('.sp-palette-toggle'),ft=Y.is('input'),ht=ft&&'color'===Y.attr('type')&&j(),vt=ft&&!v,gt=vt?t(s).addClass(b).addClass(h.className).addClass(h.replacerClassName):t([]),yt=vt?gt:Y,mt=gt.find('.sp-preview-inner'),bt=h.color||ft&&Y.val(),_t=!1,wt=h.preferredFormat,xt=!h.showButtons||h.clickoutFiresChange,Ct=!bt,St=h.allowEmpty&&!ht;function Ot(){if(h.showPaletteOnly&&(h.showPalette=!0),dt.text(h.showPaletteOnly?h.togglePaletteMoreText:h.togglePaletteLessText),h.palette){U=h.palette.slice(0),z=t.isArray(U[0])?U:[U],B={};for(var e=0;e1&&(delete window.localStorage[y],t.each(e,(function(t,e){Pt(e)})))}catch(t){}try{W=window.localStorage[y].split(';')}catch(t){}}}function Pt(e){if(g){var n=m(e).toRgbString();if(!B[n]&&-1===t.inArray(n,W))for(W.push(n);W.length>$;)W.shift();if(y&&window.localStorage)try{window.localStorage[y]=W.join(';')}catch(t){}}}function Et(){var e=Ht(),n=t.map(z,(function(t,n){return O(t,e,'sp-palette-row sp-palette-row-'+n,h)}));Tt(),W&&n.push(O(function(){var t=[];if(h.showPalette)for(var e=0;ewindow.innerWidth-window.scrollX&&i.right-a>0&&(l.left-=a-l.width);i.bottom+sMath.abs(e-r);G=i?'x':'y'}}else G=null;var a=!G||'y'===G;(!G||'x'===G)&&(V=parseFloat(t/T)),a&&(F=parseFloat((P-e)/P)),Ct=!1,h.showAlpha||(H=1),Ut()}),At,jt),bt?(Ft(bt),zt(),wt=h.preferredFormat||m(bt).getFormat(),Pt(bt)):zt(),v&&Lt();var o=i?'mousedown.spectrum':'click.spectrum touchstart.spectrum';st.delegate('.sp-thumb-el',o,n),lt.delegate('.sp-thumb-el:nth-child(1)',o,{ignore:!0},n)}();var Gt={show:Lt,hide:Rt,toggle:Dt,reflow:$t,option:function(e,o){return e===n?t.extend({},h):o===n?h[e]:(h[e]=o,'preferredFormat'===e&&(wt=h.preferredFormat),void Ot())},enable:function(){J=!1,Y.attr('disabled',!1),yt.removeClass('sp-disabled')},disable:qt,offset:function(t){h.offset=t,$t()},set:function(t){Ft(t),Wt()},get:Ht,destroy:function(){Y.show(),yt.unbind('click.spectrum touchstart.spectrum'),X.remove(),gt.remove(),r[Gt.id]=null},container:X};return Gt.id=r.push(Gt)-1,Gt}function P(){}function E(t){t.stopPropagation()}function k(t,e){var n=Array.prototype.slice,o=n.call(arguments,2);return function(){return t.apply(e,o.concat(n.call(arguments)))}}function A(e,n,o,r){n=n||function(){},o=o||function(){},r=r||function(){};var a=document,s=!1,l={},c=0,u=0,p='ontouchstart'in window,d={};function f(t){t.stopPropagation&&t.stopPropagation(),t.preventDefault&&t.preventDefault(),t.returnValue=!1}function h(t){if(s){if(i&&a.documentMode<9&&!t.button)return v();var o=t&&t.touches&&t.touches[0],r=o&&o.pageX||t.pageX,d=o&&o.pageY||t.pageY,h=Math.max(0,Math.min(r-l.left,u)),g=Math.max(0,Math.min(d-l.top,c));p&&f(t),n.apply(e,[h,g,t])}}function v(){s&&(t(a).unbind(d),t(a.body).removeClass('sp-dragging'),setTimeout((function(){r.apply(e,arguments)}),0)),s=!1}d['selectstart']=f,d['dragstart']=f,d['touchmove mousemove']=h,d['touchend mouseup']=v,t(e).bind('touchstart mousedown',(function(n){(n.which?3==n.which:2==n.button)||s||!1!==o.apply(e,arguments)&&(s=!0,c=t(e).height(),u=t(e).width(),l=t(e).offset(),t(a).bind(d),t(a.body).addClass('sp-dragging'),h(n),f(n))}))}function j(){return t.fn.spectrum.inputTypeColorSupport()}function M(t,e,n){t=J(t,255),e=J(e,255),n=J(n,255);var o,r,i=g(t,e,n),a=v(t,e,n),s=(i+a)/2;if(i==a)o=r=0;else{var l=i-a;switch(r=s>.5?l/(2-i-a):l/(i+a),i){case t:o=(e-n)/l+(e>1)+720)%360;--e;)o.h=(o.h+r)%360,i.push(m(o));return i}function K(t,e){e=e||6;for(var n=m(t).toHsv(),o=n.h,r=n.s,i=n.v,a=[],s=1/e;e--;)a.push(m({h:o,s:r,v:i})),i=(i+s)%1;return a}function Y(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function J(t,e){(function(t){return'string'==typeof t&&-1!=t.indexOf('.')&&1===parseFloat(t)})(t)&&(t='100%');var n=function(t){return'string'==typeof t&&-1!=t.indexOf('%')}(t);return t=v(e,g(0,parseFloat(t))),n&&(t=parseInt(t*e,10)/100),f.abs(t-e)<1e-6?1:t%e/parseFloat(e)}function X(t){return v(1,g(0,t))}function Z(t){return parseInt(t,16)}function Q(t){return 1==t.length?'0'+t:''+t}function tt(t){return t<=1&&(t=100*t+'%'),t}function et(t){return Z(t)/255}}(l["default"]);var jc=function(t){var e='name'===t.getFormat()&&t.toName(),n=1==t.getAlpha()?t.toHexString():t.toRgbString();return e||n.replace(/ /g,'')},Mc=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return kc(n,e),n.prototype.template=function(){var t=this.ppfx;return"\n
\n
\n
\n
\n
\n
\n ")},n.prototype.inputClass=function(){var t=this.ppfx;return"".concat(t,"field ").concat(t,"field-color")},n.prototype.holderClass=function(){return"".concat(this.ppfx,"input-holder")},n.prototype.remove=function(){return e.prototype.remove.call(this),this.colorEl.spectrum('destroy'),this},n.prototype.handleChange=function(e){e.stopPropagation();var n=e.target.value;(0,t.isUndefined)(n)||this.__onInputChange(n)},n.prototype.__onInputChange=function(t){var e=this.model,n=this.opts.onChange,o=t,r=this.getColorEl();if(r){r.spectrum('set',o);var i=r.spectrum('get'),a=o&&jc(i);a&&(o=a)}n?n(o):e.set({value:o},{fromInput:1})},n.prototype.setValue=function(e,n){void 0===n&&(n={});var o=this.model,r=(0,t.isUndefined)(n.def)?o.get('defaults'):n.def,i=(0,t.isUndefined)(e)?(0,t.isUndefined)(r)?'':r:e,a=this.getInputEl(),s=this.getColorEl(),l='none'!=i?i:'';a.value=i,s.get(0).style.backgroundColor=l,(n.fromTarget||n.fromInput&&!n.avoidStore)&&(s.spectrum('set',l),this.noneColor='none'==i,this.movedColor=l)},n.prototype.getColorEl=function(){var t=this;if(!this.colorEl){var e=this,n=e.em,o=e.model,r=e.opts,i=this.ppfx,a=r.onChange,s=(0,l["default"])("
")),c=s.get(0).style,u=n&&n.getConfig&&n.getConfig().colorPicker||{};this.movedColor='';var p,d=!1;this.$el.find('[data-colorp-c]').append(s);var f=function(t,e){void 0===e&&(e=!0),a?a(t,!e):(e&&o.setValueFromInput(0,!1),o.setValueFromInput(t,e))};s.spectrum(Ac(Ac(Ac({color:o.getValue()||!1,containerClassName:"".concat(i,"one-bg ").concat(i,"two-color ").concat(i,"editor-sp"),maxSelectionSize:8,showPalette:!0,showAlpha:!0,chooseText:'Ok',cancelText:'⨯',palette:[]},u),o.get('colorPicker')||{}),{move:function(e){var n=jc(e);t.movedColor=n,c.backgroundColor=n,f(n,!1)},change:function(e){d=!0;var n=jc(e);c.backgroundColor=n,f(n),t.noneColor=!1},show:function(e){d=!1,t.movedColor='',p=a?o.getValue({noDefault:!0}):jc(e)},hide:function(){d||!p&&!a||(t.noneColor&&(p=''),c.backgroundColor=p,s.spectrum('set',p),f(p,!1))}})),n&&n.on&&this.listenTo(n,'component:selected',(function(){t.movedColor&&f(t.movedColor),d=!0,t.movedColor='',s.spectrum('hide')})),this.colorEl=s}return this.colorEl},n.prototype.render=function(){return Ec.prototype.render.call(this),this.getColorEl(),this},n}(Ec);const Dc=Mc;var Lc=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}();const Ic=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Lc(e,t),e.prototype.templateInput=function(){return''},e.prototype.getInputEl=function(){if(!this.input){var t=this.model,e=this.getModelValue(),n=new Dc({model:t,target:this.config.em,contClass:this.ppfx+'field-color',ppfx:this.ppfx}).render();n.setValue(e,{fromTarget:1}),this.input=n.el}return this.input},e}(_c);var Nc=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Rc=function(e){function n(n){void 0===n&&(n={});var o=e.call(this,n)||this;return(0,t.bindAll)(o,'moveIncrement','upIncrement'),o.doc=document,o.listenTo(o.model,'change:unit',o.handleModelChange),o}return Nc(n,e),n.prototype.template=function(){var t=this.ppfx;return"\n \n \n
\n
\n
\n
\n ")},n.prototype.inputClass=function(){var t=this.ppfx;return this.opts.contClass||"".concat(t,"field ").concat(t,"field-integer")},n.prototype.setValue=function(t,e){var n=e||{},o=this.validateInputValue(t,{deepCheck:1}),r={value:o.value,unit:''};(o.unit||o.force)&&(r.unit=o.unit),this.model.set(r,n),n.silent&&this.handleModelChange()},n.prototype.handleChange=function(t){t.stopPropagation(),this.setValue(this.getInputEl().value),this.elementUpdated()},n.prototype.handleUnitChange=function(t){t.stopPropagation();var e=this.getUnitEl().value;this.model.set('unit',e),this.elementUpdated()},n.prototype.handleKeyDown=function(t){'ArrowUp'===t.key&&(t.preventDefault(),this.upArrowClick()),'ArrowDown'===t.key&&(t.preventDefault(),this.downArrowClick())},n.prototype.elementUpdated=function(){this.model.trigger('el:change')},n.prototype.handleModelChange=function(){var t=this.model;this.getInputEl().value=t.get('value');var e=this.getUnitEl();e&&(e.value=t.get('unit')||'')},n.prototype.getUnitEl=function(){if(!this.unitEl){var t=this.model,e=t.get('units')||[];if(e.length){var n=[''];e.forEach((function(e){var o=e==t.get('unit')?'selected':'';n.push(""))}));var o=document.createElement('div');o.innerHTML=""),this.unitEl=o.firstChild}}return this.unitEl},n.prototype.upArrowClick=function(){var t=this.model.get('step'),e=parseFloat(this.getInputEl().value);this.setValue(this.normalizeValue(e+t)),this.elementUpdated()},n.prototype.downArrowClick=function(){var t=this.model.get('step'),e=parseFloat(this.getInputEl().value);this.setValue(this.normalizeValue(e-t)),this.elementUpdated()},n.prototype.downIncrement=function(t){t.preventDefault(),this.moved=!1;var e=this.model.get('value')||0;e=this.normalizeValue(e),this.current={y:t.pageY,val:e},(0,Z.on)(this.doc,'mousemove',this.moveIncrement),(0,Z.on)(this.doc,'mouseup',this.upIncrement)},n.prototype.moveIncrement=function(t){this.moved=!0;var e=this.model,n=e.get('step'),o=this.current,r=this.normalizeValue(o.val+(o.y-t.pageY)*n),i=this.validateInputValue(r),a=i.value,s=i.unit;return this.prValue=a,e.set({value:a,unit:s},{avoidStore:1}),!1},n.prototype.upIncrement=function(){var t=this.model,e=t.get('step');if((0,Z.AU)(this.doc,'mouseup',this.upIncrement),(0,Z.AU)(this.doc,'mousemove',this.moveIncrement),this.prValue&&this.moved){var n=this.prValue-e;t.set('value',n,{avoidStore:1}).set('value',n+e),this.elementUpdated()}},n.prototype.normalizeValue=function(t,e){void 0===e&&(e=0);var n=this.model.get('step'),o=0;if(isNaN(t))return e;if(t=parseFloat(t),Math.floor(t)!==t){var r=n.toString().split('.')[1];o=r?r.length:0}return o?parseFloat(t.toFixed(o)):t},n.prototype.validateInputValue=function(e,n){void 0===n&&(n={});var o=0,r=n||{},i=this.model,a='',s=(0,t.isUndefined)(e)?a:e,l=n.units||i.get('units')||[],c=i.get('unit')||l.length&&l[0]||'',u=(0,t.isUndefined)(n.max)?i.get('max'):n.max,p=(0,t.isUndefined)(n.min)?i.get('min'):n.min,d=!!i.get('limitlessMax'),f=!!i.get('limitlessMin');if(r.deepCheck){var h=i.get('fixedValues')||[];if(''===s&&(c=''),s){var v=new RegExp('^'+h.join('|'),'g');if(h.length&&v.test(s))s=s.match(v)[0],c='',o=1;else{var g=s+'';s+='',s=parseFloat(s.replace(',','.')),s=isNaN(s)?a:s;var y=g.replace(s,'');(0,t.indexOf)(l,y)>=0&&(c=y)}}}return isNaN(s)||''===s||(d||(0,t.isUndefined)(u)||''===u||(s=s>u?u:s),f||(0,t.isUndefined)(p)||''===p||(s=s\n
\n
\n
\n
\n
")},n.prototype.getInputEl=function(){if(!this.$input){var e=this.model,n=this.em,o=e.get('name'),r=e.get('options')||[],i=[],a='',this.$input=(0,l["default"])(a);var s=e.getTargetValue(),c=i.indexOf(s)>=0?s:e.get('default');!(0,t.isUndefined)(c)&&this.$input.val(c)}return this.$input.get(0)},n}(_c);var Wc=n(8242),$c=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),qc='data-categories',Gc='data-no-categories',Kc=function(t){function e(e,n){var o=t.call(this,e)||this;o.reuseView=!0,o.renderedCategories=new Map,o.itemsView=n;var r=e.config||{};o.config=r;var i=e.editor;o.em=i;var a=r.pStylePrefix||'';return o.ppfx=a,o.pfx=a+r.stylePrefix||'',o.className="".concat(o.pfx,"traits"),o.traitContClass="".concat(a,"traits-c"),o.classNoCat="".concat(a,"traits-empty-c"),o.catsClass="".concat(a,"trait-categories"),o.collection=new mn([],{em:i}),o.listenTo(i,'component:toggled',o.updatedCollection),o.updatedCollection(),o}return $c(e,t),e.prototype.updatedCollection=function(){var t=this.ppfx,e=this.em,n=e.getSelected();this.el.className="".concat(this.traitContClass,"s ").concat(t,"one-bg ").concat(t,"two-color"),this.collection=(null==n?void 0:n.traits)||new mn([],{em:e}),this.render()},e.prototype.add=function(t,e){var n=this.config,o=this.renderedCategories,r=this.itemView,i=t.get(this.itemType);this.itemsView&&this.itemsView[i]&&(r=this.itemsView[i]);var a=new r({config:n,model:t,attributes:t.get('attributes')}).render().el,s=t.parent.initCategory(t);if(s){var l=s.getId(),c=this.getCategoriesEl(),u=o.get(l);return!u&&c&&(u=new ys({model:s},n,'trait').render(),o.set(l,u),c.appendChild(u.el)),void(null==u||u.append(a))}e?e.appendChild(a):this.append(a)},e.prototype.getCategoriesEl=function(){return this.catsEl||(this.catsEl=this.el.querySelector("[".concat(qc,"]"))),this.catsEl},e.prototype.getTraitsEl=function(){return this.traitsEl||(this.traitsEl=this.el.querySelector("[".concat(Gc,"]"))),this.traitsEl},e.prototype.append=function(t){var e=this.getTraitsEl();null==e||e.appendChild(t)},e.prototype.render=function(){var t=this,e=this,n=e.el,o=e.ppfx,r=e.catsClass,i=e.traitContClass,a=e.classNoCat,s=document.createDocumentFragment();delete this.catsEl,delete this.traitsEl,this.renderedCategories=new Map,n.innerHTML="\n
\n
\n "),this.collection.forEach((function(e){return t.add(e,s)})),this.append(s);var l="".concat(i,"s ").concat(o,"one-bg ").concat(o,"two-color");return this.$el.addClass(l),this.rendered=!0,this},e}(Wc.A);const Yc=Kc;Kc.prototype.itemView=_c;var Jc=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Xc=void 0&&(void 0).__spreadArray||function(t,e,n){if(n||2===arguments.length)for(var o,r=0,i=e.length;r\n
\n ").concat(c?"\n ").concat(x,"\n ").concat(C,"\n "):'',"\n
\n
\n
\n ").concat(S,"\n ").concat(m?"").concat(m,""):'',"\n ").concat(y,"\n
\n
\n
\n
\n
\n
").concat(u||'',"
\n
").concat(w||'',"
\n
\n \n
\n ")},Object.defineProperty(n.prototype,"em",{get:function(){return this.module.em},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"ppfx",{get:function(){return this.em.getConfig().stylePrefix},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"pfx",{get:function(){return this.config.stylePrefix},enumerable:!1,configurable:!0}),n.prototype.initComponent=function(){var t=this,e=this.model,n=this.config.onInit,o=e.components();this.listenTo(o,'remove add reset',this.checkChildren),[['change:status',this.updateStatus],['change:open',this.updateOpening],['change:layerable',this.updateLayerable],['change:style:display',this.updateVisibility],['change:draggable',this.updateMove],['rerender:layer',this.render],['change:name change:custom-name',this.updateName]].forEach((function(n){return t.listenTo(e,n[0],n[1])})),this.$el.data('model',e),this.$el.data('collection',o),e.viewLayer=this,n.bind(this)({component:e,render:this.__render,listenTo:this.listenTo})},n.prototype.updateName=function(){this.getInputName().innerText=this.model.getName()},n.prototype.getVisibilityEl=function(){return this.getItemContainer().find('[data-toggle-visible]')},n.prototype.updateVisibility=function(){var t=this,e=t.pfx,n=t.model,o=t.module,r="".concat(e,"layer-hidden"),i=!o.isVisible(n)?'addClass':'removeClass';this.$el[i](r),this.getVisibilityEl()[i]("".concat(e,"layer-off"))},n.prototype.updateMove=function(){var t=this.model,e=this.config,n=this.getItemContainer().find("[".concat(Su,"]"))[0];if(n){var o=t.get('draggable')&&e.sortable;n.style.display=o?'':'none'}},n.prototype.toggleVisibility=function(t){null==t||t.stopImmediatePropagation();var e=this.module,n=this.model;e.setVisible(n,!e.isVisible(n))},n.prototype.handleEdit=function(t){null==t||t.stopPropagation();var e=this,n=e.em,o=e.$el,r=e.clsNoEdit,i=e.clsEdit,a=this.getInputName();a[Cu]='true',a.focus(),document.execCommand('selectAll',!1),n.setEditing(!0),o.find(".".concat(this.inputNameCls)).removeClass(r).addClass(i)},n.prototype.handleEditKey=function(t){t.stopPropagation(),((0,Z.v$)(t)||(0,Z.Ci)(t))&&this.handleEditEnd(t)},n.prototype.handleEditEnd=function(t){null==t||t.stopPropagation();var e=this,n=e.em,o=e.$el,r=e.clsNoEdit,i=e.clsEdit,a=e.model,s=this.getInputName(),l=s.textContent;s.scrollLeft=0,s[Cu]='false',a.setName(l),n.setEditing(!1),o.find(".".concat(this.inputNameCls)).addClass(r).removeClass(i),this.updateName()},n.prototype.getInputName=function(){return this.inputName||(this.inputName=this.el.querySelector(".".concat(this.inputNameCls))),this.inputName},n.prototype.updateOpening=function(){var t=this,e=t.$el,n=t.model,o=t.pfx,r='open',i="".concat(o,"layer-open"),a=this.getCaret();this.module.isOpen(n)?(e.addClass(r),a.addClass(i)):(e.removeClass(r),a.removeClass(i))},n.prototype.toggleOpening=function(t){var e=this.model,n=this.module;null==t||t.stopImmediatePropagation(),e.get('components').length&&n.setOpen(e,!n.isOpen(e))},n.prototype.handleSelect=function(t){null==t||t.stopPropagation();var e=this.module,n=this.model;e.setLayerData(n,{selected:!0},{event:t})},n.prototype.handleHover=function(t){null==t||t.stopPropagation();var e=this.module,n=this.model;e.setLayerData(n,{hovered:!0})},n.prototype.handleHoverOut=function(t){null==t||t.stopPropagation();var e=this.module,n=this.model;e.setLayerData(n,{hovered:!1})},n.prototype.startSort=function(t){var e,n,o;t.stopPropagation();var r=this,i=r.em,a=r.sorter,s=r.model;if((!t.button||0===t.button)&&a){var l=(null===(n=null===(e=s.delegate)||void 0===e?void 0:e.move)||void 0===n?void 0:n.call(e,s))||s;a.eventHandlers=xu({legacyOnStartSort:gu(i),legacyOnMoveClb:yu(i),legacyOnEndMove:mu(i,[l])},a.eventHandlers);var c=(null===(o=l.viewLayer)||void 0===o?void 0:o.el)||t.target;a.startSort([{element:c}])}},n.prototype.updateStatus=function(){Zr.prototype.updateStatus.apply(this,[{avoidHover:!this.config.highlightHover,noExtHl:!0}])},n.prototype.getItemContainer=function(){return this.$el.children('[data-toggle-select]')},n.prototype.checkChildren=function(){var t=this,e=t.model,n=t.clsNoChild,o=t.module,r=o.getComponents(e).length,i=this.getItemContainer(),a=i.find(".".concat(this.clsTitle)),s=i.find('[data-count]');a[r?'removeClass':'addClass'](n),s.html("".concat(r||'')),!r&&o.setOpen(e,!1)},n.prototype.getCaret=function(){return this.caret&&this.caret.length||(this.caret=this.getItemContainer().find(".".concat(this.clsCaret))),this.caret},n.prototype.setRoot=function(e){var n,o=(0,t.isString)(e)?null===(n=this.em.getWrapper())||void 0===n?void 0:n.find(e)[0]:e;o&&(this.stopListening(),this.model=o,this.initComponent(),this._rendered&&this.render())},n.prototype.updateLayerable=function(){(this.parentView||this).render()},n.prototype.__clearItems=function(){var t;null===(t=this.items)||void 0===t||t.remove()},n.prototype.remove=function(){for(var t=[],e=0;e\n ").concat(this.getPreview(),"\n \n
\n ").concat(this.getInfo(),"\n
\n
\n ⨯\n
\n ")},n.prototype.updateTarget=function(e){e&&e.set&&(e.set('attributes',(0,t.clone)(e.get('attributes'))),e.set('src',this.model.get('src')))},n.prototype.getPreview=function(){return''},n.prototype.getInfo=function(){return''},n.prototype.render=function(){var t=this.el;return t.innerHTML=this.template(this,this.model),t.className=this.className,this},n}(u.Ss);const Ku=Gu;var Yu=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Ju=void 0&&(void 0).__makeTemplateObject||function(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t},Xu=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return Yu(n,e),n.prototype.getPreview=function(){var t=this,e=t.pfx,n=t.ppfx,o=t.model.get('src');return r(Qu||(Qu=Ju(["\n
\n
\n "],["\n
\n
\n "])),e,o,e,n)},n.prototype.getInfo=function(){var t=this.pfx,e=this.model,n=e.get('name'),o=e.get('width'),i=e.get('height'),a=e.get('unitDim'),s=o&&i?"".concat(o,"x").concat(i).concat(a):'';return n=n||e.getFilename(),r(tp||(tp=Ju(["\n
","
\n
","
\n "],["\n
","
\n
","
\n "])),t,n,t,s)},n.prototype.init=function(t){var e=this.pfx;this.className+=" ".concat(e,"asset-image")},n.prototype.onClick=function(){var e=this.model,n=this.pfx,o=this.__getBhv().select,r=this.config.onClick,i=this.collection;i.trigger('deselectAll'),this.$el.addClass(n+'highlight'),(0,t.isFunction)(o)?o(e,!1):(0,t.isFunction)(r)?r(e):this.updateTarget(i.target)},n.prototype.onDblClick=function(){var e=this.em,n=this.model,o=this.__getBhv().select,r=this.config.onDblClick,i=this.collection,a=i.target,s=i.onSelect;(0,t.isFunction)(o)?o(n,!0):(0,t.isFunction)(r)?r(n):(this.updateTarget(a),null==e||e.Modal.close()),(0,t.isFunction)(s)&&s(n)},n.prototype.onRemove=function(t){t.stopImmediatePropagation(),this.model.collection.remove(this.model)},n}(Ku);const Zu=Xu;var Qu,tp;Xu.prototype.events={'click [data-toggle=asset-remove]':'onRemove',click:'onClick',dblclick:'onDblClick'};var ep=void 0&&(void 0).__assign||function(){return ep=Object.assign||function(t){for(var e,n=1,o=arguments.length;n\n
\n \n
\n \n
\n \n ")),"\n
\n
\n ").concat(r,"\n
\n
\n
\n
\n ")},e.prototype.handleSubmit=function(t){t.preventDefault();var e=this.getAddInput(),n=e&&e.value.trim(),o=this.config.handleAdd;if(n){e.value='';var r=this.getAssetsEl();r&&(r.scrollTop=0),o?o.bind(this)(n):this.options.globalCollection.add(n,{at:0})}},e.prototype.getAssetsEl=function(){return this.el.querySelector(".".concat(this.pfx,"assets"))},e.prototype.getAddInput=function(){return this.inputUrl&&this.inputUrl.value||(this.inputUrl=this.el.querySelector(".".concat(this.pfx,"add-asset input"))),this.inputUrl},e.prototype.removedAsset=function(t){this.collection.length||this.toggleNoAssets()},e.prototype.addToAsset=function(t){1==this.collection.length&&this.toggleNoAssets(!0),this.addAsset(t)},e.prototype.addAsset=function(t,e){void 0===e&&(e=null);var n=e,o=this.collection,r=this.config,i=new t.typeView({model:t,collection:o,config:r}).render().el;if(n)n.appendChild(i);else{var a=this.getAssetsEl();a&&a.insertBefore(i,a.firstChild)}return i},e.prototype.toggleNoAssets=function(t){void 0===t&&(t=!1);var e=this.$el.find(".".concat(this.pfx,"assets"));if(t)e.empty();else{var n=this.config.noAssets;n&&e.append(n)}},e.prototype.deselectAll=function(){var t=this.pfx;this.$el.find(".".concat(t,"highlight")).removeClass("".concat(t,"highlight"))},e.prototype.renderAssets=function(){var t=this,e=document.createDocumentFragment(),n=this.$el.find(".".concat(this.pfx,"assets"));n.empty(),this.toggleNoAssets(!!this.collection.length),this.collection.each((function(n){return t.addAsset(n,e)})),n.append(e)},e.prototype.render=function(){var t=this.options.fu.render().el;return this.$el.empty(),this.$el.append(t).append(this.template(this)),this.el.className="".concat(this.ppfx,"asset-manager"),this.renderAssets(),this},e}(u.Ss);const pp=up;up.prototype.events={submit:'handleSubmit'};var dp=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),fp=void 0&&(void 0).__makeTemplateObject||function(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t},hp=function(t){function e(n){void 0===n&&(n={});var o=t.call(this,n)||this;o.options=n;var r=n.config||{};o.module=n.module,o.config=r,o.em=o.config.em,o.pfx=r.stylePrefix||'',o.ppfx=r.pStylePrefix||'',o.target=o.options.globalCollection||{},o.uploadId=o.pfx+'uploadFile',o.disabled=void 0!==r.disableUpload?r.disableUpload:!r.upload&&!r.embedAsBase64,o.multiUpload=void 0===r.multiUpload||r.multiUpload;var i=r.uploadFile;return i?o.uploadFile=i.bind(o):!r.upload&&r.embedAsBase64&&(o.uploadFile=e.embedAsBase64),o.delegateEvents(),o}return dp(e,t),e.prototype.template=function(t){var e=t.pfx,n=t.title,o=t.uploadId,i=t.disabled,a=t.multiUpload;return r(gp||(gp=fp(["\n
\n
","
\n \n
\n \n "],["\n
\n
","
\n \n
\n \n "])),e,n,o,i?'disabled':'',a?'multiple':'')},e.prototype.events=function(){return{'change [data-input]':'uploadFile'}},e.prototype.onUploadStart=function(){var t=this.module;null==t||t.__propEv(t.events.uploadStart)},e.prototype.onUploadEnd=function(t){var e=this.$el,n=this.module;null==n||n.__propEv(n.events.uploadEnd,t);var o=e.find('input');o&&o.val('')},e.prototype.onUploadError=function(t){var e=this.module;console.error(t),this.onUploadEnd(t),null==e||e.__propEv(e.events.uploadError,t)},e.prototype.onUploadResponse=function(t,e){var n,o=this,r=o.module,i=o.config,a=o.target;try{n='string'==typeof t?JSON.parse(t):t}catch(e){n=t}null==r||r.__propEv(r.events.uploadResponse,n),i.autoAdd&&a&&a.add(n.data,{at:0}),this.onUploadEnd(t),null==e||e(n)},e.prototype.uploadFile=function(t,e,n){var o,r=this,i=t.dataTransfer?t.dataTransfer.files:null===(o=t.target)||void 0===o?void 0:o.files,a=this.config,s=a.beforeUpload;if(!1!==(s&&s(i))){var l=new FormData,c=a.params,u=a.customFetch,p=a.fetchOptions;for(var d in c)l.append(d,c[d]);if(this.multiUpload)for(var f=0;f").concat(o.dropzoneContent,"")),p(),'draggable'in i&&[i,s].forEach((function(t){t.ondragover=d,t.ondragleave=f,t.ondrop=h}))},e.prototype.render=function(){var t=this,e=t.$el,n=t.pfx,o=t.em;return e.html(this.template({title:o&&o.t('assetManager.uploadTitle'),uploadId:this.uploadId,disabled:this.disabled,multiUpload:this.multiUpload,pfx:n})),this.initDrop(),e.attr('class',n+'file-uploader'),this},e.embedAsBase64=function(t,e){var n=this,o=t.dataTransfer?t.dataTransfer.files:t.target.files,r={data:[]};if(FileReader){for(var i=[],a=/^(.+)\/(.+)$/,s=function(t){var e=new Promise((function(e,n){var o=new FileReader;o.addEventListener('load',(function(r){var i,s=t.name,l=a.exec(t.type);if('image'===(i=l?l[1]:t.type)){var c={src:o.result,name:s,type:i,height:0,width:0},u=new Image;u.addEventListener('error',(function(t){n(t)})),u.addEventListener('load',(function(){c.height=u.height,c.width=u.width,e(c)})),u.src=c.src}else e(i?{src:o.result,name:s,type:i}:o.result)})),o.addEventListener('error',(function(t){n(t)})),o.addEventListener('abort',(function(t){n('Aborted')})),o.readAsDataURL(t)}));i.push(e)},l=0,c=o;l","\n
\n \n \n \n
\n
\n
\n
\n \n "],["\n
","
\n
\n \n \n \n
\n
\n
\n
\n \n "])),e,n,e,e,e,e,e,e,e)},e.prototype.events=function(){return{change:'updateDevice','click [data-add-trasp]':'startAdd'}},e.prototype.startAdd=function(){},e.prototype.updateDevice=function(){var t=this.em;if(t){var e=this.devicesEl;t.set('device',e?e.val():'')}},e.prototype.updateSelect=function(){var t=this.em,e=this.devicesEl;if(t&&t.getDeviceModel&&e){var n=t.getDeviceModel();e.val(n?n.get('id'):'')}},e.prototype.getOptions=function(){var t=this.collection,e=this.em,n='';return t.forEach((function(t){var o=t.attributes,r=o.name,i=o.id,a=e&&e.t&&e.t("deviceManager.devices.".concat(i))||r;n+="")})),n},e.prototype.render=function(){var t=this,e=t.em,n=t.ppfx,o=t.$el,r=t.el,i=e&&e.t&&e.t('deviceManager.device');return o.html(this.template({ppfx:n,label:i})),this.devicesEl=o.find(".".concat(n,"devices")),this.devicesEl.append(this.getOptions()),this.devicesEl.val(e.get('device')),r.className="".concat(n,"devices-c"),this},e}(u.Ss);const Mp=jp;var Dp,Lp=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Ip=void 0&&(void 0).__assign||function(){return Ip=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=o.length||l))return this.remove(r,$p($p({},s),{temporary:!0})),o.add(r,$p($p({},s),{at:a})),r}},o.prototype.get=function(t){return this.pages.filter((function(e){return e.get(e.idAttribute)===t}))[0]},o.prototype.getMain=function(){var t=this.pages;return t.filter((function(t){return t.get('type')===Yp}))[0]||t.at(0)},o.prototype.getAllWrappers=function(){var e=this.getAll();return(0,t.unique)((0,t.flatten)(e.map((function(t){return t.getAllFrames().map((function(t){return t.getComponent()}))}))))},o.prototype.select=function(e,n){void 0===n&&(n={});var o=this,r=o.em,i=o.model,a=o.events,s=(0,t.isString)(e)?this.get(e):e;return s&&(r.trigger(a.selectBefore,s,n),i.set('selected',s,n)),this},o.prototype.getSelected=function(){return this.model.get('selected')},o.prototype.destroy=function(){var t=this;this.pages.off().reset(),this.model.stopListening(),this.model.clear({silent:!0}),['selected','model'].map((function(e){return t[e]=0}))},o.prototype.store=function(){return this.getProjectData()},o.prototype.load=function(t){var e=this,n=this.loadProjectData(t,{all:this.pages,reset:!0,onResult:function(t,n){t.forEach((function(t){return e.add(t,n)})),e.__onReset()}});return this.pages.forEach((function(t){return t.getFrames().initRefs()})),n},o.prototype._initPage=function(){return this.get(this.config.selected)||this.getMain()},o.prototype._createId=function(){var t,n=this.getAll().length+16,o=this.getAllMap();do{t=(0,e.createId)(n)}while(o[t]);return t},o}(b);const Xp=Jp;var Zp={placeholder:'eg. Text here'};const Qp={assetManager:{addButton:'Add image',inputPlh:'http://path/to/the/image.jpg',modalTitle:'Select Image',uploadTitle:'Drop files here or click to upload'},blockManager:{labels:{},categories:{}},domComponents:{names:{'':'Box',wrapper:'Body',text:'Text',comment:'Comment',image:'Image',video:'Video',label:'Label',link:'Link',map:'Map',tfoot:'Table foot',tbody:'Table body',thead:'Table head',table:'Table',row:'Table row',cell:'Table cell'}},deviceManager:{device:'Device',devices:{desktop:'Desktop',tablet:'Tablet',mobileLandscape:'Mobile Landscape',mobilePortrait:'Mobile Portrait'}},panels:{buttons:{titles:{preview:'Preview',fullscreen:'Fullscreen','sw-visibility':'View components','export-template':'View code','open-sm':'Open Style Manager','open-tm':'Settings','open-layers':'Open Layer Manager','open-blocks':'Open Blocks'}}},selectorManager:{label:'Classes',selected:'Selected',emptyState:'- State -',states:{hover:'Hover',active:'Click','nth-of-type(2n)':'Even/Odd'}},styleManager:{empty:'Select an element before using Style Manager',layer:'Layer',fileButton:'Images',sectors:{general:'General',layout:'Layout',typography:'Typography',decorations:'Decorations',extra:'Extra',flex:'Flex',dimension:'Dimension'},properties:{'text-shadow-h':'X','text-shadow-v':'Y','text-shadow-blur':'Blur','text-shadow-color':'Color','box-shadow-h':'X','box-shadow-v':'Y','box-shadow-blur':'Blur','box-shadow-spread':'Spread','box-shadow-color':'Color','box-shadow-type':'Type','margin-top-sub':'Top','margin-right-sub':'Right','margin-bottom-sub':'Bottom','margin-left-sub':'Left','padding-top-sub':'Top','padding-right-sub':'Right','padding-bottom-sub':'Bottom','padding-left-sub':'Left','border-width-sub':'Width','border-style-sub':'Style','border-color-sub':'Color','border-top-left-radius-sub':'Top Left','border-top-right-radius-sub':'Top Right','border-bottom-right-radius-sub':'Bottom Right','border-bottom-left-radius-sub':'Bottom Left','transform-rotate-x':'Rotate X','transform-rotate-y':'Rotate Y','transform-rotate-z':'Rotate Z','transform-scale-x':'Scale X','transform-scale-y':'Scale Y','transform-scale-z':'Scale Z','transition-property-sub':'Property','transition-duration-sub':'Duration','transition-timing-function-sub':'Timing','background-image-sub':'Image','background-repeat-sub':'Repeat','background-position-sub':'Position','background-attachment-sub':'Attachment','background-size-sub':'Size'}},traitManager:{empty:'Select an element before using Trait Manager',label:'Component settings',categories:{},traits:{labels:{},attributes:{id:Zp,alt:Zp,title:Zp,href:{placeholder:'eg. https://google.com'}},options:{target:{false:'This window',_blank:'New window'}}}},storageManager:{recover:'Do you want to recover unsaved changes?'}};const td=function(){return{locale:'en',localeFallback:'en',detectLocale:!0,debug:!1,messages:{en:Qp},messagesAdd:void 0}};var ed;!function(t){t["add"]="i18n:add",t["update"]="i18n:update",t["locale"]="i18n:locale"}(ed||(ed={}));const nd=ed;var od=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),rd=function(n){function o(t){var e=n.call(this,t,'I18n',td())||this;e.events=nd;var o=e.config.messagesAdd;return o&&e.addMessages(o),e.config.detectLocale&&(e.config.locale=e._localLang()),e}return od(o,n),o.prototype.setLocale=function(t){var e=this,n=e.em,o=e.config,r=e.events;return n.trigger(r.locale,{value:t,valuePrev:o.locale}),o.locale=t,this},o.prototype.getLocale=function(){return this.config.locale},o.prototype.getMessages=function(t,e){void 0===e&&(e={});var n=this.config.messages;return t&&!n[t]&&this._debug("'".concat(t,"' i18n lang not found"),e),t?n[t]:n},o.prototype.setMessages=function(t){var e=this,n=e.em,o=e.config,r=e.events;return o.messages=t,n.trigger(r.update,t),this},o.prototype.addMessages=function(t){var n=this,o=n.em,r=n.events,i=n.config.messages;return o.trigger(r.add,t),this.setMessages((0,e.deepMerge)(i,t)),this},o.prototype.t=function(e,n){void 0===n&&(n={});var o=this.config,r=n.params||{},i=n.l||this.getLocale(),a=n.lFlb||o.localeFallback,s=this._getMsg(e,i,n);return s||(s=this._getMsg(e,a,n)),!s&&this._debug("'".concat(e,"' i18n key not found in '").concat(i,"' lang"),n),s=s&&(0,t.isString)(s)?this._addParams(s,r):s},o.prototype._localLang=function(){var t=(0,e.hasWin)()&&window.navigator||{},n=t.language||t.userLanguage;return n?n.split('-')[0]:'en'},o.prototype._addParams=function(t,e){var n=new RegExp('{([\\w\\d-]*)}','g');return t.replace(n,(function(t,n){return e[n]||''})).trim()},o.prototype._getMsg=function(e,n,o){void 0===o&&(o={});var r=this.getMessages(n,o);if(r){var i=r[e];return!i&&e.indexOf('.')>0&&(i=e.split('.').reduce((function(e,n){if(!(0,t.isUndefined)(e))return e[n]}),r)),i}},o.prototype._debug=function(t,e){void 0===e&&(e={});var n=this.em,o=this.config;(e.debug||o.debug)&&n&&n.logWarning(t)},o.prototype.destroy=function(){},o}(m);const id=rd;var ad=void 0&&(void 0).__assign||function(){return ad=Object.assign||function(t){for(var e,n=1,o=arguments.length;nC?_.h=Math.round(_.w/C):_.w=Math.round(_.h*C)}for(var S in~w.indexOf('l')&&(_.l+=i.w-_.w),~w.indexOf('t')&&(_.t+=i.h-_.h),_){var O=S;_[O]=parseInt("".concat(_[O]),10)}return _}},n.prototype.getParentRect=function(){var t={left:0,top:0,width:0,height:0},e=this.el;if(!e)return t;var n=e.offsetParent;return n&&'BODY'!==n.tagName&&(t=this.getElementPos(n)),t},n}();const ld=sd;var cd=void 0&&(void 0).__assign||function(){return cd=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=this.left&&t<=this.left+this.width&&e>=this.top&&e<=this.top+this.height},t}();const gd=vd;var yd=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),md=function(e){function n(n){var o=e.call(this)||this;return o.sourceNodes=[],o.containerOffset={top:0,left:0},o.moveThreshold=20,o.treeClass=n.treeClass,o.em=n.em,o.containerContext=n.containerContext,o.positionOptions=n.positionOptions,o.dragDirection=n.dragDirection,o.eventHandlers=n.eventHandlers,(0,t.bindAll)(o,'endDrag','cancelDrag','recalculateTargetOnScroll','startSort','onDragStart','onMove'),o.restLastMoveData(),o.rateLimiter=new fd(o.moveThreshold),o}return yd(n,e),n.prototype.startSort=function(t){this.sourceNodes=t,this.bindDragEventHandlers()},n.prototype.bindDragEventHandlers=function(){(0,Z.on)(this.containerContext.container,'dragstart',this.onDragStart),(0,Z.on)(this.containerContext.container,'mousemove dragover',this.onMove),(0,Z.on)(this.containerContext.document,'mouseup dragend touchend',this.endDrag)},n.prototype.recalculateTargetOnScroll=function(){var t=this.lastMoveData.mouseEvent;t&&this.onMove(t)},n.prototype.onMove=function(t){this.rateLimiter.updateArgs(t),this.rateLimiter.execute(this.handleMove.bind(this))},n.prototype.handleMove=function(t){var e,n,o,r,i,a,s;this.adjustForScroll();var c=this.lastMoveData.targetNode;null===(n=(e=this.eventHandlers).onMouseMove)||void 0===n||n.call(e,t),this.cacheContainerPosition();var u=this.getMousePositionRelativeToContainer(t.clientX,t.clientY),p=u.mouseXRelative,d=u.mouseYRelative,f=this.getMouseTargetElement(t),h=this.getFirstElementWithAModel(f),v=h?null===(o=(0,l["default"])(h))||void 0===o?void 0:o.data('model'):void 0,g=v?this.getOrCreateHoveredNode(v):void 0,y=g?this.getIndexInParent(g,g.nodeDimensions,p,d):0,m=g?this.getValidParent(g,0,p,d):void 0;if(!(null==m?void 0:m.equals(c))&&(null===(i=(r=this.eventHandlers).onTargetChange)||void 0===i||i.call(r,c,m)),!m||!g)return this.triggerLegacyOnMoveCallback(t,0),this.triggerMoveEvent(p,d),void this.restLastMoveData();var b=this.getDropPosition(m,p,d),_=b.index,w=b.placement,x=b.placeholderDimensions;(!x.equals(this.lastMoveData.placeholderDimensions)||w!==this.lastMoveData.placement)&&(null===(s=(a=this.eventHandlers).onPlaceholderPositionChange)||void 0===s||s.call(a,x,w)),this.lastMoveData={targetNode:m,hoveredNode:g,mouseEvent:t,index:_,hoveredIndex:y,placement:w,placeholderDimensions:x},this.triggerMoveEvent(p,d),this.triggerLegacyOnMoveCallback(t,_)},n.prototype.adjustForScroll=function(){var t,e,n=this.lastMoveData.targetNode;if(null==n?void 0:n.element){var o=this.getDim(null==n?void 0:n.element);(i=null===(t=n.nodeDimensions)||void 0===t?void 0:t.calculateDimensionDifference(o))&&n.adjustDimensions(i)}var r=this.lastMoveData.hoveredNode;if(null==r?void 0:r.element){var i;o=this.getDim(null==r?void 0:r.element);(i=null===(e=r.nodeDimensions)||void 0===e?void 0:e.calculateDimensionDifference(o))&&r.adjustDimensions(i)}},n.prototype.restLastMoveData=function(){this.lastMoveData={targetNode:void 0,index:void 0,placement:void 0,mouseEvent:void 0}},n.prototype.triggerLegacyOnMoveCallback=function(t,e){var n,o,r,i,a=null===(n=this.sourceNodes[0])||void 0===n?void 0:n.model;null===(r=(o=this.eventHandlers).legacyOnMoveClb)||void 0===r||r.call(o,{event:t,target:a,parent:null===(i=this.lastMoveData.targetNode)||void 0===i?void 0:i.model,index:e})},n.prototype.triggerMoveEvent=function(t,e){var n,o=this.lastMoveData,r=o.targetNode,i=o.placement,a=o.index,s=a?a+('after'===i?-1:0):0;this.em.trigger('sorter:drag',{target:(null==r?void 0:r.element)||null,targetModel:null===(n=this.lastMoveData.targetNode)||void 0===n?void 0:n.model,sourceModel:this.sourceNodes[0].model,dims:(null==r?void 0:r.childrenDimensions)||[],pos:{index:s,indexEl:s,placement:i},x:t,y:e})},n.prototype.getDropPosition=function(t,e,n){var o,r=t.nodeDimensions,i=t.childrenDimensions,a=t.getChildren(),s=a&&a.length>0;r=r||this.getDim(t.element),t.nodeDimensions=r,i=i||this.getChildrenDim(t),t.childrenDimensions=i;var l=r.clone(),c=0,u='inside';return s&&(c=(o=function(t,e,n){for(var o,r={index:0,placement:'before'},i=0,a=0,s=0,l=0,c=0,u=0,p=0,d=t.length;pa||s&&c>=s||i&&h+g0?0===p.handleNodeAddition(t,e,o).length&&p.triggerNullOnEndMove(!1):p.triggerNullOnEndMove(!0);null==t||t.restNodeState(),p.placeholder.hide()},p.onTargetChange=function(t,e){var n;null==t||t.restNodeState();var o=p.em.Canvas;if(!e)return p.placeholder.hide(),void o.removeSpots(Td);null==e||e.setSelectedParentState(),p.targetIsText=e.isTextNode(),p.targetIsText&&(null===(n=p.sourceNodes)||void 0===n?void 0:n.some((function(t){return t.isTextable()})))?(e.setContentEditable(!0),p.placeholder.hide()):p.placeholder.show(),[W.F.Select,W.F.Hover,W.F.Spacing].forEach((function(t){return o.removeSpots({type:t})})),o.addSpot(Od(Od({},Td),{component:e.model}))},(0,t.bindAll)(p,'handleScrollEvent'),p}return Sd(n,e),n.prototype.onStartSort=function(){this.em.clearSelection(),this.setAutoCanvasScroll(!0)},n.prototype.bindDragEventHandlers=function(){this.em.on('frame:scroll',this.handleScrollEvent),e.prototype.bindDragEventHandlers.call(this)},n.prototype.cleanupEventListeners=function(){this.em.off('frame:scroll',this.handleScrollEvent),e.prototype.cleanupEventListeners.call(this)},n.prototype.handleScrollEvent=function(){for(var t,e=[],n=0;n=0&&Qd.splice(o,1),93!=n&&224!=n||(n=91),n in Kd)for(e in Kd[n]=!1,Jd)Jd[e]==n&&(sf[e]=!1)}function af(){for(qd in Kd)Kd[qd]=!1;for(qd in Jd)sf[qd]=!1}function sf(t,e,n){var o,r;o=cf(t),void 0===n&&(n=e,e='all');for(var i=0;i1&&(r=uf(t),t=[t[t.length-1]]),t=t[0],(t=Zd(t))in Gd||(Gd[t]=[]),Gd[t].push({shortcut:o[i],scope:e,method:n,key:o[i],mods:r})}for(qd in Jd)sf[qd]=!1;function lf(){return Yd||'all'}function cf(t){var e;return''==(e=(t=t.replace(/\s/g,'')).split(','))[e.length-1]&&(e[e.length-2]+=','),e}function uf(t){for(var e=t.slice(0,t.length-1),n=0;n1&&(s=uf(o)),t=o[o.length-1],t=Zd(t),void 0===e&&(e=lf()),!Gd[t])return;for(r=0;r0,Kd)(!Kd[o]&&tf(n.mods,+o)>-1||Kd[o]&&-1==tf(n.mods,+o))&&(i=!1);(0!=n.mods.length||Kd[16]||Kd[18]||Kd[17]||Kd[91])&&!i||!1===n.method(t,n)&&(t.preventDefault?t.preventDefault():t.returnValue=!1,t.stopPropagation&&t.stopPropagation(),t.cancelBubble&&(t.cancelBubble=!0))}}(t)})),pf(t.document,'keyup',rf),pf(t,'focus',af)};const df=sf;const ff=function(){return{defaults:{'core:undo':{keys:'⌘+z, ctrl+z',handler:'core:undo',opts:{prevent:!0}},'core:redo':{keys:'⌘+shift+z, ctrl+shift+z',handler:'core:redo',opts:{prevent:!0}},'core:copy':{keys:'⌘+c, ctrl+c',handler:'core:copy'},'core:paste':{keys:'⌘+v, ctrl+v',handler:'core:paste'},'core:component-next':{keys:'s',handler:'core:component-next'},'core:component-prev':{keys:'w',handler:'core:component-prev'},'core:component-enter':{keys:'d',handler:'core:component-enter'},'core:component-exit':{keys:'a',handler:'core:component-exit'},'core:component-delete':{keys:'backspace, delete',handler:'core:component-delete',opts:{prevent:!0}}}}};var hf=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),vf=void 0&&(void 0).__spreadArray||function(t,e,n){if(n||2===arguments.length)for(var o,r=0,i=e.length;r\n
\n
").concat(r,"
\n
\n
\n
\n
").concat(o,"
\n
\n
\n \n
")},e.prototype.events=function(){return{click:'onClick','click [data-close-modal]':'hide'}},e.prototype.onClick=function(t){this.config.backdrop&&t.target===this.el&&this.hide()},e.prototype.getCollector=function(){return this.$collector||(this.$collector=this.$el.find('.'+this.pfx+'collector')),this.$collector},e.prototype.getContent=function(){var t=this.pfx;return this.$content||(this.$content=this.$el.find(".".concat(t,"content #").concat(t,"c"))),this.$content},e.prototype.getTitle=function(t){return void 0===t&&(t={}),this.$title||(this.$title=this.$el.find('.'+this.pfx+'title')),t.$?this.$title:this.$title.get(0)},e.prototype.updateContent=function(){var t=this.getContent(),e=t.children(),n=this.getCollector(),o=this.model.get('content');e.length&&n.append(e),t.empty().append(o)},e.prototype.updateTitle=function(){var t=this.getTitle({$:!0});t&&t.empty().append(this.model.get('title'))},e.prototype.updateOpen=function(){this.el.style.display=this.model.get('open')?'':'none'},e.prototype.hide=function(){this.model.close()},e.prototype.show=function(){this.model.open()},e.prototype.updateAttr=function(t){var e=this,n=e.pfx,o=e.$el,r=e.el,i=[].slice.call(r.attributes).map((function(t){return t.name}));o.removeAttr(i.join(' ')),o.attr(xf(xf({},t||{}),{class:"".concat(n,"container ").concat(t&&t.class||'').trim()}))},e.prototype.render=function(){var t=this.$el,e=this.model.toJSON();return e.pfx=this.pfx,e.ppfx=this.ppfx,t.html(this.template(e)),this.updateAttr(),this.updateOpen(),this},e}(X);const Sf=Cf;var Of=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Tf=function(e){function n(n){var o=e.call(this,n,'Modal',mf())||this;return o.model=new _f(o),o.model.on('change:open',(function(t,e){n.trigger("modal:".concat(e?'open':'close'))})),o.model.on('change',(0,t.debounce)((function(){var e=o._evData(),r=o.config.custom;(0,t.isFunction)(r)&&r(e),n.trigger('modal',e)}),0)),o}return Of(n,e),n.prototype._evData=function(){var e=this,n=this.getTitle(),o=this.getContent(),r=this.model.attributes;return{open:r.open,attributes:r.attributes,title:(0,t.isString)(n)?(0,Z.GZ)(n):n,content:(0,t.isString)(o)?(0,Z.GZ)(o):o.get?o.get(0):o,close:function(){e.close()}}},n.prototype.postRender=function(t){var e=t.model.config.el||t.el,n=this.render();n&&(null==e||e.appendChild(n))},n.prototype.open=function(t){void 0===t&&(t={});var e=t.attributes||{};return t.title&&this.setTitle(t.title),t.content&&this.setContent(t.content),this.model.set('attributes',e),this.model.open(),this.modal&&this.modal.updateAttr(e),this},n.prototype.close=function(){return this.model.close(),this},n.prototype.onceClose=function(t){return this.em.once('modal:close',t),this},n.prototype.onceOpen=function(t){return this.em.once('modal:open',t),this},n.prototype.isOpen=function(){return!!this.model.get('open')},n.prototype.setTitle=function(t){return this.model.set('title',t),this},n.prototype.getTitle=function(){return this.model.get('title')},n.prototype.setContent=function(t){return this.model.set('content',' '),this.model.set('content',t),this},n.prototype.getContent=function(){return this.model.get('content')},n.prototype.getContentEl=function(){var t;return null===(t=this.modal)||void 0===t?void 0:t.getContent().get(0)},n.prototype.getModel=function(){return this.model},n.prototype.render=function(){var t;if(!this.config.custom){var e=Sf.extend(this.config.extend),n=this.modal&&this.modal.el;return this.modal=new e({el:n,model:this.model,config:this.config}),null===(t=this.modal)||void 0===t?void 0:t.render().el}},n.prototype.destroy=function(){var t;null===(t=this.modal)||void 0===t||t.remove()},n}(m);const Pf=Tf;var Ef='sw-visibility',kf='export-template',Af='open-sm',jf='open-tm',Mf='open-layers',Df='open-blocks',Lf='fullscreen',If='preview';const Nf=function(){return{stylePrefix:'pn-',defaults:[{id:'commands',buttons:[{}]},{id:'options',buttons:[{active:!0,id:Ef,className:'fa fa-square-o',command:'core:component-outline',context:Ef,attributes:{title:'View components'}},{id:If,className:'fa fa-eye',command:If,context:If,attributes:{title:'Preview'}},{id:Lf,className:'fa fa-arrows-alt',command:Lf,context:Lf,attributes:{title:'Fullscreen'}},{id:kf,className:'fa fa-code',command:kf,attributes:{title:'View code'}}]},{id:'views',buttons:[{id:Af,className:'fa fa-paint-brush',command:Af,active:!0,togglable:!1,attributes:{title:'Open Style Manager'}},{id:jf,className:'fa fa-cog',command:jf,togglable:!1,attributes:{title:'Settings'}},{id:Mf,className:'fa fa-bars',command:Mf,togglable:!1,attributes:{title:'Open Layer Manager'}},{id:Df,className:'fa fa-th-large',command:Df,togglable:!1,attributes:{title:'Open Blocks'}}]}]}};var Rf=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}();const Vf=function(t){function e(e,n){var o=t.call(this,e,n)||this;return o.get('buttons').length&&o.set('buttons',new Uf(o.module,o.get('buttons'))),o}return Rf(e,t),e.prototype.defaults=function(){return{id:'',label:'',tagName:'span',className:'',command:'',context:'',buttons:[],attributes:{},options:{},active:!1,dragDrop:!1,togglable:!0,runDefaultCommand:!0,stopDefaultCommand:!1,disable:!1}},Object.defineProperty(e.prototype,"className",{get:function(){return this.get('className')},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"command",{get:function(){return this.get('command')},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"active",{get:function(){return this.get('active')},set:function(t){this.set('active',t)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"togglable",{get:function(){return this.get('togglable')},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"runDefaultCommand",{get:function(){return this.get('runDefaultCommand')},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stopDefaultCommand",{get:function(){return this.get('stopDefaultCommand')},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disable",{get:function(){return this.get('disable')},enumerable:!1,configurable:!0}),e}(x.A);var Ff=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Hf=function(t){function e(e,n){return t.call(this,e,n,Vf)||this}return Ff(e,t),e.prototype.deactivateAllExceptOne=function(t,e){this.forEach((function(n,o){n!==t&&(n.set('active',!1),e&&n.get('buttons').length&&n.get('buttons').deactivateAllExceptOne(t,e))}))},e.prototype.deactivateAll=function(t,e){var n=t||'';this.forEach((function(t){t.get('context')==n&&t!==e&&t.set('active',!1,{fromCollection:!0})}))},e.prototype.disableAllButtons=function(t){var e=t||'';this.forEach((function(t,n){t.get('context')==e&&t.set('disable',!0)}))},e.prototype.disableAllButtonsExceptOne=function(t,e){this.forEach((function(n,o){n!==t&&(n.set('disable',!0),e&&n.get('buttons').length&&n.get('buttons').disableAllButtonsExceptOne(t,e))}))},e}(E);const Uf=Hf;Hf.prototype.model=Vf;var zf=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}();const Bf=function(t){function e(e,n){var o=t.call(this,e,n)||this,r=o.get('buttons')||[];return o.buttons=new Uf(e,r),o}return zf(e,t),e.prototype.defaults=function(){return{id:'',content:'',visible:!0,buttons:[],attributes:{}}},Object.defineProperty(e.prototype,"buttons",{get:function(){return this.get('buttons')},set:function(t){this.set('buttons',t)},enumerable:!1,configurable:!0}),e}(x.A);var Wf=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),$f=function(t){function e(e,n){return t.call(this,e,n,Bf)||this}return Wf(e,t),e}(E);const qf=$f;$f.prototype.model=Bf;var Gf=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Kf=void 0&&(void 0).__assign||function(){return Kf=Object.assign||function(t){for(var e,n=1,o=arguments.length;n\n
","
\n
\n \n "],["\n
\n
","
\n
\n
\n "])),e,e,n,e,o,e)},e.prototype.initialize=function(t){this.config=t.config||{},this.pfx=this.config.stylePrefix},e.prototype.render=function(){var t,e,n=this,o=n.model,r=n.pfx,i=n.$el,a=o.toJSON(),s=o.get('input')||(null===(e=(t=o).getElement)||void 0===e?void 0:e.call(t));return a.pfx=r,i.html(this.template(a)),i.attr('class',"".concat(r,"editor-c")),i.find("#".concat(r,"code")).append(s),this},e}(u.Ss);const Ph=Th;var Eh,kh=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Ah=void 0&&(void 0).__assign||function(){return Ah=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=0})))return!1;if((0,t.isBoolean)(n))return!0;if((0,t.isArray)(n)&&zh(e).some((function(t){return n.indexOf(t)>=0})))return!0}return!1},on:function(e,n,o){var i=Bh.get(e);i||(i=e.previousAttributes(),Bh.set(e,i));var a=o||n||{};if(a.noUndo&&setTimeout((function(){Bh.delete(e)})),!Uh(a)){var s=e.toJSON({fromUndo:r}),l={object:e,before:i,after:s};if(Bh.delete(e),!(0,t.isEmpty)(s))return l}}}),o.um.changeUndoType('add',{on:function(t,e,n){if(void 0===n&&(n={}),!Uh(n)&&o.isRegistered(e))return{object:e,before:void 0,after:t,options:Fh(Fh({},n),{fromUndo:r})}}}),o.um.changeUndoType('remove',{on:function(t,e,n){if(void 0===n&&(n={}),!Uh(n)&&o.isRegistered(e))return{object:e,before:t,after:void 0,options:Fh(Fh({},n),{fromUndo:r})}}}),o.um.changeUndoType('reset',{undo:function(t,e){t.reset(e,{fromUndo:r})},redo:function(t,e,n){t.reset(n,{fromUndo:r})},on:function(t,e){if(void 0===e&&(e={}),!Uh(e)&&o.isRegistered(t))return{object:t,before:e.previousModels,after:Hh([],t.models,!0),options:Fh(Fh({},e),{fromUndo:r})}}}),o.um.on('undo redo',(function(){n.getSelectedAll().map((function(t){return t.trigger('rerender:layer')}))})),[Rh.undo,Rh.redo].forEach((function(t){return o.um.on(t,(function(){return n.trigger(t)}))})),o}return Vh(n,e),n.prototype.postLoad=function(){var t=this.config,e=this.em;t.trackSelection&&e&&this.add(e.get('selected'))},n.prototype.add=function(t){return this.um.register(t),this},n.prototype.remove=function(t){return this.um.unregister(t),this},n.prototype.removeAll=function(){return this.um.unregisterAll(),this},n.prototype.start=function(){return this.um.startTracking(),this},n.prototype.stop=function(){return this.um.stopTracking(),this},n.prototype.undo=function(t){void 0===t&&(t=!0);var e=this.em,n=this.um;return!e.isEditing()&&n.undo(t),this},n.prototype.undoAll=function(){return this.um.undoAll(),this},n.prototype.redo=function(t){void 0===t&&(t=!0);var e=this.em,n=this.um;return!e.isEditing()&&n.redo(t),this},n.prototype.redoAll=function(){return this.um.redoAll(),this},n.prototype.hasUndo=function(){return!!this.um.isAvailable('undo')},n.prototype.hasRedo=function(){return!!this.um.isAvailable('redo')},n.prototype.isRegistered=function(t){return!!this.getInstance().objectRegistry.isRegistered(t)},n.prototype.getStack=function(){return this.um.stack},n.prototype.getStackGroup=function(){var t=[],e=[];return this.getStack().forEach((function(n){var o=n.get('magicFusionIndex');e.indexOf(o)<0&&(e.push(o),t.push(n))})),t},n.prototype.skip=function(t){var e=!!this.um.isTracking();e&&this.stop(),t(),e&&this.start()},n.prototype.getGroupedStack=function(){var e={},n=this.getStack();return n.forEach((function(t,n){var o=t.get('magicFusionIndex'),r=function(t,e){var n=t.attributes,o=n.type,r=n.after,i=n.before,a=n.object,s=n.options;return{index:e,type:o,after:r,before:i,object:a,options:void 0===s?{}:s}}(t,n);e[o]?e[o].push(r):e[o]=[r]})),Object.keys(e).map((function(n){var o=e[n];return{index:o[o.length-1].index,actions:o,labels:(0,t.unique)(o.reduce((function(t,e){var n,o=null===(n=e.options)||void 0===n?void 0:n.action;return o&&t.push(o),t}),[]))}}))},n.prototype.goToGroup=function(e){var n=this;if(e){var o=this.getPointer(),r=e.index-o;(0,t.times)(Math.abs(r),(function(){n[r<0?'undo':'redo'](!1)}))}},n.prototype.getPointer=function(){return this.getStack().pointer},n.prototype.clear=function(){return this.um.clear(),this},n.prototype.getInstance=function(){return this.um},n.prototype.destroy=function(){this.clear().removeAll()},n}(m);const $h=Wh;const qh=function(){return{stylePrefix:'rte-',adjustToolbar:!0,actions:['bold','italic','underline','strikethrough','link','wrap'],custom:!1}};var Gh,Kh=void 0&&(void 0).__assign||function(){return Kh=Object.assign||function(t){for(var e,n=1,o=arguments.length;nB',attributes:{title:'Bold'},result:function(t){return t.exec('bold')}},italic:{name:'italic',icon:'I',attributes:{title:'Italic'},result:function(t){return t.exec('italic')}},underline:{name:'underline',icon:'U',attributes:{title:'Underline'},result:function(t){return t.exec('underline')}},strikethrough:{name:'strikethrough',icon:'S',attributes:{title:'Strike-through'},result:function(t){return t.exec('strikeThrough')}},link:{icon:"\n \n ",name:'link',attributes:{style:'font-size:1.4rem;padding:0 4px 2px;',title:'Link'},state:function(t){return t&&t.selection()&&Qh(t)?Jh:Xh},result:function(t){Qh(t)?t.exec('unlink'):t.insertHTML("").concat(t.selection(),""),{select:!0})}},wrap:{name:'wrap',icon:"\n \n ",attributes:{title:'Wrap for style'},state:function(t){return(null==t?void 0:t.selection())&&Qh(t,'SPAN')?Zh:Xh},result:function(t){!Qh(t,'SPAN')&&t.insertHTML("").concat(t.selection(),""),{select:!0})}}},nv=function(){function n(e,n,o){void 0===o&&(o={});var r=this;if(this.em=e,this.settings=o,n[Yh])return n[Yh];n[Yh]=this,this.setEl(n),this.updateActiveActions=this.updateActiveActions.bind(this),this.__onKeydown=this.__onKeydown.bind(this),this.__onPaste=this.__onPaste.bind(this);var i=(o.actions||[]).map((function(e){var n=e;return(0,t.isString)(e)?n=Kh({},ev[e]):ev[e.name]&&(n=Kh(Kh({},ev[e.name]),e)),n})),a=i.length?i:Object.keys(ev).map((function(t){return ev[t]}));o.classes=Kh({actionbar:'actionbar',button:'action',active:'active',disabled:'disabled',inactive:'inactive'},o.classes);var s=o.classes,l=o.actionbar;if(this.actionbar=l,this.classes=s,this.actions=a,!l){if(!this.isCustom(o.module)){var c=o.actionbarContainer;(l=document.createElement('div')).className=s.actionbar,null==c||c.appendChild(l),this.actionbar=l}a.forEach((function(t){return r.addAction(t)}))}return o.styleWithCSS&&this.exec('styleWithCSS'),this}return n.prototype.isCustom=function(t){var e=t||this.em.RichTextEditor;return!(!(null==e?void 0:e.config.custom)&&!(null==e?void 0:e.customRte))},n.prototype.destroy=function(){},n.prototype.setEl=function(t){this.el=t,this.doc=t.ownerDocument},n.prototype.updateActiveActions=function(){var t=this,e=this.getActions();e.forEach((function(e){var n=e.update,o=e.btn,r=t.classes,i=r.active,a=r.inactive,s=r.disabled,l=e.state,c=e.name,u=t.doc,p=Gh.INACTIVE;if(o&&(o.className=o.className.replace(i,'').trim(),o.className=o.className.replace(a,'').trim(),o.className=o.className.replace(s,'').trim()),l){var d=l(t,u);if(p=d,o)switch(d){case Jh:o.className+=" ".concat(i);break;case Xh:o.className+=" ".concat(a);break;case Zh:o.className+=" ".concat(s)}}else u.queryCommandSupported(c)&&u.queryCommandState(c)&&(o&&(o.className+=" ".concat(i)),p=Gh.ACTIVE);e.currentState=p,null==n||n(t,e)})),e.length&&this.em.RichTextEditor.__dbdTrgCustom()},n.prototype.enable=function(t){return this.enabled?this:this.__toggleEffects(!0,t)},n.prototype.disable=function(){return this.__toggleEffects(!1)},n.prototype.__toggleEffects=function(t,e){void 0===t&&(t=!1),void 0===e&&(e={});var n=t?Z.on:Z.AU,o=this.el,r=this.doc,i=this.actionbarEl();if(i&&(i.style.display=t?'':'none'),o.contentEditable="".concat(!!t),n(o,'mouseup keyup',this.updateActiveActions),n(r,'keydown',this.__onKeydown),n(r,'paste',this.__onPaste),this.enabled=t,t){var a=e.event;if(this.syncActions(),this.updateActiveActions(),a){var s=null;if(r.caretRangeFromPoint){var l=(0,Z.G2)(a);s=r.caretRangeFromPoint(l.clientX,l.clientY)}else a.rangeParent&&(s=r.createRange()).setStart(a.rangeParent,a.rangeOffset);var c=r.getSelection();null==c||c.removeAllRanges(),s&&(null==c||c.addRange(s))}o.focus()}return this},n.prototype.__onKeydown=function(t){var e=this.em,n=e.RichTextEditor.getConfig().onKeydown;if(n)return n({ev:t,rte:this,editor:e.getEditor()});var o=this.doc;'Enter'!==t.key||['insertOrderedList','insertUnorderedList'].some((function(t){return o.queryCommandState(t)}))||(o.execCommand('insertLineBreak'),t.preventDefault())},n.prototype.__onPaste=function(t){var e=this.em,n=e.RichTextEditor.getConfig().onPaste;if(n)return n({ev:t,rte:this,editor:e.getEditor()});var o=t.clipboardData,r=o.getData('text'),i=o.getData('text/html');if(r&&!i){t.preventDefault();var a=r.replace(/(?:\r\n|\r|\n)/g,'
');this.doc.execCommand('insertHTML',!1,a)}},n.prototype.syncActions=function(){var t=this;this.getActions().forEach((function(e){if(t.actionbar&&(!e.state||e.state&&e.state(t,t.doc)>=0)){var n=e.event||'click',o=e.btn;o&&(o["on".concat(n)]=function(){e.result(t,e),t.updateActiveActions()})}}))},n.prototype.addAction=function(t,e){void 0===e&&(e={});var n=e.sync,o=this.actionbarEl();if(o){var r=t.icon,i=t.attributes,a=void 0===i?{}:i,s=document.createElement('span');for(var l in s.className=this.classes.button,t.btn=s,a)s.setAttribute(l,a[l]);'string'==typeof r?s.innerHTML=r:s.appendChild(r),o.appendChild(s)}n&&(this.actions.push(t),this.syncActions())},n.prototype.getActions=function(){return this.actions},n.prototype.selection=function(){return this.doc.getSelection()},n.prototype.exec=function(t,e){this.doc.execCommand(t,!1,e)},n.prototype.actionbarEl=function(){return this.actionbar},n.prototype.insertHTML=function(n,o){var r=(void 0===o?{}:o).select,i=this,a=i.em,s=i.doc,l=i.el,c=s.getSelection();if(c&&c.rangeCount){var u=(0,e.getComponentModel)(l)||a.getSelected(),p=s.createElement('div'),d=c.getRangeAt(0);d.deleteContents(),(0,t.isString)(n)?p.innerHTML=n:n&&p.appendChild(n),Array.prototype.slice.call(p.childNodes).forEach((function(t){d.insertNode(t)})),c.removeAllRanges(),c.addRange(d),l.focus(),r&&u&&(u.once('rte:disable',(function(){var t=u.find("[".concat(tv,"]"))[0];t&&(a.setSelected(t),t.removeAttributes(tv))})),u.trigger('disable'))}},n}();const ov=nv;var rv=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),iv=void 0&&(void 0).__assign||function(){return iv=Object.assign||function(t){for(var e,n=1,o=arguments.length;n0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]=0}))),v=this.get('onChange'),g={property:this,from:p,to:u,value:l,opts:n};i.__trgEv(i.events.propertyUpdate,g),v&&v(g),h&&this.__upTargetsStyle(((o={})[a]=l,o),n)},o.prototype.__upTargetsStyle=function(t,e){var n,o=null===(n=this.em)||void 0===n?void 0:n.get('StyleManager');null==o||o.addStyleTargets(vv(vv({},t),{__p:!!e.avoidStore}),e)},o.prototype._up=function(t,e){void 0===e&&(e={}),e.noTarget&&(e.__up=!0);var n=e.partial,o=gv(e,["partial"]);return t.__p=!(!o.avoidStore&&!n),this.set(t,vv(vv({},o),{avoidStore:t.__p}))},o.prototype.up=function(t,e){void 0===e&&(e={}),this.set(t,vv(vv({},e),{__up:!0}))},o.prototype.init=function(){},o.prototype.getId=function(){return this.get('id')},o.prototype.getType=function(){return this.get('type')},o.prototype.getName=function(){return this.get('property')},o.prototype.getLabel=function(t){var e;void 0===t&&(t={});var n=t.locale,o=void 0===n||n,r=this.getId(),i=this.get('name')||this.get('label');return o&&(null===(e=this.em)||void 0===e?void 0:e.t("styleManager.properties.".concat(r)))||i},o.prototype.getValue=function(t){void 0===t&&(t={});var e=t.noDefault,n=this.get('value');return this.hasValue()||e?n:this.getDefaultValue()},o.prototype.hasValue=function(e){void 0===e&&(e={});var n=e.noParent&&this.getParentTarget(),o=this.get('value');return!(0,t.isUndefined)(o)&&''!==o&&!n},o.prototype.hasValueParent=function(){return this.hasValue()&&!this.hasValue({noParent:!0})},o.prototype.getStyle=function(t){var n;void 0===t&&(t={});var o=this.getName();return(n={})[t.camelCase?(0,e.camelCase)(o):o]=this.__getFullValue(t),n},o.prototype.getDefaultValue=function(){var e=this.get('default');return"".concat((0,t.isUndefined)(e)?this.get('defaults'):e)},o.prototype.upValue=function(t,e){void 0===e&&(e={});var n=null===t||''===t?this.__getClearProps():this.__parseValue(t,e);return this._up(n,e)},o.prototype.isVisible=function(){return!!this.get('visible')},o.prototype.clear=function(t){return void 0===t&&(t={}),this._up(this.__getClearProps(),vv(vv({},t),{__clear:!0})),this},o.prototype.canClear=function(){var t=this.getParent();return t?t.__canClearProp(this):this.hasValue({noParent:!0})},o.prototype.getParent=function(){return this.__getParentProp()},o.prototype.isFull=function(){return!!this.get('full')},o.prototype.__parseValue=function(t,e){return this.parseValue(t,e)},o.prototype.__getClearProps=function(){return{value:'',important:!1}},o.prototype.setValue=function(t,e,n){void 0===e&&(e=!0),void 0===n&&(n={});var o=this.parseValue(t),r=!e;!r&&this.set({value:void 0},{avoidStore:r,silent:!0}),this.set(o,vv({avoidStore:r},n))},o.prototype.setValueFromInput=function(t,e,n){void 0===n&&(n={}),this.setValue(t,e,vv(vv({},n),{fromInput:1}))},o.prototype.parseValue=function(e,n){void 0===n&&(n={});var o={value:e},r='!important',i=this.get('functionName')||'';if((0,t.isString)(e)&&-1!==e.indexOf(r)&&(o.value=e.replace(r,'').trim(),o.important=!0),!i&&!n.complete)return o;var a=[],s="".concat(o.value).trim(),l=s.indexOf('(')+1,c=i||s.substring(0,l-1);if(c&&(o.functionName=c),!i||0===s.indexOf("".concat(i,"("))){var u=s.lastIndexOf(')');a.push(l),u>=0&&a.push(u),o.value=String.prototype.substring.apply(s,a)}if(n.numeric){var p=parseFloat(o.value);o.unit=o.value.replace(p,''),o.value=p}return o},o.prototype.__getFullValue=function(t){var e=(void 0===t?{}:t).withDefault;return!this.hasValue()&&e?this.getDefaultValue():this.getFullValue()},o.prototype.getFullValue=function(e,n){void 0===n&&(n={});var o=this.get('functionName'),r=this.getDefaultValue(),i=(0,t.isUndefined)(e)?this.get('value'):e,a=this.hasValue();if(i&&r&&i===r)return r;if(o&&a){var s='url'===o?"'".concat(i.replace(/'|"/g,''),"'"):i;i="".concat(o,"(").concat(s,")")}return a&&this.get('important')&&!n.skipImportant&&(i="".concat(i," !important")),i||''},o.prototype.__setParentTarget=function(t){this.up({parentTarget:t})},o.prototype.getParentTarget=function(){return this.get('parentTarget')||null},o.prototype.__parseFn=function(t){void 0===t&&(t='');var e=t.indexOf('(')+1,n=t.lastIndexOf(')');return{name:t.substring(0,e-1).trim(),value:String.prototype.substring.apply(t,[e,n>=0?n:void 0]).trim()}},o.prototype.__checkVisibility=function(n){var o=n.target,r=n.component,i=n.sector,a=n.sectors,s=r||o;if(!s)return!1;var l=this.getId(),c=this.getName(),u=this.attributes,p=u.requires,d=u.requiresParent,f=u.toRequire,h=u.isVisible,v=s.get('unstylable'),g=s.get('stylable-require'),y=s.get('stylable');if((0,t.isFunction)(h))return!!h({property:this,sector:i,target:o,component:r});if((0,t.isArray)(y)&&(y=y.indexOf(c)>=0),(0,t.isArray)(v)&&(y=v.indexOf(c)<0),f&&(y=!o||g&&(g.indexOf(l)>=0||g.indexOf(c)>=0)),a&&p){var m=(0,t.keys)(p);a.forEach((function(e){e.getProperties().forEach((function(e){if((0,t.includes)(m,e.id)){var n=p[e.id];y=y&&(0,t.includes)(n,e.get('value'))}}))}))}if(d){var b=r&&r.parent(),_=b&&b.getEl();if(_){var w=(0,e.hasWin)()?window.getComputedStyle(_):{};(0,t.each)(d,(function(e,n){y=y&&w[n]&&(0,t.includes)(e,w[n])}))}else y=!1}return!!y},o}(u.Kx);const bv=mv;mv.callParentInit=function(t,e,n,o){void 0===o&&(o={}),t.prototype.initialize.apply(e,[n,vv(vv({},o),{skipInit:1})])},mv.callInit=function(t,e,n){void 0===n&&(n={}),!n.skipInit&&t.init(e,n)};var _v=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),wv=void 0&&(void 0).__assign||function(){return wv=Object.assign||function(t){for(var e,n=1,o=arguments.length;n0},o.prototype.getLayer=function(t){return void 0===t&&(t=0),this.layers.at(t)||void 0},o.prototype.getSelectedLayer=function(){var t=this.get('selectedLayer');return t&&t.getIndex()>=0?t:void 0},o.prototype.selectLayer=function(t){return this.set('selectedLayer',t,{__select:!0})},o.prototype.selectLayerAt=function(t){void 0===t&&(t=0);var e=this.getLayer(t);return e&&this.selectLayer(e)},o.prototype.moveLayer=function(e,n){void 0===n&&(n=0);var o=this.layers,r=e?e.getIndex():-1;r>=0&&(0,t.isNumber)(n)&&n>=0&&n\n
\n ")},o.prototype.templateLabel=function(t){var e=this.pfx,n=this.em,o=t.parent,r=t.attributes,i=r.icon,a=void 0===i?'':i,s=r.info,l=void 0===s?'':s,c=null==n?void 0:n.getConfig().icons,u=(null==c?void 0:c.close)||'';return"\n \n ").concat(t.getLabel(),"\n \n ").concat(o?'':"
").concat(u,"
"),"\n ")},o.prototype.templateInput=function(t){return"\n
\n \n
\n ")},o.prototype.remove=function(){var t=this;return u.Ss.prototype.remove.apply(this,arguments),['em','input','$input','view'].forEach((function(e){return t[e]=null})),this.__destroyFn(this._getClbOpts()),this},o.prototype.updateStatus=function(){var t,e=this,n=e.model,o=e.pfx,r=e.ppfx,i=e.config,a="".concat(r,"four-color"),s="".concat(r,"color-warn"),l=this.$el.children(".".concat(o,"label")),c=this.getClearEl(),u=c?c.style:{};l.removeClass("".concat(a," ").concat(s)),u.display='none',n.hasValue({noParent:!0})&&i.highlightChanged?(l.addClass(a),i.clearProperties&&(u.display='')):n.hasValue()&&i.highlightComputed&&l.addClass(s),null===(t=this.parent)||void 0===t||t.updateStatus()},o.prototype.clear=function(t){t&&t.stopPropagation(),this.model.clear()},o.prototype.getClearEl=function(){return this.clearEl||(this.clearEl=this.el.querySelector("[".concat(Rv,"]"))),this.clearEl},o.prototype.inputValueChanged=function(t){t&&t.stopPropagation(),this.emit||this.model.upValue(t.target.value)},o.prototype.onValueChange=function(t,e,n){void 0===n&&(n={}),this.setValue(this.model.getFullValue(void 0,{skipImportant:!0})),this.updateStatus()},o.prototype.setValue=function(e){var n=this.model,o=(0,t.isUndefined)(e)||''===e?n.getDefaultValue():e;if(this.update)return this.__update(o);this.__setValueInput(o)},o.prototype.__setValueInput=function(t){var e=this.getInputEl();e&&(e.value=t)},o.prototype.getInputEl=function(){return this.input||(this.input=this.el.querySelector('input')),this.input},o.prototype.updateVisibility=function(){this.el.style.display=this.model.isVisible()?'':'none'},o.prototype.clearCached=function(){delete this.clearEl,delete this.input,delete this.$input},o.prototype.__unset=function(){var t=this.unset&&this.unset.bind(this);t&&t(this._getClbOpts())},o.prototype.__update=function(t){var e=this.update&&this.update.bind(this);e&&e(Lv(Lv({},this._getClbOpts()),{value:t}))},o.prototype.__change=function(){for(var t=[],e=0;e\n \n \n ")},e.prototype.remove=function(){var t;return null===(t=this.props)||void 0===t||t.remove(),Fv.prototype.remove.apply(this,arguments),this},e.prototype.onValueChange=function(){},e.prototype.onRender=function(){var t=this.pfx,e=this.model,n=e.get('properties');if(n.length&&!this.props){var o=e.isDetached(),r=new zv({config:Wv(Wv({},this.config),{highlightComputed:o,highlightChanged:o}),collection:n,parent:this});r.render(),this.$el.find("#".concat(t,"input-holder")).append(r.el),this.props=r}},e.prototype.clearCached=function(){Fv.prototype.clearCached.apply(this,arguments),delete this.props},e}(Fv);const qv=$v;var Gv=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Kv=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return Gv(n,e),n.prototype.events=function(){return{click:'select','click [data-close-layer]':'removeItem','mousedown [data-move-layer]':'initSorter','touchstart [data-move-layer]':'initSorter'}},n.prototype.template=function(){var t=this,e=t.pfx,n=t.ppfx,o=t.em,r=null==o?void 0:o.getConfig().icons,i=(null==r?void 0:r.close)||'',a=(null==r?void 0:r.move)||'';return"\n
\n
\n ").concat(a,"\n
\n
\n
\n
\n
\n
\n ").concat(i,"\n
\n
\n
\n ")},n.prototype.initialize=function(t){void 0===t&&(t={});var e=this.model,n=t.config||{};this.em=n.em,this.config=n,this.sorter=t.sorter,this.pfx=n.stylePrefix||'',this.ppfx=n.pStylePrefix||'',this.propertyView=t.propertyView;var o=this.propertyView.model;this.listenTo(e,'destroy remove',this.remove),this.listenTo(e,'change:values',this.updateLabel),this.listenTo(o,'change:selectedLayer',this.updateVisibility),e.view=this,e.set({droppable:0,draggable:1}),this.$el.data('model',e)},n.prototype.initSorter=function(){var t;null===(t=this.sorter)||void 0===t||t.startSort([{element:this.el}])},n.prototype.removeItem=function(t){t&&t.stopPropagation(),this.model.remove()},n.prototype.select=function(){this.model.select()},n.prototype.getPropertiesWrapper=function(){return this.propsWrapEl||(this.propsWrapEl=this.el.querySelector('[data-properties]')),this.propsWrapEl},n.prototype.getPreviewEl=function(){return this.previewEl||(this.previewEl=this.el.querySelector('[data-preview]')),this.previewEl},n.prototype.getLabelEl=function(){return this.labelEl||(this.labelEl=this.el.querySelector('[data-label]')),this.labelEl},n.prototype.updateLabel=function(){var e=this.model,n=e.getLabel();if(this.getLabelEl().innerHTML=n,e.hasPreview()){var o=this.getPreviewEl(),r=e.getStylePreview({number:{min:-3,max:3}}),i=(0,t.keys)(r).map((function(t){return"".concat(t,":").concat(r[t])})).join(';');o.setAttribute('style',i)}},n.prototype.updateVisibility=function(){var t,e=this,n=e.pfx,o=e.model,r=e.propertyView,i=this.getPropertiesWrapper(),a=o.isSelected();i.style.display=a?'':'none',this.$el[a?'addClass':'removeClass']("".concat(n,"active")),a&&i.appendChild(null===(t=r.props)||void 0===t?void 0:t.el)},n.prototype.render=function(){var t=this,e=t.el,n=t.pfx,o=t.model;return e.innerHTML=this.template(),e.className="".concat(n,"layer"),o.hasPreview()&&(e.querySelector('[data-preview-box]').style.display=''),this.updateLabel(),this.updateVisibility(),this},n}(u.Ss);const Yv=Kv;var Jv=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Xv=function(t){function e(e){var n=t.call(this,e)||this,o=n.collection,r=e.config||{},i=r.em,a=r.stylePrefix||'',s=r.pStylePrefix||'';n.config=r,n.pfx=a,n.ppfx=s,n.propertyView=e.propertyView,n.className="".concat(a,"layers ").concat(s,"field"),n.listenTo(o,'add',n.addTo),n.listenTo(o,'reset',n.reset),n.items=[];var l=n.createPlaceholder(r.pStylePrefix);n.$el.append(l);var c=null==i?void 0:i.Utils;return n.sorter=c?new c.StyleManagerSorter({em:i,containerContext:{container:n.el,containerSel:".".concat(a,"layers"),itemSel:".".concat(a,"layer"),pfx:r.pStylePrefix,document,placeholderElement:l},dragBehavior:{dragDirection:$n.A.Vertical,nested:!1}}):void 0,o.view=n,n.$el.data('model',o),n.$el.data('collection',o),n}return Jv(e,t),e.prototype.addTo=function(t){var e=this.collection.indexOf(t);this.addToCollection(t,null,e)},e.prototype.addToCollection=function(t,e,n){var o=e||null,r=this,i=r.propertyView,a=r.config,s=r.sorter,l=r.$el,c=new Yv({model:t,config:a,sorter:s,propertyView:i}),u=c.render().el;if(this.items.push(c),o)o.appendChild(u);else if(void 0!==n){var p='before';l.children().length===n&&(n--,p='after'),n<0?l.append(u):l.children().eq(n)[p](u)}else l.append(u);return u},e.prototype.reset=function(t,e){this.clearItems(),this.render()},e.prototype.remove=function(){return this.clearItems(),u.Ss.prototype.remove.apply(this,arguments),this},e.prototype.clearItems=function(){this.items.forEach((function(t){return t.remove()})),this.items=[]},e.prototype.render=function(){var t=this,e=this.$el,n=document.createDocumentFragment();return e.empty(),this.collection.forEach((function(e){return t.addToCollection(e,n)})),e.append(n),e.attr('class',this.className),this},e.prototype.createPlaceholder=function(t){var e=document.createElement('div'),n=document.createElement('div');return this.el.parentNode,e.className=t+'placeholder',e.style.display='none',e.style.pointerEvents='none',n.className=t+'placeholder-int',e.appendChild(n),e},e}(u.Ss);const Zv=Xv;var Qv=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),tg=void 0&&(void 0).__assign||function(){return tg=Object.assign||function(t){for(var e,n=1,o=arguments.length;n\n \n
\n \n ")},e.prototype.init=function(){var t=this.model;this.listenTo(t.layers,'change reset',this.updateStatus),this.listenTo(t,'change:isEmptyValue',this.updateStatus)},e.prototype.addLayer=function(){this.model.addLayer({},{at:0})},e.prototype.setValue=function(){},e.prototype.remove=function(){var t;return null===(t=this.layersView)||void 0===t||t.remove(),qv.prototype.remove.apply(this,arguments),this},e.prototype.clearCached=function(){qv.prototype.clearCached.apply(this,arguments),delete this.layersView},e.prototype.onRender=function(){var t=this,e=t.model,n=t.el,o=t.config,r=e.get('properties');if(r.length&&!this.props){var i=new zv({config:tg(tg({},o),{highlightComputed:!1,highlightChanged:!1}),collection:r,parent:this});i.render();var a=new Zv({collection:e.layers,config:o,propertyView:this});a.render(),n.querySelector('[data-layers-wrapper]').appendChild(a.el),this.props=i,this.layersView=a}},e}(qv);const ng=eg;var og=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),rg=void 0&&(void 0).__assign||function(){return rg=Object.assign||function(t){for(var e,n=1,o=arguments.length;n\n
\n
\n \n
\n
\n
\n
\n
\n
").concat(r,"
\n
\n \n ")},n.prototype.__setValueInput=function(t){var e=this.model,n=this.el,o=e.getDefaultValue(),r=n.querySelector('[data-preview-box]'),i=n.querySelector('[data-preview]');r.style.display=t&&t!==o?'':'none',i.style.backgroundImage=t||e.getDefaultValue()},n.prototype.openAssetManager=function(){var e,n=this,o=null===(e=this.em)||void 0===e?void 0:e.Assets;null==o||o.open({select:function(e,r){var i=(0,t.isString)(e)?e:e.get('src');n.model.upValue(i,{partial:!r}),r&&o.close()},types:['image'],accept:'image/*'})},n}(Fv);const ag=ig;var sg=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),lg=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return sg(e,t),e.prototype.templateInput=function(t){return''},e.prototype.init=function(){var t=this.model;this.listenTo(t,'change:unit',this.onValueChange),this.listenTo(t,'change:units',this.render)},e.prototype.setValue=function(t){},e.prototype.onRender=function(){var t=this,e=t.ppfx,n=t.model,o=t.el;if(!this.inputInst){var r=n.input;r.ppfx=e,r.render(),o.querySelector(".".concat(e,"fields")).appendChild(r.el),this.input=r.inputEl.get(0),this.inputInst=r}},e.prototype.clearCached=function(){Fv.prototype.clearCached.apply(this,arguments),this.inputInst=null},e}(Fv);const cg=lg;var ug=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),pg=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ug(e,t),e.prototype.setValue=function(t){var e;null===(e=this.inputInst)||void 0===e||e.setValue(t,{fromTarget:1,def:this.model.getDefaultValue()})},e.prototype.remove=function(){var t=this;cg.prototype.remove.apply(this,arguments);var e=this.inputInst;return e&&e.remove&&e.remove(),['inputInst','$color'].forEach((function(e){return t[e]=null})),this},e.prototype.__handleChange=function(t,e){this.model.upValue(t,{partial:e})},e.prototype.onRender=function(){var t;if(!this.inputInst){this.__handleChange=this.__handleChange.bind(this);var e=this,n=e.ppfx,o=e.model,r=e.em,i=e.el,a=new Dc({target:r,model:o,ppfx:n,onChange:this.__handleChange}).render();i.querySelector(".".concat(n,"fields")).appendChild(a.el),this.input=null===(t=a.inputEl)||void 0===t?void 0:t.get(0),this.inputInst=a}},e}(cg);const dg=pg;var fg=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),hg=void 0&&(void 0).__assign||function(){return hg=Object.assign||function(t){for(var e,n=1,o=arguments.length;n\n \n
\n
\n
\n \n ")},e.prototype.updateOptions=function(){delete this.input,this.onRender()},e.prototype.onRender=function(){var t=this.pfx,e=this.model,n=e.getOptions();if(!this.input){var o=[];n.forEach((function(t){var n=e.getOptionId(t),r=e.getOptionLabel(n),i=t.style?t.style.replace(/"/g,'"'):'',a=i?"style=\"".concat(i,"\""):'',s=n.replace(/"/g,'"');o.push(""))}));var r=this.el.querySelector("#".concat(t,"input-holder"));r.innerHTML=""),this.input=r.firstChild}},e.prototype.__setValueInput=function(t){var e=this.model,n=this.getInputEl(),o=e.getOptions()[0],r=o?e.getOptionId(o):'';n&&(n.value=t||r)},e}(Fv);var _g=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),wg=void 0&&(void 0).__assign||function(){return wg=Object.assign||function(t){for(var e,n=1,o=arguments.length;n")},e.prototype.onRender=function(){var t=this.pfx,e=this.ppfx,n=this.model,o="".concat(e,"radio-item-label"),r=n.getName(),i=n.getOptions(),a="".concat(t,"radio ").concat(t,"radio-").concat(r),s=n.cid;if(!this.input){var l=[];i.forEach((function(i){var c=i.className?"".concat(i.className," ").concat(t,"icon ").concat(o):'',u=n.getOptionId(i),p="".concat(r,"-").concat(u,"-").concat(s),d=c?'':n.getOptionLabel(u),f=i.title?"title=\"".concat(i.title,"\""):'',h=n.getValue()===u?'checked':'';l.push("\n
\n \n \n
\n "))}));var c=this.el.querySelector(".".concat(e,"field"));c.innerHTML="
").concat(l.join(''),"
"),this.input=c.firstChild}},e.prototype.__setValueInput=function(t){var e,n=this.model,o=t||n.getDefaultValue(),r=null===(e=this.getInputEl())||void 0===e?void 0:e.querySelector("[value=\"".concat(o,"\"]"));r&&(r.checked=!0)},e}(bg);const Og=Sg;var Tg=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Pg=void 0&&(void 0).__assign||function(){return Pg=Object.assign||function(t){for(var e,n=1,o=arguments.length;n\n \n \n ")},e.prototype.getSliderEl=function(){return this.slider||(this.slider=this.el.querySelector('input[type=range]')),this.slider},e.prototype.inputValueChanged=function(t){t.stopPropagation(),this.model.upValue(this.getSliderEl().value)},e.prototype.inputValueChangedSoft=function(t){t.stopPropagation(),this.model.upValue(this.getSliderEl().value,{partial:!0})},e.prototype.setValue=function(t){var e=this.model,n=e.parseValue(t);this.getSliderEl().value=''===t?e.getDefaultValue():parseFloat(n.value),cg.prototype.setValue.apply(this,arguments)},e.prototype.onRender=function(){cg.prototype.onRender.apply(this,arguments),this.model.get('showInput')||(this.inputInst.el.style.display='none')},e.prototype.clearCached=function(){cg.prototype.clearCached.apply(this,arguments),delete this.slider},e}(cg);const Ng=u.pM.extend(op).extend({extendViewApi:1,init:function(){var t=this.opts,e=this.em,n=t.module||(null==e?void 0:e.get('StyleManager'));n&&(n.__listenAdd(this,n.events.propertyAdd),n.__listenRemove(this,n.events.propertyRemove))},types:[{id:'stack',model:Mv,view:ng,isType:function(t){if(t&&'stack'==t.type)return t}},{id:'composite',model:Ov,view:qv,isType:function(t){if(t&&'composite'==t.type)return t}},{id:'file',model:bv,view:ag,isType:function(t){if(t&&'file'==t.type)return t}},{id:'color',model:bv,view:dg,isType:function(t){if(t&&'color'==t.type)return t}},{id:'select',model:yg,view:bg,isType:function(t){if(t&&'select'==t.type)return t}},{id:'radio',model:xg,view:Og,isType:function(t){if(t&&'radio'==t.type)return t}},{id:'slider',model:Mg,view:Ig,isType:function(t){if(t&&'slider'==t.type)return t}},{id:'integer',model:kg,view:cg,isType:function(t){if(t&&'integer'==t.type)return t}},{id:'number',model:kg,view:cg,isType:function(t){if(t&&'number'==t.type)return t}},{id:'base',model:bv,view:Fv,isType:function(t){return t.type='base',t}}]});var Rg=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Vg=void 0&&(void 0).__assign||function(){return Vg=Object.assign||function(t){for(var e,n=1,o=arguments.length;n\n
$","
\n
","
\n \n "],["\n
\n
$","
\n
","
\n
\n "])),s,s,a,s,o)},e.prototype.events=function(){return{'click [data-sector-title]':'toggle'}},e.prototype.updateOpen=function(){var t=this,e=t.$el,n=t.model,o=t.pfx,r=n.isOpen();e[r?'addClass':'removeClass']("".concat(o,"open")),this.getPropertiesEl().style.display=r?'':'none'},e.prototype.updateVisibility=function(){this.el.style.display=this.model.isVisible()?'':'none'},e.prototype.getPropertiesEl=function(){var t=this.$el,e=this.pfx;return t.find(".".concat(e,"properties")).get(0)},e.prototype.toggle=function(){var t=this.model;t.setOpen(!t.get('open'))},e.prototype.renderProperties=function(){var t=this.model,e=this.config,n=t.get('properties');if(n){var o=new zv({collection:n,config:e});this.$el.append(o.render().el)}},e.prototype.render=function(){var t=this,e=t.pfx,n=t.model,o=t.$el,r=n.getId(),i=n.getName();return o.html(this.template({pfx:e,label:i})),this.renderProperties(),o.attr('class',"".concat(e,"sector ").concat(e,"sector__").concat(r," no-select")),this.updateOpen(),this},e}(u.Ss);const ey=ty;var ny,oy=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),ry=function(t){function e(e){void 0===e&&(e={});var n=t.call(this,e)||this,o=e.module,r=e.config,i=n.collection;return n.pfx=(null==r?void 0:r.stylePrefix)||'',n.ppfx=(null==r?void 0:r.pStylePrefix)||'',n.config=r,n.module=o,n.listenTo(i,'add',n.addTo),n.listenTo(i,'reset',n.render),n}return oy(e,t),e.prototype.remove=function(){var t=this;return u.Ss.prototype.remove.apply(this,arguments),['config','module','em'].forEach((function(e){return t[e]={}})),this},e.prototype.addTo=function(t,e,n){void 0===n&&(n={}),this.addToCollection(t,null,n)},e.prototype.addToCollection=function(t,e,n){void 0===n&&(n={});var o=this.config,r=this.el,i=e||r,a=new ey({model:t,config:o}).render().el;return(0,Z.Sc)(i,a,n.at),a},e.prototype.render=function(){var t=this,e=this,n=e.$el,o=e.pfx,r=e.ppfx;n.empty();var i=document.createDocumentFragment();return this.collection.each((function(e){return t.addToCollection(e,i)})),n.append(i),n.addClass("".concat(o,"sectors ").concat(r,"one-bg ").concat(r,"two-color")),this},e}(u.Ss);const iy=ry;var ay=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),sy=void 0&&(void 0).__assign||function(){return sy=Object.assign||function(t){for(var e,n=1,o=arguments.length;n=0}))})):[]},m=function(t){return t?c.getRules().filter((function(e){return e.selectorsToString()===t})):[]};if(p)f=c.getRules("#".concat(p.getId())),h=m(p.get('tagName')),g=(l?y(l.getSelectors().getFullName(d)):[]).concat(h).concat(f);else f=l?c.getRules("#".concat(l.getId())):[],h=m((null==l?void 0:l.get('tagName'))||''),v=y(((null==l?void 0:l.getSelectors().getFullName(d))||[]).filter((function(t){return-1===e.getSelectors().getFullName(d).findIndex((function(e){return e===t}))})).concat(e.getSelectors().getFullName(d))),g=h.concat(f).concat(v);var b=g.filter((function(e){return(0,t.isUndefined)(r)?1:e.get('state')===r})).sort(u.sortRules).reverse();s=b.slice(b.indexOf(e)+1)}return s},o.prototype.addType=function(t,e){this.properties.addType(t,e)},o.prototype.getType=function(t){return this.properties.getType(t)},o.prototype.getTypes=function(){return this.properties.getTypes()},o.prototype.createType=function(t,e){var n=void 0===e?{}:e,o=n.model,r=void 0===o?{}:o,i=n.view,a=void 0===i?{}:i,s=this.config,l=this.getType(t);if(l)return new l.view(sy({model:new l.model(r),config:s},a))},o.prototype.render=function(){var t=this,e=t.config,n=t.em,o=t.SectView,r=o&&o.el;return this.SectView=new iy({el:r,em:n,config:e,module:this,collection:this.sectors}),this.SectView.render().el},o.prototype._logNoSector=function(t){var e=this.em;e&&e.logWarning("'".concat(t,"' sector not found"))},o.prototype.__emitCmpStyleUpdate=function(t,e){void 0===e&&(e={});var n=this.em;if(!t.__p){var o=this.getSelectedAll(),r=e.components||n.getSelectedAll(),i=Array.isArray(r)?r:[r],a=sy({},t);delete a.__p,i.forEach((function(t){return!o.includes(t)&&t.__onStyleChange(a)}))}},o.prototype.__upProps=function(t){var e=this;void 0===t&&(t={});var n=this.getSelected();if(n){var o=this.sectors,r=this.model.get('component'),i=this.getSelectedParents(),a=n.getStyle(),s=i.map((function(t){return{target:t,style:t.getStyle()}}));o.map((function(n){n.getProperties().map((function(n){e.__upProp(n,a,s,t)}))})),o.forEach((function(t){var e=t.getProperties();e.forEach((function(e){var i=e.__checkVisibility({target:n,sector:t,component:r,sectors:o.models});e.set('visible',i)}));var i=e.some((function(t){return t.isVisible()}));t.set('visible',i)}))}},o.prototype.__upProp=function(t,e,n,o){var r=this,i=t.getName(),a=e[i],s=xy(a),l='stack'===t.getType(),c='composite'===t.getType(),u=sy(sy({},o),{__up:!0}),p=!c&&!l,d=t,f=t,h=l?d.__getLayersFromStyle(e):[],v=c?f.__getPropsFromStyle(e):{},g=s?a:null,y=null;if(l&&null===h||c&&null===v){var m=l?'__getLayersFromStyle':'__getPropsFromStyle';if(_=n.filter((function(t){return null!==d[m](t.style)}))[0]){g=_.style[i],y=_.target;var b=d[m](_.style);l?h=b:v=b}}else if(!s){var _;g=null,(_=n.filter((function(t){return xy(t.style[i])}))[0])&&(g=_.style[i],y=_.target)}if(t.__setParentTarget(y),p&&t.__getFullValue()!==g&&t.upValue(g,u),l&&d.__setLayers(h||[],{isEmptyValue:d.isEmptyValueStyle(e)}),c){var w=f.getProperties();if(f.isDetached()){var x=f.__getPropsFromStyle(e,{byName:!0})||{},C=n.map((function(t){return sy(sy({},t),{style:f.__getPropsFromStyle(t.style,{byName:!0})||{}})}));w.map((function(t){return r.__upProp(t,x,C,o)}))}else f.__setProperties(v||{},u),f.getProperties().map((function(t){return t.__setParentTarget(y)}))}},o.prototype.destroy=function(){var t;[this.properties,this.sectors].forEach((function(t){t.reset(),t.stopListening()})),null===(t=this.SectView)||void 0===t||t.remove(),this.model.stopListening(),this.upAll.cancel()},o}(b);const Oy=Sy;var Ty=void 0&&(void 0).__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),Py=void 0&&(void 0).__assign||function(){return Py=Object.assign||function(t){for(var e,n=1,o=arguments.length;n0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]=r.getStepsBeforeSave()&&this.store().catch((function(t){return o.logError(t)}))},o.prototype.loadModule=function(t){var e=new t(this);return this.set(e.name,e),e.onLoad&&this.toLoad.push(e),this.modules.push(e),e},o.prototype.loadStorableModule=function(t){var e=this.loadModule(t);return this.storables.push(e),e},o.prototype.init=function(t,e){void 0===e&&(e={}),this.destroyed&&(this.initialize(e),this.destroyed=!1),this.set('Editor',t)},o.prototype.getEditor=function(){return this.get('Editor')},o.prototype.handleUpdates=function(t,e,n){var o=this;void 0===n&&(n={}),this.__skip||!this.loadTriggered||n.temporary||n.noCount||n.avoidStore||n.partial||(this.timedInterval&&clearTimeout(this.timedInterval),this.timedInterval=setTimeout((function(){var t=o.getDirtyCount()||0,e=(n.unset,Ny(n,["unset"]));o.set('changesCount',t+1,e)}),0))},o.prototype.changesUp=function(t){this.handleUpdates(0,0,t)},o.prototype.componentHovered=function(t,e,n){var o=this.previous('componentHovered');o&&this.trigger('component:unhovered',o,n),e&&this.trigger('component:hovered',e,n)},o.prototype.getSelected=function(){return this.selected.lastComponent()},o.prototype.getSelectedAll=function(){return this.selected.allComponents()},o.prototype.setSelected=function(e,n){var o=this;void 0===n&&(n={});var r=n.event,i=r&&(r.ctrlKey||r.metaKey),a=(r||{}).shiftKey,s=((0,t.isArray)(e)?e:[e]).map((function(t){var e,n;return(null===(n=null===(e=null==t?void 0:t.delegate)||void 0===e?void 0:e.select)||void 0===n?void 0:n.call(e,t))||t})).filter(Boolean),l=this.getSelectedAll(),c=this.getConfig().multipleSelection,u=(0,t.isArray)(e);!u&&e||this.removeSelected(l.filter((function(e){return!(0,t.contains)(s,e)}))),s.forEach((function(e){if(e&&(o.trigger($.I.selectBefore,e,n),!e.get('selectable')||n.abort)){if(!n.useValid)return;for(var r=e.parent();r&&!r.get('selectable');)r=r.parent();e=r}if(i&&c)return o.toggleSelected(e);if(a&&c){if(o.isEditing())return;o.clearSelection(o.Canvas.getWindow());var s,p,d=e.collection,f=e.index();if(o.getSelectedAll().forEach((function(e){var n=e.collection,o=e.index();n===d&&(of&&(p=(0,t.isUndefined)(p)?o:Math.min(p,o)))})),!(0,t.isUndefined)(s))for(;s!==f;)o.addSelected(d.at(s),n),s++;if(!(0,t.isUndefined)(p))for(;p!==f;)o.addSelected(d.at(p),n),p--;return o.addSelected(e,n)}!u&&o.removeSelected(l.filter((function(t){return t!==e}))),o.addSelected(e,n)}))},o.prototype.addSelected=function(e,n){var o=this;void 0===n&&(n={}),((0,t.isArray)(e)?e:[e]).forEach((function(e){var r=o.selected;if(e&&e.get('selectable')&&!e.parents().some((function(t){return r.hasComponent(t)}))&&(n.forceChange&&o.removeSelected(e,n),r.allComponents().filter((function(n){return(0,t.contains)(n.parents(),e)})).forEach((function(t){return o.removeSelected(t,n)})),r.addComponent(e,n),o.trigger($.I.select,e,n),o.Canvas.addSpot({type:W.F.Select,component:e}),n.activate)){var i=e.getView();(null==i?void 0:i.rendered)?i.onActive(n.event):e.once($.I.render,(function(t){return t.view.onActive(n.event)}))}}))},o.prototype.removeSelected=function(e,n){var o=this;void 0===n&&(n={}),this.selected.removeComponent(e,n),((0,t.isArray)(e)?e:[e]).forEach((function(t){return o.Canvas.removeSpots({type:W.F.Select,component:t})}))},o.prototype.toggleSelected=function(e,n){var o=this;void 0===n&&(n={}),((0,t.isArray)(e)?e:[e]).forEach((function(t){o.selected.hasComponent(t)?o.removeSelected(t,n):o.addSelected(t,n)}))},o.prototype.setHovered=function(t,e){var n=this;void 0===e&&(e={});var o=function(t,e){var o=n,r=o.config,i=o.Canvas,a=n.getHovered(),s=n.getSelectedAll(),l=W.F.Hover,c=W.F.Spacing;n.set('componentHovered',t||null,e),a&&(i.removeSpots({type:l,component:a}),i.removeSpots({type:c,component:a})),t&&(i.addSpot({type:l,component:t}),s.includes(t)&&!r.showOffsetsSelected||i.addSpot({type:c,component:t}))};if(!t)return o();var r='component:hover';if(e.forceChange&&o(),this.trigger("".concat(r,":before"),t,e),!t.get('hoverable')){if(!e.useValid||e.abort)return;for(var i=t.parent();i&&!i.get('hoverable');)i=i.parent();t=i}e.abort||(o(t,e),this.trigger(r,t,e))},o.prototype.getHovered=function(){return this.get('componentHovered')},o.prototype.setComponents=function(t,e){return void 0===e&&(e={}),this.Components.setComponents(t,e)},o.prototype.getComponents=function(){var t=this.Components,e=this.CodeManager;if(t&&e){var n=t.getComponents();return e.getCode(n,'json')}},o.prototype.setStyle=function(t,e){void 0===e&&(e={});var n=this.Css;return n.clear(e),n.getAll().add(t,e),this},o.prototype.addStyle=function(e,n){void 0===n&&(n={});var o=this.getStyle().add(e,n);return(0,t.isArray)(o)?o:[o]},o.prototype.getStyle=function(){return this.Css.getAll()},o.prototype.setState=function(t){return this.set('state',t),this},o.prototype.getState=function(){return this.get('state')||''},o.prototype.getHtml=function(t){void 0===t&&(t={});var e=this.config,n=e.optsHtml,o=e.jsInHtml?this.getJs(t):'',r=t.component||this.Components.getComponent(),i=r?this.CodeManager.getCode(r,'html',Dy(Dy({},n),t)):'';return i+=o?"