code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
# 1. update in global script
# <script defer data-api="https://frappecloud.com/api/event" data-domain="frappe.io" src="https://frappecloud.com/js/script.js"></script>
# 2. set blank header and footer from website settings
# 3. Update urls using following script from frappe console https://frappecloud.com/dashboard/benches/bench-1700/sites
import frappe
url_start = "pages/"
replace_url_start = ""
def update_block_href(blocks):
for block in blocks:
if block.get("attributes") and block.get("attributes").get("href") and block.get("attributes").get("href").startswith(f'/{url_start}'):
print(block.get("attributes").get("href"))
block["attributes"]["href"] = block["attributes"]["href"].replace(url_start, replace_url_start)
if "children" in block:
update_block_href(block["children"])
def execute():
pages = frappe.get_all("Builder Page", fields=["name", "route", "blocks", "draft_blocks", "page_data_script"])
for page in pages:
frappe.db.set_value("Builder Page", page.name, "route", page.route.replace(url_start, replace_url_start), update_modified=False)
blocks = frappe.parse_json(page.get("blocks"))
if blocks:
update_block_href(blocks)
frappe.db.set_value("Builder Page", page.name, "blocks", frappe.as_json(blocks, indent=None), update_modified=False)
draft_blocks = frappe.parse_json(page.get("draft_blocks"))
if draft_blocks:
update_block_href(draft_blocks)
frappe.db.set_value("Builder Page", page.name, "draft_blocks", frappe.as_json(draft_blocks, indent=None), update_modified=False)
if page.page_data_script:
page_data_script = page.page_data_script.replace(url_start, replace_url_start)
frappe.db.set_value("Builder Page", page.name, "page_data_script", page_data_script, update_modified=False)
components = frappe.get_all("Builder Component", fields=["name", "block"])
for component in components:
component_block = frappe.parse_json(component.get("block"))
if component_block:
update_block_href([component_block])
frappe.db.set_value("Builder Component", component.name, "block", frappe.as_json(component_block, indent=None), update_modified=False)
# def extend_with_component(block, extended_from_component, component_children):
# reset_block(block)
# for index, child in enumerate(block.get("children") or []):
# child["isChildOfComponent"] = extended_from_component
# component_child = component_children[index]
# if component_child:
# child["referenceBlockId"] = component_child.get("blockId")
# extend_with_component(child, extended_from_component, component_child.get("children"))
# def reset_with_component(block, extended_with_component, component_children):
# reset_block(block)
# block["children"] = []
# for component_child in component_children:
# block_component = get_block_copy(component_child)
# block_component["isChildOfComponent"] = extended_with_component
# block_component["referenceBlockId"] = component_child.get("blockId")
# child_block = block["children"].append(block_component)
# reset_with_component(child_block, extended_with_component, component_child.get("children"))
# def sync_block_with_component(parent_block, block, component_name, component_children):
# for component_child in component_children:
# block_exists = find_component_block(component_child.get("blockId"), parent_block.get("children"))
# if not block_exists:
# block_component = get_block_copy(component_child)
# block_component["isChildOfComponent"] = component_name
# block_component["referenceBlockId"] = component_child.get("blockId")
# reset_block(block_component)
# reset_with_component(block_component, component_name, component_child.get("children"))
# block["children"].append(block_component)
# for child in block.get("children") or []:
# component_child = component_children.find(lambda c: c.get("blockId") == child.get("referenceBlockId"))
# if component_child:
# sync_block_with_component(parent_block, child, component_name, component_child.get("children"))
# def find_component_block(block_id, blocks):
# for block in blocks:
# if block.get("referenceBlockId") == block_id:
# return block
# if block.get("children"):
# found = find_component_block(block_id, block.get("children"))
# if found:
# return found
# return None
# def reset_block(block, reset_children=True):
# block["blockId"] = block.generateId()
# block["baseStyles"] = {}
# block["rawStyles"] = {}
# block["mobileStyles"] = {}
# block["tabletStyles"] = {}
# block["attributes"] = {}
# block["customAttributes"] = {}
# block["classes"] = []
# if reset_children:
# for child in block.get("children") or []:
# reset_block(child, reset_children)
|
2302_79757062/builder
|
builder/builder/doctype/builder_page/patches/script_to_update_links.py
|
Python
|
agpl-3.0
| 4,706
|
# Copyright (c) 2023, Frappe Technologies Pvt Ltd and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
class BuilderPageClientScript(Document):
pass
|
2302_79757062/builder
|
builder/builder/doctype/builder_page_client_script/builder_page_client_script.py
|
Python
|
agpl-3.0
| 223
|
// Copyright (c) 2023, Frappe Technologies Pvt Ltd and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Builder Settings", {
// refresh(frm) {
// },
// });
|
2302_79757062/builder
|
builder/builder/doctype/builder_settings/builder_settings.js
|
JavaScript
|
agpl-3.0
| 197
|
import os
import frappe
from frappe.model.document import Document
from frappe.utils import get_files_path
class BuilderSettings(Document):
def on_update(self):
self.handle_script_update("script", "JavaScript", "js", "page_scripts")
self.handle_script_update("style", "css", "css", "page_styles")
if self.has_value_changed("home_page"):
frappe.cache.delete_key("home_page")
def handle_script_update(self, attribute, script_type, extension, folder_name):
if self.has_value_changed(attribute):
if getattr(self, attribute):
self.update_script_file(attribute, script_type, extension, folder_name)
else:
self.delete_script_file(attribute, extension, folder_name)
def update_script_file(self, attribute, script_type, extension, folder_name):
script = self.script if script_type == "JavaScript" else self.style
file_name = f"builder-asset-{attribute}.{extension}"
file_path = self.get_file_path(file_name, folder_name)
self.write_to_file(file_path, script)
public_url = f"/files/{folder_name}/{file_name}?v={frappe.generate_hash(length=10)}"
self.db_set(f"{attribute}_public_url", public_url, commit=True)
def delete_script_file(self, script_type, extension, folder_name):
file_name = f"builder-asset-{script_type}.{extension}"
file_path = self.get_file_path(file_name, folder_name)
if os.path.exists(file_path):
os.remove(file_path)
self.db_set(f"{script_type.lower()}_public_url", "", commit=True)
def get_file_path(self, file_name, folder_name):
file_path = get_files_path(f"{folder_name}/{file_name}")
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def write_to_file(self, file_path, content):
with open(file_path, "w") as f:
f.write(content)
def get_website_user_home_page(session_user=None):
home_page = frappe.get_cached_value("Builder Settings", None, "home_page")
return home_page
|
2302_79757062/builder
|
builder/builder/doctype/builder_settings/builder_settings.py
|
Python
|
agpl-3.0
| 1,885
|
import frappe
from frappe.model.rename_doc import rename_doc
def execute():
if frappe.db.exists("DocType", "Web Page Beta") and not frappe.db.exists(
"DocType", "Builder Page"
):
rename_doc("DocType", "Web Page Beta", "Builder Page")
|
2302_79757062/builder
|
builder/builder/patches/rename_web_page_beta_to_builder_page.py
|
Python
|
agpl-3.0
| 242
|
import frappe
from frappe.model.rename_doc import rename_doc
def execute():
if frappe.db.exists("DocType", "Web Page Component") and not frappe.db.exists(
"DocType", "Builder Component"
):
rename_doc("DocType", "Web Page Component", "Builder Component")
|
2302_79757062/builder
|
builder/builder/patches/rename_web_page_component_to_builder_component.py
|
Python
|
agpl-3.0
| 262
|
import frappe
from . import __version__ as app_version
app_name = "builder"
app_title = "Frappe Builder"
app_publisher = "Frappe Technologies Pvt Ltd"
app_description = "An easier way to build web pages for your needs!"
app_email = "suraj@frappe.io"
app_license = "GNU Affero General Public License v3.0"
develop_version = "1.x.x-develop"
# Includes in <head>
# ------------------
# include js, css files in header of desk.html
# app_include_css = "/assets/builder/css/builder.css"
app_include_js = "/assets/builder/js/builder.js"
# include js, css files in header of web template
# web_include_css = "/assets/builder/css/builder.css"
# web_include_js = "/assets/builder/js/builder.js"
# include custom scss in every website theme (without file extension ".scss")
# website_theme_scss = "builder/public/scss/website"
# include js, css files in header of web form
# webform_include_js = {"doctype": "public/js/doctype.js"}
# webform_include_css = {"doctype": "public/css/doctype.css"}
# include js in page
# page_js = {"page" : "public/js/file.js"}
# include js in doctype views
# doctype_js = {"doctype" : "public/js/doctype.js"}
# doctype_list_js = {"doctype" : "public/js/doctype_list.js"}
# doctype_tree_js = {"doctype" : "public/js/doctype_tree.js"}
# doctype_calendar_js = {"doctype" : "public/js/doctype_calendar.js"}
# Home Pages
# ----------
# application home page (will override Website Settings)
# home_page = "/p/home"
# website user home page (by Role)
# Generators
# ----------
# automatically create page for each record of this doctype
website_generators = ["Builder Page"]
# Jinja
# ----------
# add methods and filters to jinja environment
# jinja = {
# "methods": "builder.utils.jinja_methods",
# "filters": "builder.utils.jinja_filters"
# }
# Installation
# ------------
# before_install = "builder.install.before_install"
after_install = "builder.install.after_install"
after_migrate = "builder.install.after_migrate"
# Uninstallation
# ------------
# before_uninstall = "builder.uninstall.before_uninstall"
# after_uninstall = "builder.uninstall.after_uninstall"
# Desk Notifications
# ------------------
# See frappe.core.notifications.get_notification_config
# notification_config = "builder.notifications.get_notification_config"
# Permissions
# -----------
# Permissions evaluated in scripted ways
# permission_query_conditions = {
# "Event": "frappe.desk.doctype.event.event.get_permission_query_conditions",
# }
#
# has_permission = {
# "Event": "frappe.desk.doctype.event.event.has_permission",
# }
# DocType Class
# ---------------
# Override standard doctype classes
# override_doctype_class = {
# "ToDo": "custom_app.overrides.CustomToDo"
# }
# Document Events
# ---------------
# Hook on document methods and events
# doc_events = {
# "*": {
# "on_update": "method",
# "on_cancel": "method",
# "on_trash": "method"
# }
# }
# Scheduled Tasks
# ---------------
# scheduler_events = {
# "all": [
# "builder.tasks.all"
# ],
# "daily": [
# "builder.tasks.daily"
# ],
# "hourly": [
# "builder.tasks.hourly"
# ],
# "weekly": [
# "builder.tasks.weekly"
# ],
# "monthly": [
# "builder.tasks.monthly"
# ],
# }
# Testing
# -------
# before_tests = "builder.install.before_tests"
# Overriding Methods
# ------------------------------
#
# override_whitelisted_methods = {
# "frappe.desk.doctype.event.event.get_events": "builder.event.get_events"
# }
#
# each overriding function accepts a `data` argument;
# generated from the base implementation of the doctype dashboard,
# along with any modifications made in other Frappe apps
# override_doctype_dashboards = {
# "Task": "builder.task.get_dashboard_data"
# }
# exempt linked doctypes from being automatically cancelled
#
# auto_cancel_exempted_doctypes = ["Auto Repeat"]
# Ignore links to specified DocTypes when deleting documents
# -----------------------------------------------------------
# ignore_links_on_delete = ["Communication", "ToDo"]
# User Data Protection
# --------------------
# user_data_fields = [
# {
# "doctype": "{doctype_1}",
# "filter_by": "{filter_by}",
# "redact_fields": ["{field_1}", "{field_2}"],
# "partial": 1,
# },
# {
# "doctype": "{doctype_2}",
# "filter_by": "{filter_by}",
# "partial": 1,
# },
# {
# "doctype": "{doctype_3}",
# "strict": False,
# },
# {
# "doctype": "{doctype_4}"
# }
# ]
# Authentication and authorization
# --------------------------------
# auth_hooks = [
# "builder.auth.validate"
# ]
builder_path = frappe.conf.builder_path or "builder"
website_route_rules = [
{"from_route": f"/{builder_path}/<path:app_path>", "to_route": "_builder"},
{"from_route": f"/{builder_path}", "to_route": "_builder"},
]
website_path_resolver = "builder.builder.doctype.builder_page.builder_page.resolve_path"
page_renderer = "builder.builder.doctype.builder_page.builder_page.BuilderPageRenderer"
get_web_pages_with_dynamic_routes = (
"builder.builder.doctype.builder_page.builder_page.get_web_pages_with_dynamic_routes"
)
get_website_user_home_page = (
"builder.builder.doctype.builder_settings.builder_settings.get_website_user_home_page"
)
add_to_apps_screen = [
{
"name": "builder",
"logo": "/assets/builder/frontend/builder_logo.png",
"title": "Builder",
"route": f"/{builder_path}",
"has_permission": "builder.api.check_app_permission",
}
]
|
2302_79757062/builder
|
builder/hooks.py
|
Python
|
agpl-3.0
| 5,320
|
import frappe
import requests
import html as html_parser
# TODO: Find better alternative
# Note: while working locally, "preview.frappe.cloud" won't be able to generate preview properly since it can't access local server for assets
# So, for local development, better to use local server for preview generation
# (https://github.com/frappe/preview_generator)
PREVIEW_GENERATOR_URL = (
frappe.conf.preview_generator_url
or "https://preview.frappe.cloud/api/method/preview_generator.api.generate_preview"
)
def generate_preview(html, output_path):
escaped_html = html_parser.escape(html)
response = requests.post(PREVIEW_GENERATOR_URL, json={
'html': escaped_html,
})
if response.status_code == 200:
with open(output_path, 'wb') as f:
f.write(response.content)
else:
exception = response.json().get('exc')
raise Exception(frappe.parse_json(exception)[0])
|
2302_79757062/builder
|
builder/html_preview_image.py
|
Python
|
agpl-3.0
| 874
|
import frappe
from frappe.core.api.file import create_new_folder
from builder.utils import sync_block_templates, sync_page_templates
def after_install():
create_new_folder("Builder Uploads", "Home")
sync_page_templates()
sync_block_templates()
def after_migrate():
sync_page_templates()
sync_block_templates()
|
2302_79757062/builder
|
builder/install.py
|
Python
|
agpl-3.0
| 320
|
frappe.search.utils.make_function_searchable(
() => window.open("/builder"),
"Open Builder",
);
|
2302_79757062/builder
|
builder/public/js/builder.js
|
JavaScript
|
agpl-3.0
| 97
|
<!DOCTYPE html>
<!-- Made with Frappe Builder -->
<html lang="en">
<head>
<base href="{{ base_url }}">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{title}}</title>
<link rel="icon" href="{{ favicon_light or favicon or '/assets/builder/images/frappe_black.png' }}" media="(prefers-color-scheme: light)"/>
<link rel="icon" href="{{ favicon_dark or favicon or '/assets/builder/images/frappe_white.png' }}" media="(prefers-color-scheme: dark)"/>
{% block meta_block %}{% include "templates/includes/meta_block.html" %}{% endblock %}
<link rel="stylesheet" href="/assets/builder/reset.css?v=1" media="screen">
<link rel="preconnect" href="https://fonts.googleapis.com">
{% for (font, options) in fonts.items() %}<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family={{ font }}:wght@{{ ";".join(options.weights) }}&display=swap" media="screen">{% endfor %}
{{ style }}
{% block style %}
{%- if styles -%}
{% for style_path in styles %}
<link rel="stylesheet" href="{{ style_path }}">
{% endfor %}
{%- endif -%}
{%- endblock %}
</head>
{% block page_content %}
{{ content }}
{% endblock %}
</html>
|
2302_79757062/builder
|
builder/templates/generators/webpage.html
|
HTML
|
agpl-3.0
| 1,247
|
{% block script %}
{%- if scripts -%}
{% for script_path in scripts %}
<script src="{{ script_path }}"></script>
{% endfor %}
{%- endif -%}
{%- endblock %}
<a class="__editor_link" rel="nofollow" href="{{ editor_link }}" target="frappe-builder" style="position: fixed; bottom: 40px; right: 50px; height: 35px; width: 35px; display: none; opacity: 0.1;">
<img src="/assets/builder/frontend/builder_logo.png" style="box-shadow: #bdbdbd 0px 0px 5px; border-radius: 10px;" alt="Frappe" />
</a>
<script>window.page_data = {{ (page_data or {})|tojson|safe }}</script>
<script>if (!window.frappe) window.frappe = {};</script>
<!-- csrf_token -->
{% if enable_view_tracking and not preview %}
<script>
if (navigator.doNotTrack != 1) {document.addEventListener("DOMContentLoaded", function() {let b=getBrowser(),q=getQueryParams();import('https://openfpcdn.io/fingerprintjs/v3').then(f=>f.load()).then(fp=>fp.get()).then(r=>{const d={referrer:document.referrer,browser:b.name,version:b.version,user_tz:Intl.DateTimeFormat().resolvedOptions().timeZone,source:q.source,medium:q.medium,campaign:q.campaign,visitor_id:r.visitorId};makeViewLog(d)})})}function getBrowser(){const ua=navigator.userAgent,b={};if(ua.indexOf("Chrome")!==-1){b.name="Chrome";b.version=parseInt(ua.split("Chrome/")[1])}else if(ua.indexOf("Firefox")!==-1){b.name="Firefox";b.version=parseInt(ua.split("Firefox/")[1])}else{b.name="Unknown";b.version="Unknown"}return b}function getQueryParams(){const q={},p=window.location.search.substring(1).split("&");p.forEach(p=>{const [k,v]=p.split("=");q[k]=v});return q}function makeViewLog(d){fetch('/api/method/frappe.website.doctype.web_page_view.web_page_view.make_view_log',{method:'POST',headers:{'Content-Type':'application/json',"X-Frappe-CSRF-Token": frappe.csrf_token},body:JSON.stringify(d)})}
</script>
{% endif %}
<script>
if(document.cookie.indexOf("user_id=Guest")===-1){const e=document.querySelector(".__editor_link");e.style.display="block";e.addEventListener("mouseover",()=>e.style.opacity="1");e.addEventListener("mouseout",()=>e.style.opacity="0.1");}else{document.querySelector(".__editor_link")?.remove();}
</script>
|
2302_79757062/builder
|
builder/templates/generators/webpage_scripts.html
|
HTML
|
agpl-3.0
| 2,145
|
import glob
import os
import re
import shutil
import socket
import subprocess
from os.path import join
from urllib.parse import unquote, urlparse
import frappe
from frappe.modules.import_file import import_file_by_path
from frappe.utils import get_site_base_path, get_site_path, get_url
from frappe.utils.safe_exec import (
SERVER_SCRIPT_FILE_PREFIX,
FrappeTransformer,
NamespaceDict,
get_python_builtins,
get_safe_globals,
is_safe_exec_enabled,
safe_exec,
safe_exec_flags,
)
from RestrictedPython import compile_restricted
def get_doc_as_dict(doctype, name):
assert isinstance(doctype, str)
assert isinstance(name, str)
return frappe.get_doc(doctype, name).as_dict()
def get_cached_doc_as_dict(doctype, name):
assert isinstance(doctype, str)
assert isinstance(name, str)
return frappe.get_cached_doc(doctype, name).as_dict()
def make_safe_get_request(url, **kwargs):
parsed = urlparse(url)
parsed_ip = socket.gethostbyname(parsed.hostname)
if parsed_ip.startswith("127", "10", "192", "172"):
return
return frappe.integrations.utils.make_get_request(url, **kwargs)
def safe_get_list(*args, **kwargs):
if args and len(args) > 1 and isinstance(args[1], list):
args = list(args)
args[1] = remove_unsafe_fields(args[1])
fields = kwargs.get("fields", [])
if fields:
kwargs["fields"] = remove_unsafe_fields(fields)
return frappe.db.get_list(
*args,
**kwargs,
)
def safe_get_all(*args, **kwargs):
kwargs["ignore_permissions"] = True
if "limit_page_length" not in kwargs:
kwargs["limit_page_length"] = 0
return safe_get_list(*args, **kwargs)
def remove_unsafe_fields(fields):
return [f for f in fields if "(" not in f]
def get_safer_globals():
safe_globals = get_safe_globals()
out = NamespaceDict(
json=safe_globals["json"],
as_json=frappe.as_json,
dict=safe_globals["dict"],
frappe=NamespaceDict(
db=NamespaceDict(
count=frappe.db.count,
exists=frappe.db.exists,
get_all=safe_get_all,
get_list=safe_get_list,
get_single_value=frappe.db.get_single_value,
),
make_get_request=make_safe_get_request,
get_doc=get_doc_as_dict,
get_cached_doc=get_cached_doc_as_dict,
_=frappe._,
session=safe_globals["frappe"]["session"],
),
)
out._write_ = safe_globals["_write_"]
out._getitem_ = safe_globals["_getitem_"]
out._getattr_ = safe_globals["_getattr_"]
out._getiter_ = safe_globals["_getiter_"]
out._iter_unpack_sequence_ = safe_globals["_iter_unpack_sequence_"]
# add common python builtins
out.update(get_python_builtins())
return out
def safer_exec(
script: str,
_globals: dict | None = None,
_locals: dict | None = None,
*,
script_filename: str | None = None,
):
exec_globals = get_safer_globals()
if _globals:
exec_globals.update(_globals)
filename = SERVER_SCRIPT_FILE_PREFIX
if script_filename:
filename += f": {frappe.scrub(script_filename)}"
with safe_exec_flags():
# execute script compiled by RestrictedPython
exec(
compile_restricted(script, filename=filename, policy=FrappeTransformer),
exec_globals,
_locals,
)
return exec_globals, _locals
def sync_page_templates():
print("Syncing Builder Components")
builder_component_path = frappe.get_module_path("builder", "builder_component")
make_records(builder_component_path)
print("Syncing Builder Scripts")
builder_script_path = frappe.get_module_path("builder", "builder_script")
make_records(builder_script_path)
print("Syncing Builder Page Templates")
builder_page_template_path = frappe.get_module_path("builder", "builder_page_template")
make_records(builder_page_template_path)
def sync_block_templates():
print("Syncing Builder Block Templates")
builder_block_template_path = frappe.get_module_path("builder", "builder_block_template")
make_records(builder_block_template_path)
def make_records(path):
if not os.path.isdir(path):
return
for fname in os.listdir(path):
if os.path.isdir(join(path, fname)) and fname != "__pycache__":
import_file_by_path(f"{path}/{fname}/{fname}.json")
# def generate_tailwind_css_file_from_html(html):
# # execute tailwindcss cli command to generate css file
# # create temp folder
# temp_folder = os.path.join(get_site_base_path(), "temp")
# if os.path.exists(temp_folder):
# shutil.rmtree(temp_folder)
# os.mkdir(temp_folder)
# # create temp html file
# temp_html_file_path = os.path.join(temp_folder, "temp.html")
# with open(temp_html_file_path, "w") as f:
# f.write(html)
# # place tailwind.css file in public folder
# tailwind_css_file_path = os.path.join(get_site_path(), "public", "files", "tailwind.css")
# # create temp config file
# temp_config_file_path = os.path.join(temp_folder, "tailwind.config.js")
# with open(temp_config_file_path, "w") as f:
# f.write("module.exports = {content: ['./temp.html']}")
# # run tailwindcss cli command in production mode
# subprocess.run(
# ["npx", "tailwindcss", "-o", tailwind_css_file_path, "--config", temp_config_file_path, "--minify"]
# )
def copy_img_to_asset_folder(block, self):
if block.get("element") == "img":
src = block.get("attributes", {}).get("src")
site_url = get_url()
if src and (src.startswith(f"{site_url}/files") or src.startswith("/files")):
# find file doc
if src.startswith(f"{site_url}/files"):
src = src.split(f"{site_url}")[1]
# url decode
src = unquote(src)
print(f"src: {src}")
files = frappe.get_all("File", filters={"file_url": src}, fields=["name"])
print(f"files: {files}")
if files:
_file = frappe.get_doc("File", files[0].name)
# copy physical file to new location
assets_folder_path = get_template_assets_folder_path(self)
shutil.copy(_file.get_full_path(), assets_folder_path)
block["attributes"]["src"] = f"/builder_assets/{self.name}/{src.split('/')[-1]}"
for child in block.get("children", []):
copy_img_to_asset_folder(child, self)
def get_template_assets_folder_path(page_doc):
path = os.path.join(frappe.get_app_path("builder"), "www", "builder_assets", page_doc.name)
if not os.path.exists(path):
os.makedirs(path)
return path
def get_builder_page_preview_paths(page_doc):
public_path, public_path = None, None
if page_doc.is_template:
local_path = os.path.join(get_template_assets_folder_path(page_doc), "preview.jpeg")
public_path = f"/builder_assets/{page_doc.name}/preview.jpeg"
else:
file_name = f"{page_doc.name}-preview.jpeg"
local_path = os.path.join(frappe.local.site_path, "public", "files", file_name)
random_hash = frappe.generate_hash(length=5)
public_path = f"/files/{file_name}?v={random_hash}"
return public_path, local_path
def is_component_used(blocks, component_id):
blocks = frappe.parse_json(blocks)
if not isinstance(blocks, list):
blocks = [blocks]
for block in blocks:
if not block:
continue
if block.get("extendedFromComponent") == component_id:
return True
elif block.get("children"):
return is_component_used(block.get("children"), component_id)
return False
def escape_single_quotes(text):
return (text or "").replace("'", "\\'")
def camel_case_to_kebab_case(text, remove_spaces=False):
if not text:
return ""
text = re.sub(r"(?<!^)(?=[A-Z])", "-", text).lower()
if remove_spaces:
text = text.replace(" ", "")
return text
def execute_script(script, _locals, script_filename):
if is_safe_exec_enabled():
safe_exec(script, None, _locals, script_filename=script_filename)
else:
safer_exec(script, None, _locals, script_filename=script_filename)
def get_dummy_blocks():
return [
{
"element": "div",
"extendedFromComponent": "component-1",
"children": [
{
"element": "div",
"children": [
{
"element": "div",
"extendedFromComponent": "component-2",
"children": [],
},
],
},
],
},
]
|
2302_79757062/builder
|
builder/utils.py
|
Python
|
agpl-3.0
| 7,809
|
import frappe
from frappe.utils.telemetry import capture
from builder.hooks import builder_path
no_cache = 1
def get_context(context):
csrf_token = frappe.sessions.get_csrf_token()
frappe.db.commit()
context.csrf_token = csrf_token
context.site_name = frappe.local.site
context.builder_path = builder_path
# developer mode
context.is_developer_mode = frappe.conf.developer_mode
if frappe.session.user != "Guest":
capture("active_site", "builder")
|
2302_79757062/builder
|
builder/www/_builder.py
|
Python
|
agpl-3.0
| 461
|
#!bin/bash
if [ -d "/home/frappe/frappe-bench/apps/frappe" ]; then
echo "Bench already exists, skipping init"
cd frappe-bench
bench start
else
echo "Creating new bench..."
fi
bench init --skip-redis-config-generation frappe-bench --version version-15
cd frappe-bench
# Use containers instead of localhost
bench set-mariadb-host mariadb
bench set-redis-cache-host redis:6379
bench set-redis-queue-host redis:6379
bench set-redis-socketio-host redis:6379
# Remove redis, watch from Procfile
sed -i '/redis/d' ./Procfile
sed -i '/watch/d' ./Procfile
bench get-app builder --branch develop
bench new-site builder.localhost \
--force \
--mariadb-root-password 123 \
--admin-password admin \
--no-mariadb-socket
bench --site builder.localhost install-app builder
bench --site builder.localhost set-config developer_mode 1
bench --site builder.localhost clear-cache
bench --site builder.localhost set-config mute_emails 1
bench use builder.localhost
bench start
|
2302_79757062/builder
|
docker/init.sh
|
Shell
|
agpl-3.0
| 979
|
describe("Builder Landing", () => {
before(() => {
cy.login();
});
it("Open builder page", () => {
cy.visit("builder/home");
});
});
|
2302_79757062/builder
|
frontend/cypress/e2e/landing.cy.js
|
JavaScript
|
agpl-3.0
| 140
|
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
Cypress.Commands.add("login", (email, password) => {
if (!email) {
email = Cypress.config("testUser") || "Administrator";
}
if (!password) {
password = Cypress.config("adminPassword");
}
cy.request({
url: "/api/method/login",
method: "POST",
body: { usr: email, pwd: password },
});
});
|
2302_79757062/builder
|
frontend/cypress/support/commands.js
|
JavaScript
|
agpl-3.0
| 1,140
|
// ***********************************************************
// This example support/e2e.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************
// Import commands.js using ES2015 syntax:
import './commands'
// Alternatively you can use CommonJS syntax:
// require('./commands')
|
2302_79757062/builder
|
frontend/cypress/support/e2e.js
|
JavaScript
|
agpl-3.0
| 667
|
const { defineConfig } = require("cypress");
module.exports = defineConfig({
projectId: "jvejd7",
e2e: {
baseUrl: "http://builder.test:8000",
adminPassword: "admin",
},
retries: {
runMode: 2,
openMode: 0,
},
});
|
2302_79757062/builder
|
frontend/cypress.config.js
|
JavaScript
|
agpl-3.0
| 227
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/assets/builder/images/frappe_black.png" media="(prefers-color-scheme: light)"/>
<link rel="icon" href="/assets/builder/images/frappe_white.png" media="(prefers-color-scheme: dark)"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- <script src="https://cdn.tailwindcss.com"></script> -->
<title>Frappe Builder</title>
</head>
<body class="overscroll-none dark:bg-zinc-800 no-scrollbar">
<div id="app"></div>
<div id="modals"></div>
<div id="popovers"></div>
<script>
window.csrf_token = "{{ csrf_token }}";
window.builder_path = "{{ builder_path }}";
window.site_name = "{{ site_name }}";
</script>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
|
2302_79757062/builder
|
frontend/index.html
|
HTML
|
agpl-3.0
| 824
|
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
|
2302_79757062/builder
|
frontend/postcss.config.js
|
JavaScript
|
agpl-3.0
| 77
|
module.exports = {
useTabs: true,
bracketSameLine: true,
bracketSpacing: true,
htmlWhitespaceSensitivity: "ignore",
singleAttributePerLine: false,
printWidth: 110,
arrowParens: "always",
trailingComma: "all",
plugins: [require("prettier-plugin-tailwindcss")],
tailwindConfig: "./tailwind.config.js",
};
|
2302_79757062/builder
|
frontend/prettier.config.js
|
JavaScript
|
agpl-3.0
| 313
|
<template>
<div>
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>
<UseDark></UseDark>
<Toaster :theme="isDark ? 'dark' : 'light'" richColors />
<Dialogs></Dialogs>
</div>
</template>
<script setup lang="ts">
import { UseDark } from "@vueuse/components";
import { useDark, useTitle } from "@vueuse/core";
import { Dialogs } from "frappe-ui";
import { computed, provide } from "vue";
import { useRoute } from "vue-router";
import { Toaster } from "vue-sonner";
import { sessionUser } from "./router";
import useStore from "./store";
const store = useStore();
const route = useRoute();
provide("sessionUser", sessionUser);
const title = computed(() => {
return store.activePage && route.name !== "home"
? `${store.activePage.page_title || "Untitled"} | Builder`
: "Frappe Builder";
});
useTitle(title);
const isDark = useDark();
</script>
<style>
[id^="headlessui-dialog"] {
@apply z-50;
}
[id^="headlessui-dialog-panel"] {
@apply dark:bg-zinc-800;
}
[id^="headlessui-dialog-panel"] > div,
[id^="headlessui-dialog-panel"] .space-y-4 > p {
@apply dark:bg-zinc-800;
@apply dark:text-zinc-50;
}
[id^="headlessui-dialog-panel"] header h3 {
@apply dark:text-white;
}
[id^="headlessui-dialog-panel"] button svg path {
@apply dark:fill-white;
}
[id^="headlessui-dialog-panel"] button {
@apply dark:text-white;
@apply dark:hover:bg-zinc-700;
@apply dark:bg-zinc-900;
}
[id^="headlessui-dialog-panel"] input {
@apply dark:bg-zinc-900;
@apply dark:border-zinc-800;
@apply dark:text-gray-50;
}
[id^="headlessui-dialog-panel"] input:focus {
@apply dark:ring-0;
@apply dark:border-zinc-700;
}
[id^="headlessui-dialog-panel"] input[type="checkbox"]:checked {
@apply dark:bg-zinc-700;
}
[id^="headlessui-dialog-panel"] input[type="checkbox"]:focus {
@apply dark:ring-zinc-700;
@apply dark:ring-offset-0;
}
[id^="headlessui-dialog-panel"] input[type="checkbox"]:hover {
@apply dark:bg-zinc-900;
}
[id^="headlessui-dialog-panel"] label > span {
@apply dark:text-gray-50;
}
[id^="headlessui-dialog"] [data-dialog] {
@apply dark:bg-black-overlay-800;
}
[id^="headlessui-menu-items"],
[id^="headlessui-combobox-options"] {
@apply dark:bg-zinc-800;
@apply overflow-y-auto;
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none;
@apply max-w-60;
max-height: min(60vh, 24rem);
}
[id^="headlessui-menu-items"] [id^="headlessui-menu-item"] > span {
@apply truncate;
}
.divide-gray-100 > :not([hidden]) ~ :not([hidden]) {
@apply dark:border-zinc-700;
}
[id^="headlessui-menu-items"] &::webkit-scrollbar {
display: none;
}
[id^="headlessui-menu-items"] button,
[id^="headlessui-combobox-options"] li {
@apply dark:text-zinc-200;
@apply dark:hover:bg-zinc-700;
@apply dark:rounded;
@apply break-all;
}
[data-headlessui-state~="active"] li {
@apply dark:bg-zinc-600;
@apply dark:text-zinc-200;
}
[data-headlessui-state="selected"] li {
@apply dark:bg-zinc-700;
@apply dark:text-zinc-200;
}
[id^="headlessui-menu-items"] button svg {
@apply dark:text-zinc-200;
}
[data-sonner-toaster] {
font-family: "InterVar";
}
[data-sonner-toast][data-styled="true"] {
@apply dark:bg-zinc-900;
@apply dark:border-zinc-800;
}
</style>
|
2302_79757062/builder
|
frontend/src/App.vue
|
Vue
|
agpl-3.0
| 3,252
|
<template>
<div class="relative">
<Combobox
:modelValue="value"
@update:modelValue="
(val) => {
emit('update:modelValue', val);
}
"
v-slot="{ open }"
:nullable="nullable"
:multiple="multiple">
<div
class="form-input flex h-7 w-full items-center justify-between gap-2 rounded px-2 py-1 pr-5 text-sm transition-colors dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-200 dark:focus:bg-zinc-700">
<!-- {{ displayValue }} -->
<ComboboxInput
autocomplete="off"
@change="query = $event.target.value"
@focus="() => open"
:displayValue="
(option: Option) => {
if (Array.isArray(option)) {
return option.map((o) => o.label).join(', ');
} else if (option) {
return option.label || option.value || '';
} else {
return '';
}
}
"
:placeholder="!modelValue ? placeholder : null"
class="h-full w-full border-none bg-transparent p-0 text-base focus:border-none focus:ring-0" />
</div>
<ComboboxOptions
class="absolute right-0 z-50 max-h-[15rem] w-full overflow-y-auto rounded-lg bg-white px-1.5 py-1.5 shadow-2xl"
v-show="filteredOptions.length">
<ComboboxOption v-if="query" :value="query" class="flex items-center"></ComboboxOption>
<ComboboxOption
v-slot="{ active, selected }"
v-for="option in filteredOptions"
:key="option.value"
:value="option"
class="flex items-center">
<li
class="w-full select-none rounded px-2.5 py-1.5 text-xs"
:class="{
'bg-gray-100': active,
'bg-gray-300': selected,
}">
{{ option.label }}
</li>
</ComboboxOption>
</ComboboxOptions>
</Combobox>
<div
class="absolute right-[1px] top-[3px] cursor-pointer p-1 text-gray-700 dark:text-zinc-300"
@click="clearValue"
v-show="modelValue">
<CrossIcon />
</div>
</div>
</template>
<script setup lang="ts">
import { Combobox, ComboboxInput, ComboboxOption, ComboboxOptions } from "@headlessui/vue";
import { ComputedRef, PropType, computed, ref } from "vue";
import CrossIcon from "./Icons/Cross.vue";
type Option = {
label: string;
value: string;
};
const emit = defineEmits(["update:modelValue"]);
const props = defineProps({
options: {
type: Array as PropType<Option[]>,
default: () => [],
},
modelValue: {},
placeholder: {
type: String,
default: "Search",
},
showInputAsOption: {
type: Boolean,
default: false,
},
});
const query = ref("");
const multiple = computed(() => Array.isArray(props.modelValue));
const nullable = computed(() => !multiple.value);
const value = computed(() => {
return (
props.options.find((option) => option.value === props.modelValue) || {
label: props.modelValue,
value: props.modelValue,
}
);
}) as ComputedRef<Option>;
const filteredOptions = computed(() => {
if (query.value === "") {
return props.options;
} else {
const options = props.options.filter((option) => {
return (
option.label.toLowerCase().includes(query.value.toLowerCase()) ||
option.value.toLowerCase().includes(query.value.toLowerCase())
);
});
if (props.showInputAsOption) {
options.unshift({
label: query.value,
value: query.value,
});
}
return options;
}
});
const clearValue = () => emit("update:modelValue", null);
</script>
|
2302_79757062/builder
|
frontend/src/components/Autocomplete.vue
|
Vue
|
agpl-3.0
| 3,345
|
<template>
<Popover transition="default" placement="left" class="!block w-full" popoverClass="!min-w-fit !mr-[30px]">
<template #target="{ togglePopover, isOpen }">
<div class="flex items-center justify-between">
<InputLabel>BG Image</InputLabel>
<div class="relative w-full">
<div>
<Input
class="[&>div>input]:pl-8"
type="text"
placeholder="Set Background"
@update:modelValue="updateBG"
:value="backgroundURL?.replace(/^'|'$/g, '')" />
<div
class="absolute left-2 top-[6px] z-10 h-4 w-4 rounded shadow-sm"
@click="togglePopover"
:class="{
'bg-gray-400 dark:bg-zinc-600': !backgroundURL,
}"
:style="{
backgroundImage: backgroundURL ? `url(${backgroundURL})` : '',
backgroundPosition: `center`,
backgroundSize: `contain`,
backgroundRepeat: `no-repeat`,
}"></div>
</div>
</div>
</div>
</template>
<template #body>
<div class="rounded-lg bg-white p-3 shadow-lg dark:bg-zinc-900">
<div
class="image-preview group relative h-24 w-48 cursor-pointer overflow-hidden rounded bg-gray-200 dark:bg-zinc-700"
:style="{
backgroundImage: backgroundURL ? `url(${backgroundURL})` : '',
backgroundPosition: `center`,
backgroundSize: backgroundSize || `contain`,
backgroundRepeat: `no-repeat`,
}">
<FileUploader @success="setBG">
<template v-slot="{ openFileSelector }">
<div
class="absolute bottom-0 left-0 right-0 top-0 hidden place-items-center bg-gray-500 bg-opacity-20"
:class="{
'!grid': !backgroundURL,
'group-hover:grid': backgroundURL,
}">
<div
class="rounded bg-gray-200 p-2 text-xs text-gray-900 dark:bg-zinc-700 dark:text-zinc-200"
@click="openFileSelector">
Upload
</div>
</div>
</template>
</FileUploader>
</div>
<InlineInput
label="Size"
class="mt-4"
:modelValue="backgroundSize"
type="select"
:options="['contain', 'cover']"
@update:modelValue="setBGSize" />
</div>
</template>
</Popover>
</template>
<script lang="ts" setup>
import blockController from "@/utils/blockController";
import { FileUploader, Popover } from "frappe-ui";
import { computed } from "vue";
import InlineInput from "./InlineInput.vue";
import Input from "./Input.vue";
import InputLabel from "./InputLabel.vue";
const backgroundURL = computed(() => {
const background = blockController?.getStyle("background") as string;
if (background) {
const { bgImageURL } = parseBackground(background);
return bgImageURL;
}
return null;
});
const backgroundSize = computed(() => {
const background = blockController?.getStyle("background") as string;
if (background) {
const { bgSize } = parseBackground(background);
return bgSize;
}
});
const setBG = (file: { file_url: string }) => {
const url = window.location.origin + file.file_url;
blockController?.setStyle(
"background",
`url('${url}') center / ${backgroundSize.value || "cover"} no-repeat`,
);
};
const setBGSize = (value: string) => {
blockController?.setStyle("background", `url(${backgroundURL.value}) center / ${value} no-repeat`);
};
const parseBackground = (background: string) => {
const bgImageURL = background.match(/url\((.*?)\)/)?.[1];
const bgPosition = background.match(/center|top|bottom|left|right/g)?.[0];
const bgSize = background.match(/contain|cover/g)?.[0];
const bgRepeat = background.match(/repeat|no-repeat/g)?.[0];
return { bgImageURL, bgPosition, bgSize, bgRepeat };
};
const updateBG = (value: string) => {
blockController?.setStyle(
"background",
`url('${value}') center / ${backgroundSize.value || "cover"} no-repeat`,
);
};
</script>
|
2302_79757062/builder
|
frontend/src/components/BackgroundHandler.vue
|
Vue
|
agpl-3.0
| 3,796
|
<template>
<div>
<slot :onContextMenu="showContextMenu" />
<ContextMenu
v-if="contextMenuVisible"
:pos-x="posX"
:pos-y="posY"
:options="contextMenuOptions"
@select="handleContextMenuSelect"
v-on-click-outside="() => (contextMenuVisible = false)" />
<Dialog
style="z-index: 40"
:options="{
title: 'New Component',
size: 'sm',
actions: [
{
label: 'Save',
variant: 'solid',
onClick: createComponentHandler,
},
],
}"
v-model="showDialog">
<template #body-content>
<Input
type="text"
v-model="componentProperties.componentName"
label="Component Name"
required
class="[&>div>input]:dark:bg-zinc-900 [&>label]:dark:text-zinc-300" />
<div class="mt-3">
<Input
class="text-sm [&>label]:dark:text-zinc-300 [&>span]:!text-sm"
type="checkbox"
v-model="componentProperties.isGlobalComponent"
label="Global Component" />
</div>
</template>
</Dialog>
<Dialog
style="z-index: 40"
:options="{
title: 'Save as Block Template',
size: 'sm',
actions: [
{
label: 'Save',
variant: 'solid',
onClick: () => {
store.saveBlockTemplate(
block,
blockTemplateProperties.templateName,
'Basic',
blockTemplateProperties.previewImage,
);
showBlockTemplateDialog = false;
},
},
],
}"
v-model="showBlockTemplateDialog">
<template #body-content>
<div class="flex flex-col gap-4">
<Input
type="text"
v-model="blockTemplateProperties.templateName"
label="Template Name"
required
:hideClearButton="true"
class="[&>div>input]:dark:bg-zinc-900 [&>label]:dark:text-zinc-300" />
<div class="relative">
<Input
type="text"
v-model="blockTemplateProperties.previewImage"
label="Preview Image"
:hideClearButton="true"
class="[&>div>input]:dark:bg-zinc-900 [&>label]:dark:text-zinc-300" />
<FileUploader
file-types="image/*"
@success="
(file: FileDoc) => {
blockTemplateProperties.previewImage = file.file_url;
}
">
<template v-slot="{ openFileSelector }">
<div class="absolute bottom-0 right-0 place-items-center">
<Button size="sm" @click="openFileSelector" class="text-sm">Upload</Button>
</div>
</template>
</FileUploader>
</div>
</div>
</template>
</Dialog>
</div>
</template>
<script setup lang="ts">
import webComponent from "@/data/webComponent";
import useStore from "@/store";
import { posthog } from "@/telemetry";
import { BuilderComponent } from "@/types/Builder/BuilderComponent";
import Block from "@/utils/block";
import blockController from "@/utils/blockController";
import getBlockTemplate from "@/utils/blockTemplate";
import {
confirm,
detachBlockFromComponent,
getBlockCopy,
getBlockInstance,
getBlockString,
} from "@/utils/helpers";
import { vOnClickOutside } from "@vueuse/components";
import { useStorage } from "@vueuse/core";
import { Dialog, FileUploader } from "frappe-ui";
import { Ref, nextTick, ref } from "vue";
import { toast } from "vue-sonner";
import ContextMenu from "./ContextMenu.vue";
import Input from "./Input.vue";
const store = useStore();
const props = defineProps<{
block: Block;
editable: boolean;
}>();
const contextMenuVisible = ref(false);
const posX = ref(0);
const posY = ref(0);
const showDialog = ref(false);
const componentProperties = ref({
componentName: "",
isGlobalComponent: 0,
});
const blockTemplateProperties = ref({
templateName: "",
category: "",
previewImage: "",
});
const showBlockTemplateDialog = ref(false);
const showContextMenu = (event: MouseEvent) => {
if (props.block.isRoot() || props.editable) return;
contextMenuVisible.value = true;
posX.value = event.pageX;
posY.value = event.pageY;
event.preventDefault();
event.stopPropagation();
};
const handleContextMenuSelect = (action: CallableFunction) => {
action();
contextMenuVisible.value = false;
};
const copiedStyle = useStorage("copiedStyle", { blockId: "", style: {} }, sessionStorage) as Ref<StyleCopy>;
const copyStyle = () => {
copiedStyle.value = {
blockId: props.block.blockId,
style: props.block.getStylesCopy(),
};
};
const pasteStyle = () => {
props.block.updateStyles(copiedStyle.value?.style as BlockStyleObjects);
};
const duplicateBlock = () => {
props.block.duplicateBlock();
};
const createComponentHandler = (close: () => void) => {
const blockCopy = getBlockCopy(props.block, true);
blockCopy.removeStyle("left");
blockCopy.removeStyle("top");
blockCopy.removeStyle("position");
webComponent.insert
.submit({
block: getBlockString(blockCopy),
component_name: componentProperties.value.componentName,
for_web_page: componentProperties.value.isGlobalComponent ? null : store.selectedPage,
})
.then(async (data: BuilderComponent) => {
posthog.capture("builder_component_created", { component_name: data.name });
store.componentMap.set(data.name, getBlockInstance(data.block));
const block = store.activeCanvas?.findBlock(props.block.blockId);
if (!block) return;
block.extendFromComponent(data.name);
});
close();
};
const contextMenuOptions: ContextMenuOption[] = [
{
label: "Edit HTML",
action: () => {
store.editHTML(props.block);
},
condition: () => props.block.isHTML(),
},
{ label: "Copy", action: () => document.execCommand("copy") },
{ label: "Copy Style", action: copyStyle },
{
label: "Paste Style",
action: pasteStyle,
condition: () => Boolean(copiedStyle.value.blockId && copiedStyle.value?.blockId !== props.block.blockId),
},
{ label: "Duplicate", action: duplicateBlock },
{
label: "Convert To Link",
action: () => {
blockController.convertToLink();
},
condition: () =>
(props.block.isContainer() || props.block.isText() || props.block.isImage()) &&
!props.block.isLink() &&
!props.block.isExtendedFromComponent() &&
!props.block.isRoot(),
},
{
label: "Wrap In Container",
action: () => {
const newBlockObj = getBlockTemplate("fit-container");
const parentBlock = props.block.getParentBlock();
if (!parentBlock) return;
const selectedBlocks = store.activeCanvas?.selectedBlocks || [];
const blockPosition = Math.min(...selectedBlocks.map(parentBlock.getChildIndex.bind(parentBlock)));
const newBlock = parentBlock?.addChild(newBlockObj, blockPosition);
let width = null as string | null;
// move selected blocks to newBlock
selectedBlocks
.sort((a, b) => parentBlock.getChildIndex(a) - parentBlock.getChildIndex(b))
.forEach((block) => {
parentBlock?.removeChild(block);
newBlock?.addChild(block);
if (!width) {
const blockWidth = block.getStyle("width") as string | undefined;
if (blockWidth && (blockWidth == "auto" || blockWidth.endsWith("%"))) {
width = "100%";
}
}
});
if (width) {
newBlock?.setStyle("width", width);
}
nextTick(() => {
if (newBlock) {
newBlock.selectBlock();
}
});
},
condition: () => {
if (props.block.isRoot()) return false;
if (store.activeCanvas?.selectedBlocks.length === 1) return true;
// check if all selected blocks are siblings
const parentBlock = props.block.getParentBlock();
if (!parentBlock) return false;
const selectedBlocks = store.activeCanvas?.selectedBlocks || [];
return selectedBlocks.every((block) => block.getParentBlock() === parentBlock);
},
},
{
label: "Save As Component",
action: () => (showDialog.value = true),
condition: () => !props.block.isExtendedFromComponent(),
},
{
label: "Repeat Block",
action: () => {
const repeaterBlockObj = getBlockTemplate("repeater");
const parentBlock = props.block.getParentBlock();
if (!parentBlock) return;
const repeaterBlock = parentBlock.addChild(repeaterBlockObj, parentBlock.getChildIndex(props.block));
repeaterBlock.addChild(getBlockCopy(props.block));
parentBlock.removeChild(props.block);
repeaterBlock.selectBlock();
store.propertyFilter = "data key";
toast.warning("Please set data key for repeater block");
},
condition: () => !props.block.isRoot() && !props.block.isRepeater(),
},
{
label: "Reset Overrides",
condition: () => props.block.hasOverrides(store.activeBreakpoint),
action: () => {
props.block.resetOverrides(store.activeBreakpoint);
},
},
{
label: "Reset Changes",
action: () => {
if (props.block.hasChildren()) {
confirm("Reset changes in child blocks as well?").then((confirmed) => {
props.block.resetChanges(confirmed);
});
} else {
props.block.resetChanges();
}
},
condition: () => props.block.isExtendedFromComponent(),
},
{
label: "Sync Component",
condition: () => Boolean(props.block.extendedFromComponent),
action: () => {
props.block.syncWithComponent();
},
},
{
label: "Reset Component",
condition: () => Boolean(props.block.extendedFromComponent),
action: () => {
confirm("Are you sure you want to reset?").then((confirmed) => {
if (confirmed) {
props.block.resetWithComponent();
}
});
},
},
{
label: "Edit Component",
action: () => {
store.editComponent(props.block);
},
condition: () => Boolean(props.block.extendedFromComponent),
},
{
label: "Save as Block Template",
action: () => {
showBlockTemplateDialog.value = true;
},
condition: () => !props.block.isExtendedFromComponent() && Boolean(window.is_developer_mode),
},
{
label: "Detach Component",
action: () => {
const newBlock = detachBlockFromComponent(props.block);
if (newBlock) {
newBlock.selectBlock();
}
props.block.getParentBlock()?.replaceChild(props.block, newBlock);
},
condition: () => Boolean(props.block.extendedFromComponent),
},
{
label: "Delete",
action: () => {
props.block.getParentBlock()?.removeChild(props.block);
},
condition: () => {
return (
!props.block.isRoot() &&
!props.block.isChildOfComponentBlock() &&
Boolean(props.block.getParentBlock())
);
},
},
];
</script>
|
2302_79757062/builder
|
frontend/src/components/BlockContextMenu.vue
|
Vue
|
agpl-3.0
| 10,169
|
<template>
<BlockContextMenu :block="block" :editable="editable" v-slot="{ onContextMenu }">
<div
class="editor pointer-events-none fixed z-[18] box-content select-none ring-2 ring-inset"
ref="editor"
:selected="isBlockSelected"
@click.stop="handleClick"
@dblclick="handleDoubleClick"
@mousedown.prevent="handleMove"
@drop.prevent.stop="handleDrop"
@contextmenu="onContextMenu"
:data-block-id="block.blockId"
:class="getStyleClasses">
<PaddingHandler
:data-block-id="block.blockId"
v-if="
isBlockSelected &&
!resizing &&
!editable &&
!blockController.multipleBlocksSelected() &&
!block.isSVG()
"
:target-block="block"
:target="target"
:on-update="updateTracker"
:disable-handlers="false"
:breakpoint="breakpoint" />
<MarginHandler
v-if="
isBlockSelected &&
!block.isRoot() &&
!resizing &&
!editable &&
!blockController.multipleBlocksSelected()
"
:target-block="block"
:target="target"
:on-update="updateTracker"
:disable-handlers="false"
:breakpoint="breakpoint" />
<BorderRadiusHandler
:data-block-id="block.blockId"
v-if="
isBlockSelected &&
!block.isRoot() &&
!block.isText() &&
!block.isHTML() &&
!block.isSVG() &&
!editable &&
!resizing &&
!blockController.multipleBlocksSelected()
"
:target-block="block"
:target="target" />
<!-- prettier-ignore -->
<BoxResizer
v-if="showResizer"
:targetBlock="block"
@resizing="resizing = $event"
:target="(target as HTMLElement)" />
</div>
</BlockContextMenu>
</template>
<script setup lang="ts">
import Block from "@/utils/block";
import { addPxToNumber } from "@/utils/helpers";
import { Ref, computed, inject, nextTick, onMounted, ref, watch, watchEffect } from "vue";
import blockController from "@/utils/blockController";
import useStore from "../store";
import setGuides from "../utils/guidesTracker";
import trackTarget from "../utils/trackTarget";
import BlockContextMenu from "./BlockContextMenu.vue";
import BorderRadiusHandler from "./BorderRadiusHandler.vue";
import BoxResizer from "./BoxResizer.vue";
import MarginHandler from "./MarginHandler.vue";
import PaddingHandler from "./PaddingHandler.vue";
const canvasProps = inject("canvasProps") as CanvasProps;
const showResizer = computed(() => {
return (
!props.block.isRoot() &&
!props.editable &&
isBlockSelected.value &&
!blockController.multipleBlocksSelected() &&
!props.block.getParentBlock()?.isGrid() &&
!(props.block.isHTML() && !props.block.isSVG() && !props.block.isIframe())
);
});
const props = defineProps({
block: {
type: Block,
required: true,
},
breakpoint: {
type: String,
default: "desktop",
},
target: {
type: [HTMLElement, SVGElement],
required: true,
},
editable: {
type: Boolean,
default: false,
},
isSelected: {
type: Boolean,
default: false,
},
});
const store = useStore();
const editor = ref(null) as unknown as Ref<HTMLElement>;
const updateTracker = ref(() => {});
const resizing = ref(false);
const guides = setGuides(props.target, canvasProps);
const moving = ref(false);
const preventCLick = ref(false);
watchEffect(() => {
props.block.getStyle("top");
props.block.getStyle("left");
props.block.getStyle("bottom");
props.block.getStyle("right");
props.block.getStyle("position");
props.block.rawStyles;
const parentBlock = props.block.getParentBlock();
parentBlock?.getStyle("display");
parentBlock?.getStyle("justifyContent");
parentBlock?.getStyle("alignItems");
parentBlock?.getStyle("flexDirection");
parentBlock?.getStyle("paddingTop");
parentBlock?.getStyle("paddingBottom");
parentBlock?.getStyle("paddingLeft");
parentBlock?.getStyle("paddingRight");
parentBlock?.getStyle("margin");
parentBlock?.getChildIndex(props.block);
store.builderLayout.leftPanelWidth;
store.builderLayout.rightPanelWidth;
store.showRightPanel;
store.showLeftPanel;
store.activeBreakpoint;
canvasProps.breakpoints.map((bp) => bp.visible);
nextTick(() => {
updateTracker.value();
});
});
const isBlockSelected = computed(() => {
return props.isSelected && props.breakpoint === store.activeBreakpoint;
});
const getStyleClasses = computed(() => {
const classes = [];
if (movable.value && !props.block.isRoot()) {
classes.push("cursor-grab");
}
if (Boolean(props.block.extendedFromComponent)) {
classes.push("ring-purple-400");
} else {
classes.push("ring-blue-400");
}
if (isBlockSelected.value && !props.editable && !props.block.isRoot() && !props.block.isRepeater()) {
// make editor interactive
classes.push("pointer-events-auto");
// Place the block on the top of the stack
classes.push("!z-[19]");
}
return classes;
});
watch(
() => store.activeCanvas?.block,
() => {
nextTick(() => {
updateTracker.value();
});
},
);
const movable = computed(() => {
return props.block.isMovable();
});
onMounted(() => {
updateTracker.value = trackTarget(props.target, editor.value, canvasProps);
});
const handleClick = (ev: MouseEvent) => {
if (props.editable) return;
if (preventCLick.value) {
preventCLick.value = false;
return;
}
const editorWrapper = editor.value;
editorWrapper.classList.add("pointer-events-none");
let element = document.elementFromPoint(ev.x, ev.y) as HTMLElement;
if (element.classList.contains("editor")) {
element.classList.remove("pointer-events-auto");
element.classList.add("pointer-events-none");
element = document.elementFromPoint(ev.x, ev.y) as HTMLElement;
}
if (element.classList.contains("__builder_component__")) {
element.dispatchEvent(new MouseEvent("click", ev));
}
};
// dispatch drop event to the target block
const handleDrop = (ev: DragEvent) => {
if (props.editable) return;
const dropEvent = new DragEvent("drop", ev);
props.target.dispatchEvent(dropEvent);
};
const handleDoubleClick = (ev: MouseEvent) => {
if (props.block.isHTML()) {
store.editHTML(props.block);
return;
}
if (props.editable) return;
if (props.block.isText() || props.block.isButton() || props.block.isLink()) {
store.editableBlock = props.block;
}
};
const handleMove = (ev: MouseEvent) => {
if (store.mode === "text") {
store.editableBlock = props.block;
}
if (!movable.value || props.block.isRoot()) return;
const target = ev.target as HTMLElement;
const startX = ev.clientX;
const startY = ev.clientY;
const startLeft = props.target.offsetLeft || 0;
const startTop = props.target.offsetTop || 0;
moving.value = true;
guides.showX();
// to disable cursor jitter
const docCursor = document.body.style.cursor;
document.body.style.cursor = "grabbing";
target.style.cursor = "grabbing";
const mousemove = async (mouseMoveEvent: MouseEvent) => {
const scale = canvasProps.scale;
const movementX = (mouseMoveEvent.clientX - startX) / scale;
const movementY = (mouseMoveEvent.clientY - startY) / scale;
let finalLeft = startLeft + movementX;
let finalTop = startTop + movementY;
props.block.setStyle("left", addPxToNumber(finalLeft));
props.block.setStyle("top", addPxToNumber(finalTop));
await nextTick();
const { leftOffset, rightOffset } = guides.getPositionOffset();
if (leftOffset !== 0) {
props.block.setStyle("left", addPxToNumber(finalLeft + leftOffset));
}
if (rightOffset !== 0) {
props.block.setStyle("left", addPxToNumber(finalLeft + rightOffset));
}
mouseMoveEvent.preventDefault();
preventCLick.value = true;
};
document.addEventListener("mousemove", mousemove);
document.addEventListener(
"mouseup",
(mouseUpEvent) => {
moving.value = false;
document.body.style.cursor = docCursor;
target.style.cursor = "grab";
document.removeEventListener("mousemove", mousemove);
mouseUpEvent.preventDefault();
guides.hideX();
},
{ once: true },
);
};
defineExpose({
element: editor,
});
</script>
|
2302_79757062/builder
|
frontend/src/components/BlockEditor.vue
|
Vue
|
agpl-3.0
| 7,905
|
<template>
<OptionToggle
label="Direction"
v-if="blockController.isFlex()"
:options="[
{ label: 'Horizontal', value: 'row', icon: 'arrow-right', hideLabel: true },
{ label: 'Vertical', value: 'column', icon: 'arrow-down', hideLabel: true },
]"
:modelValue="blockController.getStyle('flexDirection') || 'column'"
@update:modelValue="
(val: string | number) => blockController.setStyle('flexDirection', val)
"></OptionToggle>
<PlacementControl v-if="blockController.isFlex()"></PlacementControl>
<InlineInput
v-if="blockController.isFlex()"
:modelValue="blockController.getStyle('justifyContent')"
type="select"
label="Distribution"
:options="[
{ label: 'Space Between', value: 'space-between' },
{ label: 'Space Around', value: 'space-around' },
{ label: 'Space Evenly', value: 'space-evenly' },
]"
@update:modelValue="(val: string | number) => blockController.setStyle('justifyContent', val)" />
<InlineInput
label="Gap"
v-if="blockController.isFlex()"
type="text"
:enableSlider="true"
:unitOptions="['px', 'em', 'rem']"
:modelValue="blockController.getStyle('gap')"
@update:modelValue="(val: string | number) => blockController.setStyle('gap', val)" />
<OptionToggle
label="Wrap"
v-if="blockController.isFlex()"
:options="[
{ label: 'No Wrap', value: 'nowrap' },
{ label: 'Wrap', value: 'wrap' },
]"
:modelValue="blockController.getStyle('flexWrap') || 'nowrap'"
@update:modelValue="(val: string | number) => blockController.setStyle('flexWrap', val)"></OptionToggle>
<div class="flex flex-col gap-3" v-if="blockController.getParentBlock()?.isFlex()">
<OptionToggle
label="Grow"
:options="[
{ label: 'Yes', value: 1 },
{ label: 'No', value: 0 },
]"
:modelValue="blockController.getStyle('flexGrow') || 0"
@update:modelValue="(val: string | number) => blockController.setStyle('flexGrow', val)"></OptionToggle>
<OptionToggle
label="Shrink"
:options="[
{ label: 'Yes', value: 1 },
{ label: 'No', value: 0 },
]"
:modelValue="blockController.getStyle('flexShrink') ?? 1"
@update:modelValue="
(val: string | number) => blockController.setStyle('flexShrink', val)
"></OptionToggle>
</div>
</template>
<script lang="ts" setup>
import blockController from "@/utils/blockController";
import InlineInput from "./InlineInput.vue";
import OptionToggle from "./OptionToggle.vue";
import PlacementControl from "./PlacementControl.vue";
</script>
|
2302_79757062/builder
|
frontend/src/components/BlockFlexLayoutHandler.vue
|
Vue
|
agpl-3.0
| 2,476
|
<template>
<OptionToggle
class="w-full"
label="Grid Type"
v-if="blockController.isGrid()"
:modelValue="isFixed ? 'fixed' : 'auto'"
@update:modelValue="setGridType"
:options="[
{ label: 'Fixed', value: 'fixed' },
{ label: 'Auto', value: 'auto' },
]"></OptionToggle>
<InlineInput
v-if="blockController.isGrid() && isFixed"
label="Columns"
:modelValue="columns"
:enableSlider="true"
:changeFactor="0.08"
:minValue="1"
:maxValue="20"
@update:modelValue="setColumns" />
<InlineInput
v-if="blockController.isGrid() && isFixed"
label="Rows"
:modelValue="rows"
:enableSlider="true"
:changeFactor="0.08"
:minValue="1"
:maxValue="20"
@update:modelValue="setRows" />
<InlineInput
label="Item Width"
v-if="blockController.isGrid()"
v-show="['auto-fit', 'auto-fill'].includes(columns as string)"
type="text"
:modelValue="width"
:enableSlider="true"
:unitOptions="['px', 'em', 'rem', 'fr']"
@update:modelValue="setWidth" />
<InlineInput
label="Row Height"
v-if="blockController.isGrid()"
v-show="['auto-fit', 'auto-fill'].includes(rows as string)"
:enableSlider="true"
:unitOptions="['px', 'em', 'rem', 'fr']"
type="text"
:modelValue="height"
@update:modelValue="setHeight" />
<InlineInput
label="Gap"
v-if="blockController.isGrid()"
type="text"
:enableSlider="true"
:unitOptions="['px', 'em', 'rem']"
:modelValue="blockController.getStyle('gap') || '0px'"
@update:modelValue="(val: string | number) => blockController.setStyle('gap', val)" />
<!-- <InlineInput
label="Align"
v-if="blockController.isGrid()"
type="select"
:modelValue="blockController.getStyle('justifyItems') || 'stretch'"
:options="[
{
label: 'Stretch',
value: 'stretch',
},
{
label: 'Start',
value: 'start',
},
{
label: 'Center',
value: 'center',
},
{
label: 'End',
value: 'end',
},
]"
@update:modelValue="(val: string) => blockController.setStyle('justifyItems', val)" /> -->
<!-- <InlineInput
label="Flow"
v-if="blockController.isGrid()"
type="select"
:modelValue="blockController.getStyle('gridAutoFlow') || 'row'"
:options="[
{
label: 'Row',
value: 'row',
},
{
label: 'Column',
value: 'column',
},
{
label: 'Row Dense',
value: 'row dense',
},
{
label: 'Column Dense',
value: 'column dense',
},
]"
@update:modelValue="(val: string) => blockController.setStyle('gridAutoFlow', val)" /> -->
<!-- place items -->
<!-- <InlineInput
label="Place Items"
v-if="blockController.isGrid()"
type="select"
:modelValue="blockController.getStyle('placeItems') || 'stretch'"
:options="[
{
label: 'Top Right',
value: 'start end',
},
{
label: 'Top Center',
value: 'start center',
},
{
label: 'Top Left',
value: 'start start',
},
{
label: 'Center Right',
value: 'center end',
},
{
label: 'Center',
value: 'center center',
},
{
label: 'Center Left',
value: 'center start',
},
{
label: 'Bottom Right',
value: 'end end',
},
{
label: 'Bottom Center',
value: 'end center',
},
{
label: 'Bottom Left',
value: 'end start',
},
]"
@update:modelValue="(val: string) => blockController.setStyle('placeItems', val)" /> -->
<InlineInput
label="Col Span"
v-if="blockController.getParentBlock()?.isGrid()"
type="text"
:enableSlider="true"
:changeFactor="0.08"
:modelValue="columnSpan"
@update:modelValue="setColumnSpan" />
<InlineInput
label="Row Span"
v-if="blockController.getParentBlock()?.isGrid()"
type="text"
:enableSlider="true"
:changeFactor="0.08"
:modelValue="rowSpan"
@update:modelValue="setRowSpan" />
<!-- place self -->
<!-- <InlineInput
label="Place Self"
v-if="blockController.getParentBlock()?.isGrid()"
type="select"
:modelValue="blockController.getStyle('placeSelf') || 'stretch'"
:options="[
{
label: 'Top Right',
value: 'start end',
},
{
label: 'Top Center',
value: 'start center',
},
{
label: 'Top Left',
value: 'start start',
},
{
label: 'Center Right',
value: 'center end',
},
{
label: 'Center',
value: 'center center',
},
{
label: 'Center Left',
value: 'center start',
},
{
label: 'Bottom Right',
value: 'end end',
},
{
label: 'Bottom Center',
value: 'end center',
},
{
label: 'Bottom Left',
value: 'end start',
},
]"
@update:modelValue="(val: string) => blockController.setStyle('placeSelf', val)" /> -->
</template>
<script lang="ts" setup>
import blockController from "@/utils/blockController";
import { computed } from "vue";
import InlineInput from "./InlineInput.vue";
import OptionToggle from "./OptionToggle.vue";
const columns = computed(() => {
const template = blockController.getStyle("gridTemplateColumns") as string;
if (!template) {
return;
}
const value = parseRepeatFunction(template);
return value.repeat || 1;
});
const rows = computed(() => {
const template = blockController.getStyle("gridTemplateRows") as string;
if (!template) {
return;
}
const value = parseRepeatFunction(template);
return value.repeat || 1;
});
const width = computed(() => {
const template = blockController.getStyle("gridTemplateColumns") as string;
const value = parseRepeatFunction(template);
return value.minValue !== "0" ? value.minValue : "200px";
});
const height = computed(() => {
const template = blockController.getStyle("gridTemplateRows") as string;
const value = parseRepeatFunction(template);
return value.minValue !== "0" ? value.minValue : "200px";
});
const columnSpan = computed(() => {
let gridColumn = blockController.getStyle("gridColumn") as string;
if (!gridColumn) {
return 1;
}
gridColumn = gridColumn.replace("span", "").trim();
const [start, end] = gridColumn.split("/");
return end ? parseInt(end) - parseInt(start) : start || 1;
});
const rowSpan = computed(() => {
let gridRow = blockController.getStyle("gridRow") as string;
if (!gridRow) {
return 1;
}
gridRow = gridRow.replace("span", "").trim();
const [start, end] = gridRow.split("/");
return end ? parseInt(end) - parseInt(start) : start || 1;
});
const setColumns = (val: string | number) => {
if (val == null) {
val = "auto-fill";
}
const widthRange = `minmax(0, 1fr)`;
val = `repeat(${val}, ${widthRange})`;
blockController.setStyle("gridTemplateColumns", val);
blockController.setStyle("gridAutoColumns", widthRange);
};
const setRows = (val: string | number) => {
if (val == null) {
val = "auto-fill";
}
const heightRange = `minmax(0, 1fr)`;
val = `repeat(${val}, ${heightRange})`;
blockController.setStyle("gridTemplateRows", val);
blockController.setStyle("gridAutoRows", heightRange);
};
const setWidth = (val: string | number) => {
if (val == null) {
val = "1fr";
}
const widthRange = `minmax(${val}, 1fr)`;
val = `repeat(${columns.value}, ${widthRange})`;
blockController.setStyle("gridTemplateColumns", val);
blockController.setStyle("gridAutoColumns", widthRange);
};
const setHeight = (val: string | number) => {
if (val == null) {
val = "1fr";
}
const heightRange = `minmax(${val}, 1fr)`;
val = `repeat(${rows.value}, ${heightRange})`;
blockController.setStyle("gridTemplateRows", val);
blockController.setStyle("gridAutoRows", heightRange);
};
const setColumnSpan = (val: string) => {
blockController.setStyle("width", null);
blockController.setStyle("minWidth", null);
blockController.setStyle("maxWidth", null);
if (!val) {
blockController.setStyle("gridColumn", val);
} else {
blockController.setStyle("gridColumn", `span ${val}`);
}
};
const setRowSpan = (val: string) => {
blockController.setStyle("height", null);
blockController.setStyle("minHeight", null);
blockController.setStyle("maxHeight", null);
if (!val) {
blockController.setStyle("gridRow", val);
} else {
blockController.setStyle("gridRow", `span ${val}`);
}
};
function parseRepeatFunction(input: string) {
const res = {
repeat: 1 as number | string,
minValue: 0 as number | string,
};
if (!input) {
return res;
}
const repeatPattern = /repeat\((\d+|auto-fit|auto-fill),\s*(.+)\)/;
const minMaxPattern = /minmax\((.+),\s*(.+)\)/;
const match = input.match(repeatPattern);
if (match) {
const countOrKeyword = match[1]; // Extract the count or keyword
const values = match[2].trim(); // Extract the values inside the repeat
const minValueMatch = values.match(minMaxPattern);
res.repeat = isNaN(parseInt(countOrKeyword, 10)) ? countOrKeyword : parseInt(countOrKeyword, 10);
res.minValue = minValueMatch ? minValueMatch[1] : 0;
}
return res;
}
const isFixed = computed(() => {
const template = blockController.getStyle("gridTemplateColumns") as string;
if (!template) {
return false;
}
const value = parseRepeatFunction(template);
return value.repeat !== "auto-fill" && value.repeat !== "auto-fit";
});
const setGridType = (val: string) => {
if (val === "fixed") {
blockController.setStyle("gridTemplateColumns", `repeat(2, minmax(0, 1fr))`);
} else {
blockController.setStyle("gridTemplateColumns", `repeat(auto-fill, minmax(${width.value}, 1fr))`);
}
};
</script>
|
2302_79757062/builder
|
frontend/src/components/BlockGridLayoutHandler.vue
|
Vue
|
agpl-3.0
| 9,284
|
<template>
<div ref="component" class="!relative" v-html="html"></div>
</template>
<script setup lang="ts">
import Block from "@/utils/block";
import { computed, ref } from "vue";
const component = ref<HTMLElement | null>(null);
const props = defineProps({
block: {
type: Block,
required: true,
},
data: {
type: Object,
default: null,
},
});
const html = computed(
() => `
<div class="absolute top-0 bottom-0 right-0 left-0"></div>
${props.block.getInnerHTML()}
`
);
defineExpose({
component,
});
</script>
|
2302_79757062/builder
|
frontend/src/components/BlockHTML.vue
|
Vue
|
agpl-3.0
| 529
|
<template>
<div>
<draggable
class="block-tree"
:list="blocks"
:group="{ name: 'block-tree' }"
item-key="blockId"
@add="updateParent"
:disabled="blocks.length && (blocks[0].isRoot() || blocks[0].isChildOfComponentBlock())">
<template #item="{ element }">
<div>
<BlockContextMenu v-slot="{ onContextMenu }" :block="element" :editable="false">
<div
:data-block-layer-id="element.blockId"
:title="element.blockId"
@contextmenu.prevent.stop="onContextMenu"
class="min-w-24 cursor-pointer overflow-hidden rounded border border-transparent bg-white bg-opacity-50 text-base text-gray-700 dark:bg-zinc-900 dark:text-gray-500"
@click.stop="
store.activeCanvas?.history.pause();
store.selectBlock(element, $event, false, true);
store.activeCanvas?.history.resume();
"
@mouseover.stop="store.hoveredBlock = element.blockId"
@mouseleave.stop="store.hoveredBlock = null">
<span
class="group my-[7px] flex items-center gap-1.5 pr-[2px] font-medium"
:style="{ paddingLeft: `${indent}px` }"
:class="{
'!opacity-50': !element.isVisible(),
}">
<FeatherIcon
:name="isExpanded(element) ? 'chevron-down' : 'chevron-right'"
class="h-3 w-3"
v-if="element.children && element.children.length && !element.isRoot()"
@click.stop="toggleExpanded(element)" />
<FeatherIcon
:name="element.getIcon()"
class="h-3 w-3"
:class="{
'text-purple-500 opacity-80 dark:opacity-100 dark:brightness-125 dark:saturate-[0.3]':
element.isExtendedFromComponent(),
}"
v-if="!Boolean(element.extendedFromComponent)" />
<BlocksIcon
class="mr-1 h-3 w-3"
:class="{
'text-purple-500 opacity-80 dark:opacity-100 dark:brightness-125 dark:saturate-[0.3]':
element.isExtendedFromComponent(),
}"
v-if="Boolean(element.extendedFromComponent)" />
<span
class="min-h-[1em] min-w-[2em] truncate"
:contenteditable="element.editable"
:title="element.blockId"
:class="{
'text-purple-500 opacity-80 dark:opacity-100 dark:brightness-125 dark:saturate-[0.3]':
element.isExtendedFromComponent(),
}"
@dblclick="element.editable = true"
@keydown.enter.stop.prevent="element.editable = false"
@blur="setBlockName($event, element)">
{{ element.getBlockDescription() }}
</span>
<!-- toggle visibility -->
<FeatherIcon
v-if="!element.isRoot()"
:name="element.isVisible() ? 'eye' : 'eye-off'"
class="ml-auto mr-2 hidden h-3 w-3 group-hover:block"
@click.stop="element.toggleVisibility()" />
<span
v-if="element.isRoot()"
class="ml-auto mr-2 text-sm capitalize text-gray-500 dark:text-zinc-500">
{{ store.activeBreakpoint }}
</span>
</span>
<div v-show="canShowChildLayer(element)">
<BlockLayers :blocks="element.children" ref="childLayer" :indent="childIndent" />
</div>
</div>
</BlockContextMenu>
</div>
</template>
</draggable>
</div>
</template>
<script setup lang="ts">
import Block from "@/utils/block";
import { FeatherIcon } from "frappe-ui";
import { PropType, ref, watch } from "vue";
import draggable from "vuedraggable";
import useStore from "../store";
import BlockContextMenu from "./BlockContextMenu.vue";
import BlockLayers from "./BlockLayers.vue";
import BlocksIcon from "./Icons/Blocks.vue";
const store = useStore();
const childLayer = ref<InstanceType<typeof BlockLayers> | null>(null);
const props = defineProps({
blocks: {
type: Array as PropType<Block[]>,
default: () => [],
},
indent: {
type: Number,
default: 10,
},
});
interface LayerBlock extends Block {
editable: boolean;
}
const childIndent = props.indent + 16;
const setBlockName = (ev: Event, block: LayerBlock) => {
const target = ev.target as HTMLElement;
block.blockName = target.innerText.trim();
block.editable = false;
};
const expandedLayers = ref(new Set(["root"]));
const isExpanded = (block: Block) => {
return expandedLayers.value.has(block.blockId);
};
const toggleExpanded = (block: Block) => {
const blockIndex = props.blocks.findIndex((b) => b.blockId === block.blockId);
if (blockIndex === -1) {
childLayer.value?.toggleExpanded(block);
return;
}
if (isExpanded(block) && !block.isRoot()) {
expandedLayers.value.delete(block.blockId);
} else {
expandedLayers.value.add(block.blockId);
}
};
const canShowChildLayer = (block: Block) => {
return (
((isExpanded(block) && block.hasChildren()) || (block.canHaveChildren() && !block.hasChildren())) &&
block.isVisible()
);
};
watch(
() => store.activeCanvas?.selectedBlocks,
() => {
if (store.activeCanvas?.selectedBlocks.length) {
store.activeCanvas?.selectedBlocks.forEach((block: Block) => {
if (block) {
let parentBlock = block.getParentBlock();
// open all parent blocks
while (parentBlock && !parentBlock.isRoot()) {
expandedLayers.value.add(parentBlock?.blockId);
parentBlock = parentBlock.getParentBlock();
}
}
});
}
},
);
const updateParent = (event) => {
event.item.__draggable_context.element.parentBlock = store.activeCanvas?.findBlock(
event.to.closest("[data-block-layer-id]").dataset.blockLayerId,
);
};
defineExpose({
isExpanded,
toggleExpanded,
});
</script>
<style>
.hovered-block {
@apply border-blue-300 text-gray-700 dark:border-blue-900 dark:text-gray-500;
}
.block-selected {
@apply border-blue-400 text-gray-900 dark:border-blue-700 dark:text-gray-200;
}
</style>
|
2302_79757062/builder
|
frontend/src/components/BlockLayers.vue
|
Vue
|
agpl-3.0
| 5,777
|
<template>
<div class="flex w-full flex-col items-center gap-5">
<OptionToggle
:modelValue="position"
@update:modelValue="position = $event"
:options="[
{ label: 'Auto', value: 'static' },
{ label: 'Free', value: 'absolute' },
{
label: 'Fixed',
value: 'fixed',
},
{ label: 'Sticky', value: 'sticky' },
]"></OptionToggle>
<div class="grid-rows grid grid-cols-3 gap-4" v-if="showHandler">
<div class="col-span-1 col-start-2 w-16 self-center">
<Input
type="text"
placeholder="top"
:modelValue="blockController.getStyle('top') as string"
@update:modelValue="(value: string) => blockController.setStyle('top', value)" />
</div>
<div class="col-span-1 col-start-1 w-16 self-center">
<Input
type="text"
placeholder="left"
:modelValue="blockController.getStyle('left') as string"
@update:modelValue="(value: string) => blockController.setStyle('left', value)" />
</div>
<div
class="grid-col-3 grid h-16 w-16 grid-rows-3 gap-1 self-center justify-self-center rounded bg-gray-50 p-2 dark:bg-zinc-800">
<div
class="col-span-3 row-start-1 h-2 w-[2px] self-center justify-self-center rounded bg-gray-400 dark:bg-zinc-900"></div>
<div
class="col-span-3 row-start-3 h-2 w-[2px] self-center justify-self-center rounded bg-gray-400 dark:bg-zinc-900"></div>
<div
class="h-5 w-5 self-center justify-self-center rounded bg-gray-400 shadow-md dark:bg-zinc-900"></div>
<div
class="col-span-1 col-start-1 row-start-2 h-[2px] w-2 self-center justify-self-center rounded bg-gray-400 dark:bg-zinc-900"></div>
<div
class="col-span-1 col-start-3 row-start-2 h-[2px] w-2 self-center justify-self-center rounded bg-gray-400 dark:bg-zinc-900"></div>
</div>
<div class="col-span-1 col-start-3 w-16 self-center">
<Input
type="text"
placeholder="right"
:modelValue="blockController.getStyle('right') as string"
@update:modelValue="(value: string) => blockController.setStyle('right', value)" />
</div>
<div class="col-span-1 col-start-2 w-16 self-center">
<Input
type="text"
placeholder="bottom"
:modelValue="blockController.getStyle('bottom') as string"
@update:modelValue="(value: string) => blockController.setStyle('bottom', value)" />
</div>
</div>
</div>
</template>
<script setup lang="ts">
import blockController from "@/utils/blockController";
import { computed, watch } from "vue";
import Input from "./Input.vue";
import OptionToggle from "./OptionToggle.vue";
const position = computed({
get() {
const pos = (blockController.getStyle("position") as string) || "static";
if (["relative", "static"].includes(pos)) {
return "static";
}
return pos;
},
set(value: string) {
if (value === "static") {
value = "";
}
blockController.setStyle("position", value);
const parentBlock = blockController.getParentBlock();
if (parentBlock) {
parentBlock.setStyle("position", "relative");
}
},
});
watch(position, (value) => {
if (value === "static") {
blockController.setStyle("top", "");
blockController.setStyle("left", "");
blockController.setStyle("right", "");
blockController.setStyle("bottom", "");
}
});
const showHandler = computed(() => {
return ["absolute", "fixed", "sticky"].includes(position.value);
});
</script>
|
2302_79757062/builder
|
frontend/src/components/BlockPositionHandler.vue
|
Vue
|
agpl-3.0
| 3,363
|
<template>
<div v-if="blockController.isBLockSelected()" class="flex select-none flex-col pb-16">
<div class="sticky top-9 z-50 mt-[-15px] flex w-full bg-white py-3 dark:bg-zinc-900">
<Input
ref="searchInput"
type="text"
placeholder="Search properties"
v-model="store.propertyFilter"
@input="
(value) => {
store.propertyFilter = value;
}
" />
</div>
<div class="flex flex-col gap-3">
<CollapsibleSection
:sectionName="section.name"
v-for="section in filteredSections"
:sectionCollapsed="section.collapsed">
<template v-for="property in getFilteredProperties(section)">
<component :is="property.component" v-bind="property.getProps()" v-on="property.events || {}">
{{ property.innerText || "" }}
</component>
</template>
</CollapsibleSection>
</div>
</div>
<div v-else>
<p class="text-center text-sm text-gray-600 dark:text-zinc-500">Select a block to edit properties.</p>
</div>
</template>
<script setup lang="ts">
import { webPages } from "@/data/webPage";
import useStore from "@/store";
import { BuilderPage } from "@/types/Builder/BuilderPage";
import blockController from "@/utils/blockController";
import { setFont as _setFont, fontListNames, getFontWeightOptions } from "@/utils/fontManager";
import { Button, createResource } from "frappe-ui";
import { Ref, computed, nextTick, ref } from "vue";
import { toast } from "vue-sonner";
import BackgroundHandler from "./BackgroundHandler.vue";
import BlockFlexLayoutHandler from "./BlockFlexLayoutHandler.vue";
import BlockGridLayoutHandler from "./BlockGridLayoutHandler.vue";
import BlockPositionHandler from "./BlockPositionHandler.vue";
import CodeEditor from "./CodeEditor.vue";
import CollapsibleSection from "./CollapsibleSection.vue";
import ColorInput from "./ColorInput.vue";
import DimensionInput from "./DimensionInput.vue";
import InlineInput from "./InlineInput.vue";
import Input from "./Input.vue";
import ObjectEditor from "./ObjectEditor.vue";
import OptionToggle from "./OptionToggle.vue";
const store = useStore();
// command + f should focus on search input
window.addEventListener("keydown", (e) => {
if (e.key === "f" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
document.querySelector(".properties-search-input")?.querySelector("input")?.focus();
}
});
type BlockProperty = {
component: any;
getProps: () => Record<string, unknown>;
events?: Record<string, unknown>;
searchKeyWords: string;
condition?: () => boolean;
innerText?: string;
};
type PropertySection = {
name: string;
properties: BlockProperty[];
condition?: () => boolean;
collapsed?: boolean;
};
const searchInput = ref(null) as Ref<HTMLElement | null>;
const filteredSections = computed(() => {
return sections.filter((section) => {
let showSection = true;
if (section.condition) {
showSection = section.condition();
}
if (showSection && store.propertyFilter) {
showSection = getFilteredProperties(section).length > 0;
}
return showSection;
});
});
const getFilteredProperties = (section: PropertySection) => {
return section.properties.filter((property) => {
let showProperty = true;
if (property.condition) {
showProperty = property.condition();
}
if (showProperty && store.propertyFilter) {
showProperty =
section.name.toLowerCase().includes(store.propertyFilter.toLowerCase()) ||
property.searchKeyWords.toLowerCase().includes(store.propertyFilter.toLowerCase());
}
return showProperty;
});
};
const setFont = (font: string) => {
_setFont(font, null).then(() => {
blockController.setFontFamily(font);
});
};
const setClasses = (val: string) => {
const classes = val.split(",").map((c) => c.trim());
blockController.setClasses(classes);
};
const linkSectionProperties = [
{
component: InlineInput,
getProps: () => {
return {
label: "Link To",
type: "autocomplete",
showInputAsOption: true,
options: webPages.data
.filter((page: BuilderPage) => {
return page.route && !page.dynamic_route;
})
.map((page: BuilderPage) => {
return {
value: `/${page.route}`,
label: `/${page.route}`,
};
}),
modelValue: blockController.getAttribute("href"),
};
},
searchKeyWords: "Link, Href, URL",
events: {
"update:modelValue": async (val: string) => {
if (val && !blockController.isLink()) {
blockController.convertToLink();
await nextTick();
await nextTick();
}
if (!val && blockController.isLink()) {
blockController.unsetLink();
} else {
blockController.setAttribute("href", val);
}
},
},
},
{
component: InlineInput,
getProps: () => {
return {
label: "Opens in",
type: "select",
options: [
{
value: "_self",
label: "Same Tab",
},
{
value: "_blank",
label: "New Tab",
},
],
modelValue: blockController.getAttribute("target") || "_self",
};
},
searchKeyWords: "Link, Target, Opens in, OpensIn, Opens In, New Tab",
events: {
"update:modelValue": (val: string) => {
if (val === "_self") {
blockController.removeAttribute("target");
} else {
blockController.setAttribute("target", val);
}
},
},
condition: () => blockController.getAttribute("href"),
},
];
const typographySectionProperties = [
{
component: InlineInput,
getProps: () => {
return {
label: "Family",
type: "autocomplete",
options: fontListNames,
modelValue: blockController.getFontFamily(),
};
},
searchKeyWords: "Font, Family, FontFamily",
events: {
"update:modelValue": (val: string) => setFont(val),
},
condition: () => blockController.isText() || blockController.isContainer(),
},
{
component: InlineInput,
getProps: () => {
return {
label: "Weight",
modelValue: blockController.getStyle("fontWeight"),
type: "autocomplete",
options: getFontWeightOptions((blockController.getStyle("fontFamily") || "Inter") as string),
};
},
searchKeyWords: "Font, Weight, FontWeight",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("fontWeight", val),
},
},
{
component: InlineInput,
getProps: () => {
return {
label: "Size",
modelValue: blockController.getStyle("fontSize"),
enableSlider: true,
minValue: 1,
};
},
searchKeyWords: "Font, Size, FontSize",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("fontSize", val),
},
condition: () => blockController.isText() || blockController.isInput(),
},
{
component: InlineInput,
getProps: () => {
return {
label: "Height",
modelValue: blockController.getStyle("lineHeight"),
};
},
searchKeyWords: "Font, Height, LineHeight, Line Height",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("lineHeight", val),
},
condition: () => blockController.isText(),
},
{
component: InlineInput,
getProps: () => {
return {
label: "Letter",
modelValue: blockController.getStyle("letterSpacing"),
};
},
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("letterSpacing", val),
},
searchKeyWords: "Font, Letter, LetterSpacing, Letter Spacing",
condition: () => blockController.isText(),
},
{
component: InlineInput,
getProps: () => {
return {
label: "Transform",
modelValue: blockController.getStyle("textTransform"),
type: "select",
options: [
{
value: null,
label: "None",
},
{
value: "uppercase",
label: "Uppercase",
},
{
value: "lowercase",
label: "Lowercase",
},
{
value: "capitalize",
label: "Capitalize",
},
],
};
},
searchKeyWords: "Font, Transform, TextTransform, Text Transform, Capitalize, Uppercase, Lowercase",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("textTransform", val),
},
condition: () => blockController.isText(),
},
{
component: OptionToggle,
getProps: () => {
return {
label: "Align",
options: [
{
label: "Left",
value: "left",
icon: "align-left",
hideLabel: true,
},
{
label: "Center",
value: "center",
icon: "align-center",
hideLabel: true,
},
{
label: "Right",
value: "right",
icon: "align-right",
hideLabel: true,
},
],
modelValue: blockController.getStyle("textAlign") || "left",
};
},
searchKeyWords: "Font, Align, TextAlign, Text Align, Left, Center, Right, Justify",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("textAlign", val),
},
condition: () => blockController.isText(),
},
];
const layoutSectionProperties = [
{
component: OptionToggle,
getProps: () => {
return {
label: "Type",
options: [
{
label: "Stack",
value: "flex",
},
{
label: "Grid",
value: "grid",
},
],
modelValue: blockController.getStyle("display") || "flex",
};
},
searchKeyWords: "Layout, Display, Flex, Grid, Flexbox, Flex Box, FlexBox",
events: {
"update:modelValue": (val: StyleValue) => {
blockController.setStyle("display", val);
if (val === "grid") {
if (!blockController.getStyle("gridTemplateColumns")) {
blockController.setStyle("gridTemplateColumns", "repeat(2, minmax(200px, 1fr))");
}
if (!blockController.getStyle("gap")) {
blockController.setStyle("gap", "10px");
}
if (blockController.getStyle("height")) {
if (blockController.getSelectedBlocks()[0].hasChildren()) {
blockController.setStyle("height", null);
}
}
}
},
},
},
{
component: BlockGridLayoutHandler,
getProps: () => {},
searchKeyWords:
"Layout, Grid, GridTemplate, Grid Template, GridGap, Grid Gap, GridRow, Grid Row, GridColumn, Grid Column",
},
{
component: BlockFlexLayoutHandler,
getProps: () => {},
searchKeyWords:
"Layout, Flex, Flexbox, Flex Box, FlexBox, Justify, Space Between, Flex Grow, Flex Shrink, Flex Basis, Align Items, Align Content, Align Self, Flex Direction, Flex Wrap, Flex Flow, Flex Grow, Flex Shrink, Flex Basis, Gap",
},
];
const styleSectionProperties = [
{
component: ColorInput,
getProps: () => {
return {
label: "BG Color",
value: blockController.getStyle("background"),
};
},
searchKeyWords: "Background, BackgroundColor, Background Color, BG, BGColor, BG Color",
events: {
change: (val: StyleValue) => blockController.setStyle("background", val),
},
},
{
component: ColorInput,
getProps: () => {
return {
label: "Text Color",
value: blockController.getTextColor(),
};
},
searchKeyWords: "Text, Color, TextColor, Text Color",
events: {
change: (val: string) => blockController.setTextColor(val),
},
},
{
component: ColorInput,
getProps: () => {
return {
label: "Border Color",
value: blockController.getStyle("borderColor"),
};
},
searchKeyWords: "Border, Color, BorderColor, Border Color",
events: {
change: (val: StyleValue) => {
blockController.setStyle("borderColor", val);
if (val) {
if (!blockController.getStyle("borderWidth")) {
blockController.setStyle("borderWidth", "1px");
blockController.setStyle("borderStyle", "solid");
}
} else {
blockController.setStyle("borderWidth", null);
blockController.setStyle("borderStyle", null);
}
},
},
},
{
component: InlineInput,
getProps: () => {
return {
label: "Border Width",
modelValue: blockController.getStyle("borderWidth"),
enableSlider: true,
unitOptions: ["px", "%", "em", "rem"],
minValue: 0,
};
},
searchKeyWords: "Border, Width, BorderWidth, Border Width",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("borderWidth", val),
},
condition: () => blockController.getStyle("borderColor") || blockController.getStyle("borderWidth"),
},
{
component: InlineInput,
getProps: () => {
return {
label: "Border Style",
modelValue: blockController.getStyle("borderStyle"),
type: "select",
options: ["solid", "dashed", "dotted"],
};
},
searchKeyWords: "Border, Style, BorderStyle, Border Style, Solid, Dashed, Dotted",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("borderStyle", val),
},
condition: () => blockController.getStyle("borderColor"),
},
{
component: BackgroundHandler,
getProps: () => {},
searchKeyWords:
"Background, BackgroundImage, Background Image, Background Position, Background Repeat, Background Size, BG, BGImage, BG Image, BGPosition, BG Position, BGRepeat, BG Repeat, BGSize, BG Size",
},
{
component: InlineInput,
getProps: () => {
return {
label: "Shadow",
type: "select",
options: [
{
value: null,
label: "None",
},
{
label: "Small",
value:
"rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0.05) 0px 1px 2px 0px, rgba(0, 0, 0, 0.05) 0px 1px 3px 0px",
},
{
label: "Medium",
value:
"rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.1) 0px 4px 6px -4px",
},
{
label: "Large",
value:
"rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0.1) 0px 20px 25px -5px, rgba(0, 0, 0, 0.1) 0px 10px 10px -5px",
},
],
modelValue: blockController.getStyle("boxShadow"),
};
},
searchKeyWords: "Shadow, BoxShadow, Box Shadow",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("boxShadow", val),
},
},
{
component: InlineInput,
getProps: () => {
return {
label: "Radius",
modelValue: blockController.getStyle("borderRadius"),
enableSlider: true,
unitOptions: ["px", "%"],
minValue: 0,
};
},
searchKeyWords: "Border, Radius, BorderRadius, Border Radius",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("borderRadius", val),
},
},
{
component: InlineInput,
getProps: () => {
return {
label: "Z-Index",
modelValue: blockController.getStyle("zIndex"),
};
},
searchKeyWords: "Z, Index, ZIndex, Z Index",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("zIndex", val),
},
condition: () =>
!blockController.multipleBlocksSelected() &&
!blockController.isRoot() &&
blockController.getStyle("position") !== "static",
},
];
const dimensionSectionProperties = [
{
component: DimensionInput,
searchKeyWords: "Width",
getProps: () => {
return {
label: "Width",
property: "width",
};
},
},
{
component: DimensionInput,
searchKeyWords: "Min, Width, MinWidth, Min Width",
getProps: () => {
return {
label: "Min Width",
property: "minWidth",
};
},
},
{
component: DimensionInput,
searchKeyWords: "Max, Width, MaxWidth, Max Width",
getProps: () => {
return {
label: "Max Width",
property: "maxWidth",
};
},
},
{
component: "hr",
getProps: () => {
return {
class: "dark:border-zinc-700",
};
},
searchKeyWords: "",
},
{
component: DimensionInput,
searchKeyWords: "Height",
getProps: () => {
return {
label: "Height",
property: "height",
};
},
},
{
component: DimensionInput,
searchKeyWords: "Min, Height, MinHeight, Min Height",
getProps: () => {
return {
label: "Min Height",
property: "minHeight",
};
},
},
{
component: DimensionInput,
searchKeyWords: "Max, Height, MaxHeight, Max Height",
getProps: () => {
return {
label: "Max Height",
property: "maxHeight",
};
},
},
];
const positionSectionProperties = [
{
component: BlockPositionHandler,
searchKeyWords:
"Position, Top, Right, Bottom, Left, PositionTop, Position Top, PositionRight, Position Right, PositionBottom, Position Bottom, PositionLeft, Position Left, Free, Fixed, Absolute, Relative, Sticky",
getProps: () => {},
},
];
const spacingSectionProperties = [
{
component: InlineInput,
searchKeyWords: "Margin, Top, MarginTop, Margin Top",
getProps: () => {
return {
label: "Margin",
modelValue: blockController.getMargin(),
};
},
events: {
"update:modelValue": (val: string) => blockController.setMargin(val),
},
condition: () => !blockController.isRoot(),
},
{
component: InlineInput,
searchKeyWords: "Padding, Top, PaddingTop, Padding Top",
getProps: () => {
return {
label: "Padding",
modelValue: blockController.getPadding(),
};
},
events: {
"update:modelValue": (val: string) => blockController.setPadding(val),
},
},
];
const optionsSectionProperties = [
{
component: InlineInput,
getProps: () => {
return {
label: "Tag",
type: "select",
options: [
"aside",
"article",
"span",
"div",
"section",
"button",
"p",
"a",
"input",
"hr",
"form",
"textarea",
"nav",
"header",
"footer",
"select",
"option",
],
modelValue: blockController.getKeyValue("element"),
};
},
searchKeyWords:
"Tag, Element, TagName, Tag Name, ElementName, Element Name, header, footer, nav, input, form, textarea, button, p, a, div, span, section, hr, TagType, Tag Type, ElementType, Element Type",
events: {
"update:modelValue": (val: string) => blockController.setKeyValue("element", val),
},
},
{
component: InlineInput,
getProps: () => {
return {
label: "Image URL",
modelValue: blockController.getAttribute("src"),
};
},
searchKeyWords: "Image, URL, Src",
events: {
"update:modelValue": (val: string) => blockController.setAttribute("src", val),
},
condition: () => blockController.isImage(),
},
{
component: Button,
getProps: () => {
return {
label: "Convert to WebP",
class: "text-base dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700",
};
},
innerText: "Convert to WebP",
searchKeyWords: "Convert, webp, Convert to webp, image, src, url",
events: {
click: () => {
const block = blockController.getSelectedBlocks()[0];
const convertToWebP = createResource({
url: "/api/method/builder.api.convert_to_webp",
params: {
image_url: block.getAttribute("src"),
},
});
toast.promise(
convertToWebP.fetch().then((res: string) => {
block.setAttribute("src", res);
}),
{
loading: "Converting...",
success: () => "Image converted to WebP",
error: () => "Failed to convert image to WebP",
},
);
},
},
condition: () => {
if (!blockController.isImage()) {
return false;
}
if (
[".jpg", ".jpeg", ".png"].some((ext) =>
((blockController.getAttribute("src") as string) || ("" as string)).toLowerCase().endsWith(ext),
)
) {
return true;
}
},
},
{
component: InlineInput,
getProps: () => {
return {
label: "Image Fit",
type: "select",
options: ["fill", "contain", "cover", "none"],
modelValue: blockController.getStyle("objectFit"),
};
},
searchKeyWords: "Image, Fit, ObjectFit, Object Fit, Fill, Contain, Cover, None",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("objectFit", val),
},
condition: () => blockController.isImage(),
},
{
component: InlineInput,
getProps: () => {
return {
label: "Input Type",
type: "select",
options: ["text", "number", "email", "password", "date", "time", "search", "tel", "url", "color"],
modelValue: blockController.getAttribute("type") || "text",
};
},
searchKeyWords:
"Input, Type, InputType, Input Type, Text, Number, Email, Password, Date, Time, Search, Tel, Url, Color, tag",
events: {
"update:modelValue": (val: string) => blockController.setAttribute("type", val),
},
condition: () => blockController.isInput(),
},
{
component: InlineInput,
getProps: () => {
return {
label: "Placeholder",
modelValue: blockController.getAttribute("placeholder"),
};
},
searchKeyWords:
"Placeholder, Input, PlaceholderText, Placeholder Text, form, input, text, number, email, password, date, time, search, tel, url, color, tag",
events: {
"update:modelValue": (val: string) => blockController.setAttribute("placeholder", val),
},
condition: () => blockController.isInput(),
},
{
component: InlineInput,
getProps: () => {
return {
label: "Content",
// @ts-ignore
modelValue: blockController.getSelectedBlocks()[0]?.__proto__?.editor?.getText(),
};
},
searchKeyWords: "Content, Text, ContentText, Content Text",
events: {
"update:modelValue": (val: string) => blockController.setKeyValue("innerHTML", val),
},
condition: () => blockController.isText() || blockController.isButton(),
},
{
component: OptionToggle,
getProps: () => {
return {
label: "Visibility",
options: [
{
label: "Visible",
value: "flex",
},
{
label: "Hidden",
value: "none",
},
],
modelValue: blockController.getStyle("display") || "flex",
};
},
searchKeyWords: "Visibility, Display, Visible, Hidden, Flex, None, hide, show",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("display", val),
},
},
{
component: InlineInput,
getProps: () => {
return {
label: "Overflow X",
type: "select",
options: ["auto", "visible", "hidden", "scroll"],
modelValue: blockController.getStyle("overflowX") || blockController.getStyle("overflow"),
};
},
searchKeyWords:
"Overflow, X, OverflowX, Overflow X, Auto, Visible, Hide, Scroll, horizontal scroll, horizontalScroll",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("overflowX", val),
},
},
{
component: InlineInput,
getProps: () => {
return {
label: "Overflow Y",
type: "select",
options: ["auto", "visible", "hidden", "scroll"],
modelValue: blockController.getStyle("overflowY") || blockController.getStyle("overflow"),
};
},
searchKeyWords:
"Overflow, Y, OverflowY, Overflow Y, Auto, Visible, Hide, Scroll, vertical scroll, verticalScroll",
events: {
"update:modelValue": (val: StyleValue) => blockController.setStyle("overflowY", val),
},
},
{
component: InlineInput,
getProps: () => {
return {
label: "Alt Text",
modelValue: blockController.getAttribute("alt"),
};
},
searchKeyWords: "Alt, Text, AltText, Alternate Text",
events: {
"update:modelValue": (val: string) => blockController.setAttribute("alt", val),
},
condition: () => blockController.isImage(),
},
{
component: InlineInput,
getProps: () => {
return {
label: "Class",
modelValue: blockController.getClasses().join(", "),
};
},
searchKeyWords: "Class, ClassName, Class Name",
events: {
"update:modelValue": (val: string) => setClasses(val || ""),
},
condition: () => !blockController.multipleBlocksSelected(),
},
{
component: CodeEditor,
getProps: () => {
return {
label: "HTML",
type: "HTML",
autofocus: false,
modelValue: blockController.getInnerHTML() || "",
};
},
searchKeyWords: "HTML, InnerHTML, Inner HTML",
events: {
"update:modelValue": (val: string) => {
blockController.setInnerHTML(val);
},
},
condition: () =>
blockController.isHTML() || (blockController.getInnerHTML() && !blockController.isText()),
},
{
component: InlineInput,
getProps: () => {
return {
label: "Condition",
modelValue: blockController.getKeyValue("visibilityCondition"),
description:
"Visibility condition to show/hide the block based on a condition. Pass a boolean variable created in your Data Script.<br><b>Note:</b> This is only evaluated in the preview mode.",
};
},
searchKeyWords:
"Condition, Visibility, VisibilityCondition, Visibility Condition, show, hide, display, hideIf, showIf",
events: {
"update:modelValue": (val: string) => blockController.setKeyValue("visibilityCondition", val),
},
},
];
const dataKeySectionProperties = [
{
component: InlineInput,
getProps: () => {
return {
label: "Key",
modelValue: blockController.getDataKey("key"),
};
},
searchKeyWords: "Key, DataKey, Data Key",
events: {
"update:modelValue": (val: string) => blockController.setDataKey("key", val),
},
},
{
component: InlineInput,
condition: () => !blockController.isRepeater(),
getProps: () => {
return {
label: "Type",
modelValue: blockController.getDataKey("type"),
};
},
searchKeyWords: "Type, DataType, Data Type",
events: {
"update:modelValue": (val: string) => blockController.setDataKey("type", val),
},
},
{
component: InlineInput,
condition: () => !blockController.isRepeater(),
getProps: () => {
return {
label: "Property",
modelValue: blockController.getDataKey("property"),
};
},
searchKeyWords: "Property, DataProperty, Data Property",
events: {
"update:modelValue": (val: string) => blockController.setDataKey("property", val),
},
},
];
const customAttributesSectionProperties = [
{
component: ObjectEditor,
getProps: () => {
return {
obj: blockController.getCustomAttributes() as Record<string, string>,
};
},
searchKeyWords: "Attributes, CustomAttributes, Custom Attributes, HTML Attributes, Data Attributes",
events: {
"update:obj": (obj: Record<string, string>) => blockController.setCustomAttributes(obj),
},
},
];
const rawStyleSectionProperties = [
{
component: ObjectEditor,
getProps: () => {
return {
obj: blockController.getRawStyles() as Record<string, string>,
description: `
<b>Note:</b>
<br />
<br />
- Raw styles get applied across all devices
<br />
- State based styles are supported (e.g. hover, focus, visited)
<br />
Syntax: hover:color, focus:color, etc.
<br />
- State styles are only activated in preview mode
`,
};
},
searchKeyWords: "Raw, RawStyle, Raw Style, CSS, Style, Styles",
events: {
"update:obj": (obj: Record<string, string>) => blockController.setRawStyles(obj),
},
},
];
const videoOptionsSectionProperties = [
{
component: InlineInput,
getProps: () => {
return {
label: "Video URL",
modelValue: blockController.getAttribute("src"),
};
},
searchKeyWords: "Video, URL, Src",
events: {
"update:modelValue": (val: string) => blockController.setAttribute("src", val),
},
},
{
component: InlineInput,
getProps: () => {
return {
label: "Poster",
modelValue: blockController.getAttribute("poster"),
};
},
searchKeyWords: "Poster",
events: {
"update:modelValue": (val: string) => blockController.setAttribute("poster", val),
},
},
{
component: OptionToggle,
getProps: () => {
return {
label: "Controls",
options: [
{
label: "Show",
value: "true",
},
{
label: "Hide",
value: "false",
},
],
modelValue: blockController.getAttribute("controls") === "" ? "true" : "false",
};
},
searchKeyWords: "Controls, volume, play, pause, stop, mute, unmute, fullscreen, full screen",
events: {
"update:modelValue": (val: boolean) => blockController.toggleAttribute("controls"),
},
},
{
component: OptionToggle,
getProps: () => {
return {
label: "Autoplay",
options: [
{
label: "Yes",
value: "true",
},
{
label: "No",
value: "false",
},
],
modelValue: blockController.getAttribute("autoplay") === "" ? "true" : "false",
};
},
searchKeyWords: "Autoplay, Auto Play",
events: {
"update:modelValue": (val: boolean) => blockController.toggleAttribute("autoplay"),
},
},
{
component: OptionToggle,
getProps: () => {
return {
label: "Muted",
options: [
{
label: "Yes",
value: "true",
},
{
label: "No",
value: "false",
},
],
modelValue: blockController.getAttribute("muted") === "" ? "true" : "false",
};
},
searchKeyWords: "Muted",
events: {
"update:modelValue": (val: boolean) => blockController.toggleAttribute("muted"),
},
},
{
component: OptionToggle,
getProps: () => {
return {
label: "Loop",
options: [
{
label: "Yes",
value: "true",
},
{
label: "No",
value: "false",
},
],
modelValue: blockController.getAttribute("loop") === "" ? "true" : "false",
};
},
searchKeyWords: "Loop",
events: {
"update:modelValue": (val: boolean) => blockController.toggleAttribute("loop"),
},
},
];
const sections = [
{
name: "Link",
properties: linkSectionProperties,
collapsed: computed(() => !blockController.isLink()),
condition: () => !blockController.multipleBlocksSelected(),
},
{
name: "Layout",
properties: layoutSectionProperties,
condition: () => !blockController.multipleBlocksSelected(),
},
{
name: "Typography",
properties: typographySectionProperties,
condition: () => blockController.isText() || blockController.isContainer() || blockController.isInput(),
},
{
name: "Style",
properties: styleSectionProperties,
},
{
name: "Video Options",
properties: videoOptionsSectionProperties,
condition: () => blockController.isVideo(),
},
{
name: "Dimension",
properties: dimensionSectionProperties,
},
{
name: "Position",
properties: positionSectionProperties,
condition: () => !blockController.multipleBlocksSelected(),
collapsed: computed(() => {
return (
!blockController.getStyle("top") &&
!blockController.getStyle("right") &&
!blockController.getStyle("bottom") &&
!blockController.getStyle("left")
);
}),
},
{
name: "Spacing",
properties: spacingSectionProperties,
collapsed: computed(
() =>
!blockController.getStyle("marginTop") &&
!blockController.getStyle("paddingTop") &&
!blockController.getStyle("marginBottom") &&
!blockController.getStyle("paddingBottom"),
),
},
{
name: "Options",
properties: optionsSectionProperties,
},
{
name: "Data Key",
properties: dataKeySectionProperties,
collapsed: false,
},
{
name: "HTML Attributes",
properties: customAttributesSectionProperties,
collapsed: computed(() => {
return Object.keys(blockController.getCustomAttributes()).length === 0;
}),
},
{
name: "Raw Style",
properties: rawStyleSectionProperties,
collapsed: computed(() => {
return Object.keys(blockController.getRawStyles()).length === 0;
}),
},
] as PropertySection[];
</script>
|
2302_79757062/builder
|
frontend/src/components/BlockProperties.vue
|
Vue
|
agpl-3.0
| 30,897
|
<template>
<div>
<div
class="x fixed bottom-0 top-0 z-10 w-[1px] bg-pink-600"
v-if="store.guides.showX"
:style="{
left: store.guides.x + 'px',
}"></div>
<div
class="y fixed left-0 right-0 z-10 h-[1px] bg-pink-600"
v-if="store.guides.showY"
:style="{
top: store.guides.y + 'px',
}"></div>
</div>
</template>
<script setup lang="ts">
import useStore from "../store";
const store = useStore();
</script>
|
2302_79757062/builder
|
frontend/src/components/BlockSnapGuides.vue
|
Vue
|
agpl-3.0
| 439
|
<template>
<div
ref="handler"
class="border-radius-resize pointer-events-auto absolute left-2 top-2 h-[10px] w-[10px] cursor-pointer rounded-full border-2 border-blue-400 bg-white"
:class="{
hidden: canvasProps.scale < 0.4 || !showHandler(),
}"
:style="{
top: handlerTop + 'px',
left: handlerLeft + 'px',
}"
@mousedown.stop="handleRounded">
<div
class="absolute left-2 top-2 w-fit rounded-full bg-zinc-800 px-3 py-2 text-xs text-white opacity-60"
v-show="updating">
{{ borderRadius }}
</div>
</div>
</template>
<script setup lang="ts">
import { getNumberFromPx } from "@/utils/helpers";
import { Ref, inject, onMounted, ref } from "vue";
import Block from "../utils/block";
const props = defineProps({
targetBlock: {
type: Block,
required: true,
},
target: {
type: [HTMLElement, SVGElement],
required: true,
},
});
const borderRadius = ref(parseInt(props.target.style.borderRadius, 10) || 0);
const updating = ref(false);
const canvasProps = inject("canvasProps") as CanvasProps;
const handler = ref() as Ref<HTMLElement>;
const handlerTop = ref(10);
const handlerLeft = ref(10);
let minLeft = 10;
let minTop = 10;
const handleRounded = (ev: MouseEvent) => {
const startX = ev.clientX;
const startY = ev.clientY;
const handleStyle = window.getComputedStyle(handler.value);
const handleHeight = parseInt(handleStyle.height, 10);
const handleWidth = parseInt(handleStyle.width, 10);
let lastX = startX;
let lastY = startY;
updating.value = true;
const mousemove = (mouseMoveEvent: MouseEvent) => {
mouseMoveEvent.preventDefault();
const movementX = mouseMoveEvent.clientX - lastX;
const movementY = mouseMoveEvent.clientY - lastY;
// mean of movement on both axis
const movement = ((movementX + movementY) / 2) * 2;
if (movement < 0) {
minTop = -(handleHeight / 2);
minLeft = -(handleWidth / 2);
}
let radius = Math.round(getNumberFromPx(props.target.style.borderRadius) + movement);
radius = Math.max(0, Math.min(radius, maxRadius));
setHandlerPosition(radius);
borderRadius.value = radius;
props.targetBlock.setStyle("borderRadius", `${radius}px`);
lastX = mouseMoveEvent.clientX;
lastY = mouseMoveEvent.clientY;
};
document.addEventListener("mousemove", mousemove);
document.addEventListener(
"mouseup",
(mouseUpEvent) => {
mouseUpEvent.preventDefault();
if (getNumberFromPx(props.targetBlock.getStyle("borderRadius")) < 10) {
handlerTop.value = 10;
handlerLeft.value = 10;
}
updating.value = false;
document.removeEventListener("mousemove", mousemove);
},
{ once: true }
);
};
const targetStyle = window.getComputedStyle(props.target);
const targetWidth = parseInt(targetStyle.width, 10);
const targetHeight = parseInt(targetStyle.height, 10);
const targetBounds = props.target.getBoundingClientRect();
const maxDistance = Math.min(targetBounds.height, targetBounds.width) / 2;
const maxRadius = Math.min(targetHeight, targetWidth) / 2;
const setHandlerPosition = (radius: number) => {
// refer position based on bounding rect of target (target could have been scaled)
const handleStyle = window.getComputedStyle(handler.value);
const handleHeight = parseInt(handleStyle.height, 10);
const handleWidth = parseInt(handleStyle.width, 10);
const ratio = radius / maxRadius;
handlerTop.value = Math.max(minTop, maxDistance * ratio - handleHeight / 2);
handlerLeft.value = Math.max(minLeft, maxDistance * ratio - handleWidth / 2);
};
const showHandler = () => {
canvasProps.scale;
props.targetBlock.getStyle("height");
props.targetBlock.getStyle("width");
const targetBounds = props.target.getBoundingClientRect();
return getNumberFromPx(targetBounds.height) >= 25 && getNumberFromPx(targetBounds.width) >= 25;
};
onMounted(() => {
setHandlerPosition(borderRadius.value);
});
</script>
|
2302_79757062/builder
|
frontend/src/components/BorderRadiusHandler.vue
|
Vue
|
agpl-3.0
| 3,840
|
<template>
<span
class="resize-dimensions absolute bottom-[-40px] right-[-40px] flex h-8 w-20 items-center justify-center whitespace-nowrap rounded-full bg-gray-600 p-2 text-sm text-white opacity-80"
v-if="resizing && !props.targetBlock.isText()">
{{ targetWidth }} x
{{ targetHeight }}
</span>
<span
class="resize-dimensions absolute bottom-[-40px] right-[-40px] flex h-8 w-fit items-center justify-center whitespace-nowrap rounded-full bg-gray-600 p-2 text-sm text-white opacity-80"
v-if="resizing && props.targetBlock.isText()">
{{ fontSize }}
</span>
<div
class="left-handle ew-resize pointer-events-auto absolute bottom-0 left-[-2px] top-0 w-2 border-none bg-transparent" />
<div
class="right-handle pointer-events-auto absolute bottom-0 right-[-2px] top-0 w-2 border-none bg-transparent"
:class="{ 'cursor-ew-resize': true }"
@mousedown.stop="handleRightResize" />
<div
class="top-handle ns-resize pointer-events-auto absolute left-0 right-0 top-[-2px] h-2 border-none bg-transparent" />
<div
class="bottom-handle pointer-events-auto absolute bottom-[-2px] left-0 right-0 h-2 border-none bg-transparent"
:class="{ 'cursor-ns-resize': true }"
@mousedown.stop="handleBottomResize" />
<div
class="pointer-events-auto absolute bottom-[-5px] right-[-5px] h-[12px] w-[12px] cursor-nwse-resize rounded-full border-[2.5px] border-blue-400 bg-white"
v-show="!resizing"
@mousedown.stop="handleBottomCornerResize" />
</template>
<script setup lang="ts">
import { getNumberFromPx } from "@/utils/helpers";
import { clamp } from "@vueuse/core";
import { computed, inject, onMounted, ref, watch } from "vue";
import useStore from "../store";
import Block from "../utils/block";
import guidesTracker from "../utils/guidesTracker";
const props = defineProps({
targetBlock: {
type: Block,
default: null,
},
target: {
type: [HTMLElement, SVGElement],
default: null,
},
});
const emit = defineEmits(["resizing"]);
const store = useStore();
const resizing = ref(false);
let guides = null as unknown as ReturnType<typeof guidesTracker>;
const canvasProps = inject("canvasProps") as CanvasProps;
onMounted(() => {
guides = guidesTracker(props.target as HTMLElement, canvasProps);
});
watch(resizing, () => {
if (resizing.value) {
store.activeCanvas?.history.pause();
emit("resizing", true);
} else {
store.activeCanvas?.history.resume(true);
emit("resizing", false);
}
});
const targetWidth = computed(() => {
props.targetBlock.getStyle("width"); // to trigger reactivity
return Math.round(getNumberFromPx(getComputedStyle(props.target).getPropertyValue("width")));
});
const targetHeight = computed(() => {
props.targetBlock.getStyle("height"); // to trigger reactivity
return Math.round(getNumberFromPx(getComputedStyle(props.target).getPropertyValue("height")));
});
const fontSize = computed(() => {
props.targetBlock.getStyle("fontSize"); // to trigger reactivity
return Math.round(getNumberFromPx(getComputedStyle(props.target).getPropertyValue("font-size")));
});
const handleRightResize = (ev: MouseEvent) => {
const startX = ev.clientX;
const startHeight = props.target.offsetHeight;
const startWidth = props.target.offsetWidth;
const blockStartWidth = props.targetBlock.getStyle("width") as string;
const blockStartHeight = props.targetBlock.getStyle("height") as string;
const startFontSize = fontSize.value || 0;
// to disable cursor jitter
const docCursor = document.body.style.cursor;
document.body.style.cursor = window.getComputedStyle(ev.target as HTMLElement).cursor;
resizing.value = true;
guides.showX();
const mousemove = (mouseMoveEvent: MouseEvent) => {
const movement = (mouseMoveEvent.clientX - startX) / canvasProps.scale;
if (props.targetBlock.isText() && !props.targetBlock.hasChildren()) {
setFontSize(movement, startFontSize);
return mouseMoveEvent.preventDefault();
}
setWidth(movement, startWidth, blockStartWidth);
if (mouseMoveEvent.shiftKey) {
setHeight(movement, startHeight, blockStartHeight);
}
mouseMoveEvent.preventDefault();
};
document.addEventListener("mousemove", mousemove);
document.addEventListener(
"mouseup",
(mouseUpEvent) => {
document.body.style.cursor = docCursor;
document.removeEventListener("mousemove", mousemove);
mouseUpEvent.preventDefault();
resizing.value = false;
guides.hideX();
},
{ once: true },
);
};
const handleBottomResize = (ev: MouseEvent) => {
const startY = ev.clientY;
const startHeight = props.target.offsetHeight;
const startWidth = props.target.offsetWidth;
const blockStartWidth = props.targetBlock.getStyle("width") as string;
const blockStartHeight = props.targetBlock.getStyle("height") as string;
const startFontSize = fontSize.value || 0;
// to disable cursor jitter
const docCursor = document.body.style.cursor;
document.body.style.cursor = window.getComputedStyle(ev.target as HTMLElement).cursor;
resizing.value = true;
guides.showY();
const mousemove = (mouseMoveEvent: MouseEvent) => {
const movement = (mouseMoveEvent.clientY - startY) / canvasProps.scale;
if (props.targetBlock.isText() && !props.targetBlock.hasChildren()) {
setFontSize(movement, startFontSize);
return mouseMoveEvent.preventDefault();
}
setHeight(movement, startHeight, blockStartHeight);
if (mouseMoveEvent.shiftKey) {
setWidth(movement, startWidth, blockStartWidth);
}
mouseMoveEvent.preventDefault();
};
document.addEventListener("mousemove", mousemove);
document.addEventListener(
"mouseup",
(mouseUpEvent) => {
document.body.style.cursor = docCursor;
document.removeEventListener("mousemove", mousemove);
mouseUpEvent.preventDefault();
resizing.value = false;
guides.hideY();
},
{ once: true },
);
};
const handleBottomCornerResize = (ev: MouseEvent) => {
const startX = ev.clientX;
const startY = ev.clientY;
const startHeight = props.target.offsetHeight;
const startWidth = props.target.offsetWidth;
const blockStartWidth = props.targetBlock.getStyle("width") as string;
const blockStartHeight = props.targetBlock.getStyle("height") as string;
const startFontSize = fontSize.value || 0;
// to disable cursor jitter
const docCursor = document.body.style.cursor;
document.body.style.cursor = window.getComputedStyle(ev.target as HTMLElement).cursor;
resizing.value = true;
const mousemove = (mouseMoveEvent: MouseEvent) => {
const movementX = (mouseMoveEvent.clientX - startX) / canvasProps.scale;
const movementY = (mouseMoveEvent.clientY - startY) / canvasProps.scale;
if (props.targetBlock.isText() && !props.targetBlock.hasChildren()) {
setFontSize(movementY, startFontSize);
return mouseMoveEvent.preventDefault();
}
setWidth(movementX, startWidth, blockStartWidth);
setHeight(mouseMoveEvent.shiftKey ? movementX : movementY, startHeight, blockStartHeight);
mouseMoveEvent.preventDefault();
};
document.addEventListener("mousemove", mousemove);
document.addEventListener(
"mouseup",
(mouseUpEvent) => {
document.body.style.cursor = docCursor;
document.removeEventListener("mousemove", mousemove);
mouseUpEvent.preventDefault();
resizing.value = false;
},
{ once: true },
);
};
const setWidth = (movementX: number, startWidth: number, blockStartWidth: string) => {
const finalWidth = Math.round(startWidth + movementX);
if (blockStartWidth?.includes("%")) {
const parentWidth = props.target.parentElement?.offsetWidth || 0;
const movementPercent = (movementX / parentWidth) * 100;
const startWidthPercent = (startWidth / parentWidth) * 100;
const finalWidthPercent = Math.abs(Math.round(startWidthPercent + movementPercent));
props.targetBlock.setStyle("width", `${finalWidthPercent}%`);
} else {
props.targetBlock.setStyle("width", `${finalWidth}px`);
}
};
const setHeight = (movementY: number, startHeight: number, blockStartHeight: string) => {
const finalHeight = Math.round(startHeight + movementY);
if (blockStartHeight?.includes("%")) {
const parentHeight = props.target.parentElement?.offsetHeight || 0;
const movementPercent = (movementY / parentHeight) * 100;
const startHeightPercent = (startHeight / parentHeight) * 100;
const finalHeightPercent = Math.abs(Math.round(startHeightPercent + movementPercent));
props.targetBlock.setStyle("height", `${finalHeightPercent}%`);
} else {
props.targetBlock.setStyle("height", `${finalHeight}px`);
}
};
const setFontSize = (movement: number, startFontSize: number) => {
const fontSize = clamp(Math.round(startFontSize + 0.5 * movement), 10, 300);
props.targetBlock.setStyle("fontSize", `${fontSize}px`);
};
</script>
|
2302_79757062/builder
|
frontend/src/components/BoxResizer.vue
|
Vue
|
agpl-3.0
| 8,633
|
<template>
<div class="flex flex-col gap-3">
<CollapsibleSection :sectionName="'Block Templates'">
<div v-show="blockTemplates.length > 10 || blockTemplateFilter">
<Input
type="text"
placeholder="Search component"
v-model="blockTemplateFilter"
@input="
(value: string) => {
blockTemplateFilter = value;
}
" />
</div>
<div class="grid grid-cols-2 gap-4">
<div v-for="blockTemplate in blockTemplates" :key="blockTemplate.name" class="flex">
<div
class="relative flex h-24 w-full translate-x-0 translate-y-0 cursor-pointer flex-col items-center justify-center gap-2 overflow-hidden truncate rounded border border-transparent bg-gray-100 px-2 py-1.5 dark:bg-zinc-800"
draggable="true"
@click="is_developer_mode && store.editBlockTemplate(blockTemplate.name)"
@dragstart="(ev) => setBlockTemplateData(ev, blockTemplate)">
<div class="flex h-11 w-15 items-center justify-center">
<img :src="blockTemplate.preview" class="text-gray-800 dark:text-zinc-400" />
</div>
<p class="text-sm text-gray-800 dark:text-zinc-400">
{{ blockTemplate.template_name }}
</p>
</div>
</div>
</div>
</CollapsibleSection>
<CollapsibleSection :sectionName="'Components'">
<div v-show="components.length > 10 || componentFilter">
<Input
type="text"
placeholder="Search component"
v-model="componentFilter"
@input="
(value: string) => {
componentFilter = value;
}
" />
</div>
<div>
<div v-show="!components.length" class="mt-2 text-base italic text-gray-600">No components saved</div>
<div v-for="component in components" :key="component.name" class="flex w-full">
<div class="component-container group relative flex w-full flex-col">
<div
class="relative flex translate-x-0 translate-y-0 cursor-pointer items-center justify-between overflow-hidden truncate rounded border border-transparent bg-white px-2 py-1.5 dark:bg-zinc-900"
draggable="true"
:class="{
'!border-gray-400 dark:!border-zinc-600':
store.fragmentData.fragmentName === component.component_name,
}"
@click="store.editComponent(null, component.name)"
@dragstart="(ev) => setComponentData(ev, component)">
<div class="flex items-center gap-2">
<FeatherIcon :name="'box'" class="h-4 w-4 text-gray-800 dark:text-zinc-400"></FeatherIcon>
<p class="text-base text-gray-800 dark:text-zinc-400">
{{ component.component_name }}
</p>
</div>
<FeatherIcon
name="trash"
class="hidden h-3 w-3 cursor-pointer text-gray-800 group-hover:block dark:text-zinc-400"
@click.stop.prevent="deleteComponent(component)"></FeatherIcon>
</div>
</div>
</div>
</div>
</CollapsibleSection>
</div>
</template>
<script setup lang="ts">
import builderBlockTemplate from "@/data/builderBlockTemplate";
import webComponent from "@/data/webComponent";
import useStore from "@/store";
import { BuilderComponent } from "@/types/Builder/BuilderComponent";
import { confirm } from "@/utils/helpers";
import { computed, ref } from "vue";
import CollapsibleSection from "./CollapsibleSection.vue";
import Input from "./Input.vue";
const store = useStore();
const componentFilter = ref("");
const is_developer_mode = window.is_developer_mode;
const components = computed(() =>
(webComponent.data || []).filter((d: BuilderComponent) => {
if (d.for_web_page && d.for_web_page !== store.selectedPage) {
return false;
}
if (componentFilter.value) {
return d.component_name?.toLowerCase().includes(componentFilter.value.toLowerCase());
} else {
return true;
}
}),
);
const blockTemplateFilter = ref("");
const blockTemplates = computed(() => {
return builderBlockTemplate.data.filter((d) => {
if (blockTemplateFilter.value) {
return d.name?.toLowerCase().includes(blockTemplateFilter.value.toLowerCase());
} else {
return true;
}
});
});
const deleteComponent = async (component: BlockComponent) => {
if (store.isComponentUsed(component.name)) {
alert("Component is used in current page. You cannot delete it.");
} else {
const confirmed = await confirm(
`Are you sure you want to delete component: ${component.component_name}?`,
);
if (confirmed) {
webComponent.delete.submit(component.name).then(() => {
store.componentMap.delete(component.name);
});
}
}
};
const setComponentData = (ev: DragEvent, component: BlockComponent) => {
ev?.dataTransfer?.setData("componentName", component.name);
};
const setBlockTemplateData = (ev: DragEvent, component: BlockComponent) => {
ev?.dataTransfer?.setData("blockTemplate", component.name);
};
</script>
|
2302_79757062/builder
|
frontend/src/components/BuilderAssets.vue
|
Vue
|
agpl-3.0
| 4,783
|
<template>
<component
:is="getComponentName(block)"
:selected="isSelected"
@click="handleClick"
@dblclick="handleDoubleClick"
@contextmenu="triggerContextMenu($event)"
@mouseover="handleMouseOver"
@mouseleave="handleMouseLeave"
:data-block-id="block.blockId"
:draggable="draggable"
:class="classes"
v-bind="attributes"
:style="styles"
v-if="showBlock"
ref="component">
<BuilderBlock
:data="data"
:block="child"
:breakpoint="breakpoint"
:preview="preview"
:isChildOfComponent="block.isExtendedFromComponent() || isChildOfComponent"
:key="child.blockId"
v-for="child in block.getChildren()" />
</component>
<teleport to="#overlay" v-if="canvasProps?.overlayElement && !preview && Boolean(canvasProps)">
<!-- prettier-ignore -->
<BlockEditor
ref="editor"
v-if="loadEditor"
:block="block"
:breakpoint="breakpoint"
:editable="isEditable"
:isSelected="isSelected"
:target="(target as HTMLElement)" />
</teleport>
</template>
<script setup lang="ts">
import Block from "@/utils/block";
import { setFont } from "@/utils/fontManager";
import { computed, inject, nextTick, onMounted, reactive, ref, useAttrs, watch, watchEffect } from "vue";
import getBlockTemplate from "@/utils/blockTemplate";
import { getDataForKey } from "@/utils/helpers";
import { useDraggableBlock } from "@/utils/useDraggableBlock";
import useStore from "../store";
import BlockEditor from "./BlockEditor.vue";
import BlockHTML from "./BlockHTML.vue";
import DataLoaderBlock from "./DataLoaderBlock.vue";
import TextBlock from "./TextBlock.vue";
const component = ref<HTMLElement | InstanceType<typeof TextBlock> | null>(null);
const attrs = useAttrs();
const store = useStore();
const editor = ref<InstanceType<typeof BlockEditor> | null>(null);
const props = defineProps({
block: {
type: Block,
required: true,
},
isChildOfComponent: {
type: Boolean,
default: false,
},
breakpoint: {
type: String,
default: "desktop",
},
preview: {
type: Boolean,
default: false,
},
data: {
type: Object,
default: null,
},
});
defineOptions({
inheritAttrs: false,
});
const draggable = computed(() => {
// TODO: enable this
return !props.block.isRoot() && !props.preview && false;
});
const isHovered = ref(false);
const isSelected = ref(false);
const getComponentName = (block: Block) => {
if (block.isRepeater()) {
return DataLoaderBlock;
}
if (block.isText() || block.isLink() || block.isButton()) {
return TextBlock;
} else if (block.isHTML()) {
return BlockHTML;
} else {
return block.getTag();
}
};
const classes = computed(() => {
return [attrs.class, "__builder_component__", "outline-none", "select-none", ...props.block.getClasses()];
});
const attributes = computed(() => {
const attribs = { ...props.block.getAttributes(), ...attrs } as { [key: string]: any };
if (
props.block.isText() ||
props.block.isHTML() ||
props.block.isLink() ||
props.block.isButton() ||
props.block.isRepeater()
) {
attribs.block = props.block;
attribs.preview = props.preview;
attribs.breakpoint = props.breakpoint;
attribs.data = props.data;
}
if (props.data) {
if (props.block.getDataKey("type") === "attribute") {
attribs[props.block.getDataKey("property") as string] =
getDataForKey(props.data, props.block.getDataKey("key")) ||
attribs[props.block.getDataKey("property") as string];
}
}
if (props.block.isInput()) {
attribs.readonly = true;
}
return attribs;
});
const canvasProps = !props.preview ? (inject("canvasProps") as CanvasProps) : null;
const target = computed(() => {
if (!component.value) return null;
if (component.value instanceof HTMLElement || component.value instanceof SVGElement) {
return component.value;
} else {
return component.value.component;
}
});
const styles = computed(() => {
let dynamicStyles = {};
if (props.data) {
if (props.block.getDataKey("type") === "style") {
dynamicStyles = {
[props.block.getDataKey("property") as string]: getDataForKey(
props.data,
props.block.getDataKey("key"),
),
};
}
}
return {
...props.block.getStyles(props.breakpoint),
...props.block.getEditorStyles(),
...dynamicStyles,
} as BlockStyleMap;
});
const loadEditor = computed(() => {
return (
target.value &&
props.block.getStyle("display") !== "none" &&
((isSelected.value && props.breakpoint === store.activeBreakpoint) ||
(isHovered.value && store.hoveredBreakpoint === props.breakpoint)) &&
!canvasProps?.scaling &&
!canvasProps?.panning
);
});
const emit = defineEmits(["mounted"]);
watchEffect(() => {
setFont(props.block.getStyle("fontFamily") as string, props.block.getStyle("fontWeight") as string);
});
onMounted(async () => {
await nextTick();
emit("mounted", target.value);
if (draggable.value) {
useDraggableBlock(
props.block,
component.value as HTMLElement,
reactive({ ghostScale: canvasProps?.scale || 1 }),
);
}
});
const isEditable = computed(() => {
// to ensure it is right block and not on different breakpoint
return store.editableBlock === props.block && store.activeBreakpoint === props.breakpoint;
});
const selectBlock = (e: MouseEvent | null) => {
if (store.editableBlock === props.block || store.mode !== "select" || props.preview) {
return;
}
store.selectBlock(props.block, e);
store.activeBreakpoint = props.breakpoint;
if (!props.preview) {
store.leftPanelActiveTab = "Layers";
store.rightPanelActiveTab = "Properties";
}
};
const triggerContextMenu = (e: MouseEvent) => {
if (props.block.isRoot() || isEditable.value) return;
e.stopPropagation();
e.preventDefault();
selectBlock(e);
nextTick(() => {
editor.value?.element.dispatchEvent(new MouseEvent("contextmenu", e));
});
};
const handleClick = (e: MouseEvent) => {
if (isEditable.value) return;
selectBlock(e);
e.stopPropagation();
e.preventDefault();
};
const handleDoubleClick = (e: MouseEvent) => {
if (isEditable.value) return;
store.editableBlock = null;
if (props.block.isText() || props.block.isLink() || props.block.isButton()) {
store.editableBlock = props.block;
e.stopPropagation();
}
// dblclick on container adds text block or selects text block if only one child
let children = props.block.getChildren();
if (props.block.isHTML()) {
editor.value?.element.dispatchEvent(new MouseEvent("dblclick", e));
e.stopPropagation();
} else if (props.block.isContainer()) {
if (!children.length) {
const child = getBlockTemplate("text");
props.block.setBaseStyle("alignItems", "center");
props.block.setBaseStyle("justifyContent", "center");
const childBlock = props.block.addChild(child);
childBlock.makeBlockEditable();
} else if (children.length === 1 && children[0].isText()) {
const child = children[0];
child.makeBlockEditable();
}
e.stopPropagation();
}
};
const handleMouseOver = (e: MouseEvent) => {
if (store.mode === "move") return;
store.hoveredBlock = props.block.blockId;
store.hoveredBreakpoint = props.breakpoint;
e.stopPropagation();
};
const handleMouseLeave = (e: MouseEvent) => {
if (store.mode === "move") return;
if (store.hoveredBlock === props.block.blockId) {
store.hoveredBlock = null;
e.stopPropagation();
}
};
const showBlock = computed(() => {
// const data = props.block.getVisibilityCondition()
// ? getDataForKey(props.data, props.block.getVisibilityCondition() as string)
// : true;
return true;
});
if (!props.preview) {
watch(
() => store.hoveredBlock,
(newValue, oldValue) => {
if (newValue === props.block.blockId) {
isHovered.value = true;
} else if (oldValue === props.block.blockId) {
isHovered.value = false;
}
},
);
watch(
() => store.activeCanvas?.selectedBlockIds,
() => {
if (store.activeCanvas?.isSelected(props.block)) {
isSelected.value = true;
} else {
isSelected.value = false;
}
},
{
deep: true,
immediate: true,
},
);
}
</script>
|
2302_79757062/builder
|
frontend/src/components/BuilderBlock.vue
|
Vue
|
agpl-3.0
| 7,960
|
<template>
<div ref="canvasContainer" @click="handleClick">
<slot name="header"></slot>
<div class="overlay absolute" id="overlay" ref="overlay" />
<Transition name="fade">
<div
class="absolute bottom-0 left-0 right-0 top-0 z-40 w-full bg-gray-200 p-10 dark:bg-zinc-800"
v-show="store.settingPage"></div>
</Transition>
<BlockSnapGuides></BlockSnapGuides>
<div
v-if="isOverDropZone"
class="pointer-events-none absolute bottom-0 left-0 right-0 top-0 z-30 bg-cyan-300 opacity-20"></div>
<div
class="fixed flex gap-40"
ref="canvas"
:style="{
transformOrigin: 'top center',
transform: `scale(${canvasProps.scale}) translate(${canvasProps.translateX}px, ${canvasProps.translateY}px)`,
}">
<div class="absolute right-0 top-[-60px] flex rounded-md bg-white px-3 dark:bg-zinc-900">
<div
v-show="!canvasProps.scaling && !canvasProps.panning"
class="w-auto cursor-pointer p-2"
v-for="breakpoint in canvasProps.breakpoints"
:key="breakpoint.device"
@click.stop="breakpoint.visible = !breakpoint.visible">
<FeatherIcon
:name="breakpoint.icon"
class="h-8 w-6"
:class="{
'text-gray-700 dark:text-zinc-50': breakpoint.visible,
'text-gray-300 dark:text-zinc-500': !breakpoint.visible,
}" />
</div>
</div>
<div
class="canvas relative flex h-full rounded-md bg-white shadow-2xl"
:style="{
...canvasStyles,
background: canvasProps.background,
width: `${breakpoint.width}px`,
}"
v-for="breakpoint in visibleBreakpoints"
:key="breakpoint.device">
<div
class="cursor absolute left-0 select-none text-3xl text-gray-700 dark:text-zinc-300"
:style="{
fontSize: `calc(${12}px * 1/${canvasProps.scale})`,
top: `calc(${-20}px * 1/${canvasProps.scale})`,
}"
v-show="!canvasProps.scaling && !canvasProps.panning"
@click="store.activeBreakpoint = breakpoint.device">
{{ breakpoint.displayName }}
</div>
<BuilderBlock
class="h-full min-h-[inherit]"
:block="block"
:key="block.blockId"
v-if="showBlocks"
:breakpoint="breakpoint.device"
:data="store.pageData" />
</div>
</div>
<div
class="fixed bottom-12 left-[50%] z-40 flex translate-x-[-50%] cursor-default items-center justify-center gap-2 rounded-lg bg-white px-3 py-2 text-center text-sm font-semibold text-gray-600 shadow-md dark:bg-zinc-900 dark:text-zinc-400"
v-show="!canvasProps.panning">
{{ Math.round(canvasProps.scale * 100) + "%" }}
<div class="ml-2 cursor-pointer" @click="setScaleAndTranslate">
<FitScreenIcon />
</div>
</div>
</div>
</template>
<script setup lang="ts">
import builderBlockTemplate from "@/data/builderBlockTemplate";
import webComponent from "@/data/webComponent";
import { posthog } from "@/telemetry";
import Block from "@/utils/block";
import getBlockTemplate from "@/utils/blockTemplate";
import {
addPxToNumber,
getBlockCopy,
getBlockInstance,
getBlockObject,
getNumberFromPx,
isCtrlOrCmd,
isTargetEditable,
} from "@/utils/helpers";
import {
UseRefHistoryReturn,
clamp,
useDebouncedRefHistory,
useDropZone,
useElementBounding,
useEventListener,
} from "@vueuse/core";
import { FeatherIcon } from "frappe-ui";
import { Ref, computed, nextTick, onMounted, provide, reactive, ref, watch } from "vue";
import { toast } from "vue-sonner";
import useStore from "../store";
import setPanAndZoom from "../utils/panAndZoom";
import BlockSnapGuides from "./BlockSnapGuides.vue";
import BuilderBlock from "./BuilderBlock.vue";
import FitScreenIcon from "./Icons/FitScreen.vue";
const store = useStore();
const canvasContainer = ref(null);
const canvas = ref(null);
const showBlocks = ref(false);
const overlay = ref(null);
const isDirty = ref(false);
let selectionTrail = [] as string[];
const props = defineProps({
blockData: {
type: Block,
default: false,
},
canvasStyles: {
type: Object,
default: () => ({}),
},
});
// clone props.block into canvas data to avoid mutating them
const block = ref(getBlockCopy(props.blockData, true)) as Ref<Block>;
const canvasProps = reactive({
overlayElement: null,
background: "#fff",
scale: 1,
translateX: 0,
translateY: 0,
settingCanvas: true,
scaling: false,
panning: false,
breakpoints: [
{
icon: "monitor",
device: "desktop",
displayName: "Desktop",
width: 1400,
visible: true,
},
{
icon: "tablet",
device: "tablet",
displayName: "Tablet",
width: 800,
visible: false,
},
{
icon: "smartphone",
device: "mobile",
displayName: "Mobile",
width: 420,
visible: false,
},
],
});
const canvasHistory = ref(null) as Ref<UseRefHistoryReturn<{}, {}>> | Ref<null>;
provide("canvasProps", canvasProps);
onMounted(() => {
canvasProps.overlayElement = overlay.value;
setupHistory();
setEvents();
});
function setupHistory() {
canvasHistory.value = useDebouncedRefHistory(block, {
capacity: 50,
deep: true,
debounce: 200,
dump: (obj) => {
return getBlockObject(obj);
},
parse: (obj) => {
return getBlockInstance(obj);
},
});
}
const { isOverDropZone } = useDropZone(canvasContainer, {
onDrop: (files, ev) => {
let element = document.elementFromPoint(ev.x, ev.y) as HTMLElement;
let parentBlock = block.value as Block | null;
if (element) {
if (element.dataset.blockId) {
parentBlock = findBlock(element.dataset.blockId) || parentBlock;
}
}
const componentName = ev.dataTransfer?.getData("componentName");
const blockTemplate = ev.dataTransfer?.getData("blockTemplate");
if (componentName) {
const newBlock = getBlockInstance(webComponent.getRow(componentName).block);
newBlock.extendFromComponent(componentName);
// if shift key is pressed, replace parent block with new block
if (ev.shiftKey) {
while (parentBlock && parentBlock.isChildOfComponent) {
parentBlock = parentBlock.getParentBlock();
}
if (!parentBlock) return;
const parentParentBlock = parentBlock.getParentBlock();
if (!parentParentBlock) return;
const index = parentParentBlock.children.indexOf(parentBlock);
parentParentBlock.children.splice(index, 1, newBlock);
} else {
while (parentBlock && !parentBlock.canHaveChildren()) {
parentBlock = parentBlock.getParentBlock();
}
if (!parentBlock) return;
parentBlock.addChild(newBlock);
}
ev.stopPropagation();
posthog.capture("builder_component_used");
} else if (blockTemplate) {
const templateDoc = builderBlockTemplate.getRow(blockTemplate);
const newBlock = getBlockInstance(templateDoc.block, false);
// if shift key is pressed, replace parent block with new block
if (ev.shiftKey) {
while (parentBlock && parentBlock.isChildOfComponent) {
parentBlock = parentBlock.getParentBlock();
}
if (!parentBlock) return;
const parentParentBlock = parentBlock.getParentBlock();
if (!parentParentBlock) return;
const index = parentParentBlock.children.indexOf(parentBlock);
parentParentBlock.children.splice(index, 1, newBlock);
} else {
while (parentBlock && !parentBlock.canHaveChildren()) {
parentBlock = parentBlock.getParentBlock();
}
if (!parentBlock) return;
parentBlock.addChild(newBlock);
}
posthog.capture("builder_block_template_used", { template: blockTemplate });
} else if (files && files.length) {
store.uploadFile(files[0]).then((fileDoc: { fileURL: string; fileName: string }) => {
if (!parentBlock) return;
if (fileDoc.fileName.match(/\.(mp4|webm|ogg|mov)$/)) {
if (parentBlock.isVideo()) {
parentBlock.setAttribute("src", fileDoc.fileURL);
} else {
while (parentBlock && !parentBlock.canHaveChildren()) {
parentBlock = parentBlock.getParentBlock() as Block;
}
parentBlock.addChild(store.getVideoBlock(fileDoc.fileURL));
}
posthog.capture("builder_video_uploaded");
return;
}
if (parentBlock.isImage()) {
parentBlock.setAttribute("src", fileDoc.fileURL);
posthog.capture("builder_image_uploaded", {
type: "image-replace",
});
} else if (parentBlock.isSVG()) {
const imageBlock = store.getImageBlock(fileDoc.fileURL, fileDoc.fileName);
const parentParentBlock = parentBlock.getParentBlock();
parentParentBlock?.replaceChild(parentBlock, getBlockInstance(imageBlock));
posthog.capture("builder_image_uploaded", {
type: "svg-replace",
});
} else if (parentBlock.isContainer() && ev.shiftKey) {
parentBlock.setStyle("background", `url(${fileDoc.fileURL})`);
posthog.capture("builder_image_uploaded", {
type: "background",
});
} else {
while (parentBlock && !parentBlock.canHaveChildren()) {
parentBlock = parentBlock.getParentBlock() as Block;
}
parentBlock.addChild(store.getImageBlock(fileDoc.fileURL, fileDoc.fileName));
posthog.capture("builder_image_uploaded", {
type: "new-image",
});
}
});
}
},
});
const visibleBreakpoints = computed(() => {
return canvasProps.breakpoints.filter(
(breakpoint) => breakpoint.visible || breakpoint.device === "desktop",
);
});
function setEvents() {
const container = document.body.querySelector(".canvas-container") as HTMLElement;
let counter = 0;
useEventListener(container, "mousedown", (ev: MouseEvent) => {
if (store.mode === "move") {
return;
}
const initialX = ev.clientX;
const initialY = ev.clientY;
if (store.mode === "select") {
return;
} else {
canvasHistory.value?.pause();
ev.stopPropagation();
let element = document.elementFromPoint(ev.x, ev.y) as HTMLElement;
let block = getFirstBlock();
if (element) {
if (element.dataset.blockId) {
block = findBlock(element.dataset.blockId) || block;
}
}
let parentBlock = getFirstBlock();
if (element.dataset.blockId) {
parentBlock = findBlock(element.dataset.blockId) || parentBlock;
while (parentBlock && !parentBlock.canHaveChildren()) {
parentBlock = parentBlock.getParentBlock() || getFirstBlock();
}
}
const child = getBlockTemplate(store.mode);
const parentElement = document.body.querySelector(
`.canvas [data-block-id="${parentBlock.blockId}"]`,
) as HTMLElement;
const parentOldPosition = parentBlock.getStyle("position");
if (parentOldPosition === "static" || parentOldPosition === "inherit" || !parentOldPosition) {
parentBlock.setBaseStyle("position", "relative");
}
const parentElementBounds = parentElement.getBoundingClientRect();
let x = (ev.x - parentElementBounds.left) / canvasProps.scale;
let y = (ev.y - parentElementBounds.top) / canvasProps.scale;
const parentWidth = getNumberFromPx(getComputedStyle(parentElement).width);
const parentHeight = getNumberFromPx(getComputedStyle(parentElement).height);
const childBlock = parentBlock.addChild(child);
childBlock.setBaseStyle("position", "absolute");
childBlock.setBaseStyle("top", addPxToNumber(y));
childBlock.setBaseStyle("left", addPxToNumber(x));
if (store.mode === "container" || store.mode === "repeater") {
const colors = ["#ededed", "#e2e2e2", "#c7c7c7"];
childBlock.setBaseStyle("background", colors[counter % colors.length]);
counter++;
}
const mouseMoveHandler = (mouseMoveEvent: MouseEvent) => {
if (store.mode === "text") {
return;
} else {
mouseMoveEvent.preventDefault();
let width = (mouseMoveEvent.clientX - initialX) / canvasProps.scale;
let height = (mouseMoveEvent.clientY - initialY) / canvasProps.scale;
width = clamp(width, 0, parentWidth);
height = clamp(height, 0, parentHeight);
const setFullWidth = width === parentWidth;
childBlock.setBaseStyle("width", setFullWidth ? "100%" : addPxToNumber(width));
childBlock.setBaseStyle("height", addPxToNumber(height));
}
};
useEventListener(document, "mousemove", mouseMoveHandler);
useEventListener(
document,
"mouseup",
() => {
document.removeEventListener("mousemove", mouseMoveHandler);
parentBlock.setBaseStyle("position", parentOldPosition || "static");
childBlock.setBaseStyle("position", "static");
childBlock.setBaseStyle("top", "auto");
childBlock.setBaseStyle("left", "auto");
setTimeout(() => {
store.mode = "select";
}, 50);
if (store.mode === "text") {
canvasHistory.value?.resume(true);
store.editableBlock = childBlock;
return;
}
if (parentBlock.isGrid()) {
childBlock.setStyle("width", "auto");
childBlock.setStyle("height", "100%");
} else {
if (getNumberFromPx(childBlock.getStyle("width")) < 100) {
childBlock.setBaseStyle("width", "100%");
}
if (getNumberFromPx(childBlock.getStyle("height")) < 100) {
childBlock.setBaseStyle("height", "200px");
}
}
canvasHistory.value?.resume(true);
},
{ once: true },
);
}
});
useEventListener(container, "mousedown", (ev: MouseEvent) => {
if (store.mode === "move") {
container.style.cursor = "grabbing";
const initialX = ev.clientX;
const initialY = ev.clientY;
const initialTranslateX = canvasProps.translateX;
const initialTranslateY = canvasProps.translateY;
const mouseMoveHandler = (mouseMoveEvent: MouseEvent) => {
mouseMoveEvent.preventDefault();
const diffX = (mouseMoveEvent.clientX - initialX) / canvasProps.scale;
const diffY = (mouseMoveEvent.clientY - initialY) / canvasProps.scale;
canvasProps.translateX = initialTranslateX + diffX;
canvasProps.translateY = initialTranslateY + diffY;
};
useEventListener(document, "mousemove", mouseMoveHandler);
useEventListener(
document,
"mouseup",
() => {
document.removeEventListener("mousemove", mouseMoveHandler);
container.style.cursor = "grab";
},
{ once: true },
);
ev.stopPropagation();
ev.preventDefault();
}
});
useEventListener(document, "keydown", (ev: KeyboardEvent) => {
if (isTargetEditable(ev)) {
return;
}
if (ev.shiftKey && ev.key === "ArrowLeft") {
if (isCtrlOrCmd(ev)) {
if (selectedBlocks.value.length) {
const selectedBlock = selectedBlocks.value[0];
store.activeLayers?.toggleExpanded(selectedBlock);
return;
}
}
if (selectedBlocks.value.length) {
const selectedBlock = selectedBlocks.value[0];
const parentBlock = selectedBlock.getParentBlock();
if (parentBlock) {
selectionTrail.push(selectedBlock.blockId);
maintainTrail = true;
store.selectBlock(parentBlock, null, true, true);
maintainTrail = false;
}
}
}
if (ev.shiftKey && ev.key === "ArrowRight") {
const blockId = selectionTrail.pop();
if (blockId) {
const block = findBlock(blockId);
if (block) {
maintainTrail = true;
store.selectBlock(block, null, true, true);
maintainTrail = false;
}
} else {
if (selectedBlocks.value.length) {
const selectedBlock = selectedBlocks.value[0];
if (selectedBlock.children && selectedBlock.isVisible()) {
let child = selectedBlock.children[0];
while (child && !child.isVisible()) {
child = child.getSiblingBlock("next") as Block;
if (!child) {
break;
}
}
child && store.selectBlock(child, null, true, true);
}
}
}
}
if (ev.shiftKey && ev.key === "ArrowUp") {
if (selectedBlocks.value.length) {
let sibling = selectedBlocks.value[0].getSiblingBlock("previous");
if (sibling) {
store.selectBlock(sibling, null, true, true);
}
}
}
if (ev.shiftKey && ev.key === "ArrowDown") {
if (selectedBlocks.value.length) {
let sibling = selectedBlocks.value[0].getSiblingBlock("next");
if (sibling) {
store.selectBlock(sibling, null, true, true);
}
}
}
});
}
const containerBound = reactive(useElementBounding(canvasContainer));
const canvasBound = reactive(useElementBounding(canvas));
const setScaleAndTranslate = async () => {
if (document.readyState !== "complete") {
await new Promise((resolve) => {
window.addEventListener("load", resolve);
});
}
const paddingX = 300;
const paddingY = 200;
await nextTick();
canvasBound.update();
const containerWidth = containerBound.width;
const canvasWidth = canvasBound.width / canvasProps.scale;
canvasProps.scale = containerWidth / (canvasWidth + paddingX * 2);
canvasProps.translateX = 0;
canvasProps.translateY = 0;
await nextTick();
const scale = canvasProps.scale;
canvasBound.update();
const diffY = containerBound.top - canvasBound.top + paddingY * scale;
if (diffY !== 0) {
canvasProps.translateY = diffY / scale;
}
canvasProps.settingCanvas = false;
};
onMounted(() => {
setScaleAndTranslate();
const canvasContainerEl = canvasContainer.value as unknown as HTMLElement;
const canvasEl = canvas.value as unknown as HTMLElement;
setPanAndZoom(canvasProps, canvasEl, canvasContainerEl);
showBlocks.value = true;
});
const resetZoom = () => {
canvasProps.scale = 1;
canvasProps.translateX = 0;
canvasProps.translateY = 0;
};
const moveCanvas = (direction: "up" | "down" | "right" | "left") => {
if (direction === "up") {
canvasProps.translateY -= 20;
} else if (direction === "down") {
canvasProps.translateY += 20;
} else if (direction === "right") {
canvasProps.translateX += 20;
} else if (direction === "left") {
canvasProps.translateX -= 20;
}
};
const zoomIn = () => {
canvasProps.scale = Math.min(canvasProps.scale + 0.1, 10);
};
const zoomOut = () => {
canvasProps.scale = Math.max(canvasProps.scale - 0.1, 0.1);
};
watch(
() => canvasProps.breakpoints.map((b) => b.visible),
() => {
if (canvasProps.settingCanvas) {
return;
}
setScaleAndTranslate();
},
);
watch(
() => store.mode,
(newValue, oldValue) => {
store.lastMode = oldValue;
toggleMode(store.mode);
},
);
function toggleMode(mode: BuilderMode) {
if (!canvasContainer.value) return;
const container = canvasContainer.value as HTMLElement;
if (mode === "text") {
container.style.cursor = "text";
} else if (["container", "image", "repeater"].includes(mode)) {
container.style.cursor = "crosshair";
} else if (mode === "move") {
container.style.cursor = "grab";
} else {
container.style.cursor = "default";
}
}
const handleClick = (ev: MouseEvent) => {
const target = document.elementFromPoint(ev.clientX, ev.clientY);
// hack to ensure if click is on canvas-container
// TODO: Still clears selection if space handlers are dragged over canvas-container
if (target?.classList.contains("canvas-container")) {
clearSelection();
}
};
const clearCanvas = () => {
block.value = store.getRootBlock();
};
const getFirstBlock = () => {
return block.value;
};
const setRootBlock = (newBlock: Block, resetCanvas = false) => {
block.value = newBlock;
if (canvasHistory.value) {
canvasHistory.value.dispose();
setupHistory();
}
if (resetCanvas) {
nextTick(() => {
setScaleAndTranslate();
toggleDirty(false);
});
}
};
const selectedBlockIds = ref([]) as Ref<string[]>;
const selectedBlocks = computed(() => {
return selectedBlockIds.value.map((id) => findBlock(id)).filter((b) => b) as Block[];
}) as Ref<Block[]>;
const isSelected = (block: Block) => {
return selectedBlockIds.value.includes(block.blockId);
};
let maintainTrail = false;
const selectBlock = (_block: Block, multiSelect = false) => {
if (multiSelect) {
selectedBlockIds.value.push(_block.blockId);
} else {
selectedBlockIds.value.splice(0, selectedBlockIds.value.length, _block.blockId);
}
if (!maintainTrail) {
selectionTrail = [];
}
};
const toggleBlockSelection = (_block: Block) => {
if (isSelected(_block)) {
selectedBlockIds.value.splice(selectedBlockIds.value.indexOf(_block.blockId), 1);
} else {
selectBlock(_block, true);
}
};
const selectBlockRange = (newSelectedBlock: Block) => {
const lastSelectedBlockId = selectedBlockIds.value[selectedBlockIds.value.length - 1];
const lastSelectedBlock = findBlock(lastSelectedBlockId);
const lastSelectedBlockParent = lastSelectedBlock?.parentBlock;
if (!lastSelectedBlock || !lastSelectedBlockParent) {
newSelectedBlock.selectBlock();
return;
}
const lastSelectedBlockIndex = lastSelectedBlock.parentBlock?.children.indexOf(lastSelectedBlock);
const newSelectedBlockIndex = newSelectedBlock.parentBlock?.children.indexOf(newSelectedBlock);
const newSelectedBlockParent = newSelectedBlock.parentBlock;
if (lastSelectedBlockIndex === undefined || newSelectedBlockIndex === undefined) {
return;
}
const start = Math.min(lastSelectedBlockIndex, newSelectedBlockIndex);
const end = Math.max(lastSelectedBlockIndex, newSelectedBlockIndex);
if (lastSelectedBlockParent === newSelectedBlockParent) {
const blocks = lastSelectedBlockParent.children.slice(start, end + 1);
selectedBlockIds.value = selectedBlockIds.value.concat(...blocks.map((b) => b.blockId));
selectedBlockIds.value = Array.from(new Set(selectedBlockIds.value));
}
};
const clearSelection = () => {
selectedBlockIds.value = [];
};
const findBlock = (blockId: string, blocks?: Block[]): Block | null => {
if (!blocks) {
blocks = [getFirstBlock()];
}
for (const block of blocks) {
if (block.blockId === blockId) {
return block;
}
if (block.children) {
const found = findBlock(blockId, block.children);
if (found) {
return found;
}
}
}
return null;
};
const removeBlock = (block: Block) => {
if (block.blockId === "root") {
toast.warning("Warning", {
description: "Cannot delete root block",
});
return;
}
if (block.isChildOfComponentBlock()) {
toast.warning("Warning", {
description: "Cannot delete block inside component",
});
return;
}
const parentBlock = block.parentBlock;
if (!parentBlock) {
return;
}
const index = parentBlock.children.indexOf(block);
parentBlock.removeChild(block);
nextTick(() => {
if (parentBlock.children.length) {
const nextSibling = parentBlock.children[index] || parentBlock.children[index - 1];
if (nextSibling) {
selectBlock(nextSibling);
}
}
});
};
watch(
() => block,
() => {
toggleDirty(true);
},
{
deep: true,
},
);
const toggleDirty = (dirty: boolean | null = null) => {
if (dirty === null) {
isDirty.value = !isDirty.value;
} else {
isDirty.value = dirty;
}
};
const scrollBlockIntoView = async (blockToFocus: Block) => {
// wait for editor to render
await new Promise((resolve) => setTimeout(resolve, 100));
await nextTick();
if (
!canvasContainer.value ||
!canvas.value ||
blockToFocus.isRoot() ||
!blockToFocus.isVisible() ||
blockToFocus.getParentBlock()?.isSVG()
) {
return;
}
const container = canvasContainer.value as HTMLElement;
const containerRect = container.getBoundingClientRect();
const selectedBlock = document.body.querySelector(
`.editor[data-block-id="${blockToFocus.blockId}"][selected=true]`,
) as HTMLElement;
if (!selectedBlock) {
return;
}
const blockRect = reactive(useElementBounding(selectedBlock));
// check if block is in view
if (
blockRect.top >= containerRect.top &&
blockRect.bottom <= containerRect.bottom &&
blockRect.left >= containerRect.left &&
blockRect.right <= containerRect.right
) {
return;
}
let padding = 80;
let paddingBottom = 200;
const blockWidth = blockRect.width + padding * 2;
const containerBound = container.getBoundingClientRect();
const blockHeight = blockRect.height + padding + paddingBottom;
const scaleX = containerBound.width / blockWidth;
const scaleY = containerBound.height / blockHeight;
const newScale = Math.min(scaleX, scaleY);
const scaleDiff = canvasProps.scale - canvasProps.scale * newScale;
if (scaleDiff > 0.2) {
return;
}
if (newScale < 1) {
canvasProps.scale = canvasProps.scale * newScale;
await new Promise((resolve) => setTimeout(resolve, 100));
await nextTick();
blockRect.update();
}
padding = padding * canvasProps.scale;
paddingBottom = paddingBottom * canvasProps.scale;
// slide in block from the closest edge of the container
const diffTop = containerRect.top - blockRect.top + padding;
const diffBottom = blockRect.bottom - containerRect.bottom + paddingBottom;
const diffLeft = containerRect.left - blockRect.left + padding;
const diffRight = blockRect.right - containerRect.right + padding;
if (diffTop > 0) {
canvasProps.translateY += diffTop / canvasProps.scale;
} else if (diffBottom > 0) {
canvasProps.translateY -= diffBottom / canvasProps.scale;
}
if (diffLeft > 0) {
canvasProps.translateX += diffLeft / canvasProps.scale;
} else if (diffRight > 0) {
canvasProps.translateX -= diffRight / canvasProps.scale;
}
};
defineExpose({
setScaleAndTranslate,
resetZoom,
moveCanvas,
zoomIn,
zoomOut,
history: canvasHistory as Ref<UseRefHistoryReturn<{}, {}>>,
clearCanvas,
getFirstBlock,
block,
setRootBlock,
canvasProps,
selectBlock,
toggleBlockSelection,
selectedBlocks,
clearSelection,
isSelected,
selectedBlockIds,
findBlock,
isDirty,
toggleDirty,
scrollBlockIntoView,
removeBlock,
selectBlockRange,
});
</script>
|
2302_79757062/builder
|
frontend/src/components/BuilderCanvas.vue
|
Vue
|
agpl-3.0
| 25,107
|
<template>
<div
:style="{
width: `${store.builderLayout.leftPanelWidth}px`,
}">
<div
class="relative min-h-full"
@click.stop="store.leftPanelActiveTab === 'Layers' && store.activeCanvas?.clearSelection()">
<PanelResizer
:dimension="store.builderLayout.leftPanelWidth"
side="right"
:maxDimension="500"
@resize="(width) => (store.builderLayout.leftPanelWidth = width)" />
<div v-if="false" class="mb-5 flex flex-col overflow-hidden rounded-lg text-sm">
<textarea
class="no-scrollbar h-fit resize-none rounded-sm border-0 bg-gray-300 text-sm outline-none dark:bg-zinc-700 dark:text-white"
v-model="prompt"
:disabled="generating" />
<button
@click="getPage"
type="button"
class="bg-gray-300 p-2 text-gray-800 dark:bg-zinc-700 dark:text-zinc-300"
:disabled="generating">
Generate
</button>
</div>
<div class="flex w-full border-gray-200 px-2 text-base dark:border-zinc-800">
<button
v-for="tab of ['Layers', 'Assets'] as LeftSidebarTabOption[]"
:key="tab"
class="mx-3 flex-1 p-2 py-3"
@click.stop="setActiveTab(tab as LeftSidebarTabOption)"
:class="{
'border-b-[1px] border-gray-900 dark:border-zinc-500 dark:text-zinc-300':
store.leftPanelActiveTab === tab,
'text-gray-700 dark:text-zinc-500': store.leftPanelActiveTab !== tab,
}">
{{ tab }}
</button>
</div>
<div v-show="store.leftPanelActiveTab === 'Assets'">
<BuilderAssets class="mt-1 p-4 pt-3" />
</div>
<div v-show="store.leftPanelActiveTab === 'Layers'" class="p-4 pt-3">
<BlockLayers
class="no-scrollbar overflow-auto"
v-if="pageCanvas"
ref="pageLayers"
:blocks="[pageCanvas?.getFirstBlock() as Block]"
v-show="store.editingMode == 'page'" />
<BlockLayers
class="no-scrollbar overflow-auto"
ref="componentLayers"
:blocks="[fragmentCanvas?.getFirstBlock()]"
v-if="store.editingMode === 'fragment' && fragmentCanvas" />
</div>
</div>
</div>
</template>
<script setup lang="ts">
import convertHTMLToBlocks from "@/utils/convertHTMLToBlocks";
import { createResource } from "frappe-ui";
import { Ref, inject, ref, watch, watchEffect } from "vue";
import useStore from "../store";
import BlockLayers from "./BlockLayers.vue";
import BuilderAssets from "./BuilderAssets.vue";
import PanelResizer from "./PanelResizer.vue";
import Block from "@/utils/block";
import BuilderCanvas from "./BuilderCanvas.vue";
const pageCanvas = inject("pageCanvas") as Ref<InstanceType<typeof BuilderCanvas> | null>;
const fragmentCanvas = inject("fragmentCanvas") as Ref<InstanceType<typeof BuilderCanvas> | null>;
const prompt = ref(null) as unknown as Ref<string>;
const store = useStore();
const generating = ref(false);
const pageLayers = ref<InstanceType<typeof BlockLayers> | null>(null);
const componentLayers = ref<InstanceType<typeof BlockLayers> | null>(null);
watchEffect(() => {
if (pageLayers.value) {
store.activeLayers = pageLayers.value;
} else if (componentLayers.value) {
store.activeLayers = componentLayers.value;
}
});
const getPage = () => {
generating.value = true;
createResource({
url: "builder.api.get_blocks",
onSuccess(html: string) {
store.clearBlocks();
const blocks = convertHTMLToBlocks(html);
store.pushBlocks([blocks]);
generating.value = false;
},
}).submit({
prompt: prompt.value,
});
};
const setActiveTab = (tab: LeftSidebarTabOption) => {
store.leftPanelActiveTab = tab;
};
// moved out of BlockLayers for performance
// TODO: Find a better way to do this
watch(
() => store.hoveredBlock,
() => {
document.querySelectorAll(`[data-block-layer-id].hovered-block`).forEach((el) => {
el.classList.remove("hovered-block");
});
if (store.hoveredBlock) {
document.querySelector(`[data-block-layer-id="${store.hoveredBlock}"]`)?.classList.add("hovered-block");
}
},
);
watch(
() => store.activeCanvas?.selectedBlocks,
() => {
document.querySelectorAll(`[data-block-layer-id].block-selected`).forEach((el) => {
el.classList.remove("block-selected");
});
if (store.activeCanvas?.selectedBlocks.length) {
store.activeCanvas?.selectedBlocks.forEach((block: Block) => {
document.querySelector(`[data-block-layer-id="${block.blockId}"]`)?.classList.add("block-selected");
});
}
},
);
</script>
|
2302_79757062/builder
|
frontend/src/components/BuilderLeftPanel.vue
|
Vue
|
agpl-3.0
| 4,365
|
<template>
<div
:style="{
width: `${store.builderLayout.rightPanelWidth}px`,
}">
<div class="relative min-h-full">
<PanelResizer
:dimension="store.builderLayout.rightPanelWidth"
side="left"
@resize="(width) => (store.builderLayout.rightPanelWidth = width)"
:min-dimension="275"
:max-dimension="400" />
<div
class="sticky top-0 z-[12] flex w-full border-gray-200 bg-white px-2 text-base dark:border-zinc-800 dark:bg-zinc-900">
<button
v-for="tab of ['Properties', 'Script', 'Options'] as RightSidebarTabOption[]"
:key="tab"
class="mx-2 flex-1 p-2 py-3"
@click="store.rightPanelActiveTab = tab"
:class="{
'border-b-[1px] border-gray-900 dark:border-zinc-500 dark:text-zinc-300':
store.rightPanelActiveTab === tab,
'text-gray-700 dark:text-zinc-500': store.rightPanelActiveTab !== tab,
}">
{{ tab }}
</button>
</div>
<BlockProperties v-show="store.rightPanelActiveTab === 'Properties'" class="p-4" />
<PageScript
class="p-4"
v-show="store.rightPanelActiveTab === 'Script'"
:key="store.selectedPage"
v-if="store.selectedPage && store.activePage"
:page="store.activePage" />
<PageOptions
class="p-4"
v-show="store.rightPanelActiveTab === 'Options'"
:key="store.selectedPage"
v-if="store.selectedPage && store.activePage"
:page="store.activePage" />
</div>
</div>
</template>
<script setup lang="ts">
import useStore from "@/store";
import BlockProperties from "./BlockProperties.vue";
import PageOptions from "./PageOptions.vue";
import PageScript from "./PageScript.vue";
import PanelResizer from "./PanelResizer.vue";
const store = useStore();
</script>
|
2302_79757062/builder
|
frontend/src/components/BuilderRightPanel.vue
|
Vue
|
agpl-3.0
| 1,708
|
<template>
<div
class="toolbar flex h-14 items-center justify-center bg-white p-2 shadow-sm dark:border-b-[1px] dark:border-gray-800 dark:bg-zinc-900"
ref="toolbar">
<div class="absolute left-3 flex items-center">
<router-link class="flex items-center gap-2" :to="{ name: 'home' }">
<img src="/builder_logo.png" alt="logo" class="h-7" />
<h1 class="text-md mt-[2px] font-semibold leading-5 text-gray-800 dark:text-gray-200">Builder</h1>
</router-link>
</div>
<div class="ml-10 flex gap-3">
<Tooltip
:text="mode.description"
:hoverDelay="0.6"
v-for="mode in [
{ mode: 'select', icon: 'mouse-pointer', description: 'Select (v)' },
{ mode: 'text', icon: 'type', description: 'Text (t)' },
{ mode: 'container', icon: 'square', description: 'Container (c)' },
{ mode: 'image', icon: 'image', description: 'Image (i)' },
]">
<Button
variant="ghost"
:icon="mode.icon"
class="!text-gray-700 dark:!text-gray-200 hover:dark:bg-zinc-800 focus:dark:bg-zinc-700 [&[active='true']]:bg-gray-100 [&[active='true']]:!text-gray-900 [&[active='true']]:dark:bg-zinc-700 [&[active='true']]:dark:!text-zinc-50"
@click="store.mode = mode.mode as BuilderMode"
:active="store.mode === mode.mode"></Button>
</Tooltip>
</div>
<div class="absolute right-3 flex items-center gap-5">
<Dialog
style="z-index: 40"
:options="{
title: 'Get Started',
size: '4xl',
}"
v-model="showDialog">
<template #body-content>
<iframe
class="h-[60vh] w-full rounded-sm"
src="https://www.youtube-nocookie.com/embed/videoseries?si=8NvOFXFq6ntafauO&controls=0&list=PL3lFfCEoMxvwZsBfCgk6vLKstZx204xe3"
title="Frappe Builder - Get Started"
frameborder="0"
allowfullscreen></iframe>
</template>
</Dialog>
<div class="group flex hover:gap-1" v-if="store.viewers.length">
<div v-for="user in store.viewers">
<Tooltip :text="currentlyViewedByText" :hoverDelay="0.6">
<div class="ml-[-10px] h-6 w-6 cursor-pointer transition-all group-hover:ml-0">
<img
class="h-full w-full rounded-full border-2 border-orange-400 object-cover shadow-sm"
:src="user.image"
v-if="user.image" />
<div
v-else
:title="user.fullname"
class="grid h-full w-full place-items-center rounded-full border-2 border-orange-400 bg-gray-400 text-sm text-gray-700 shadow-sm">
{{ user.fullname.charAt(0) }}
</div>
</div>
</Tooltip>
</div>
</div>
<Badge
:variant="'subtle'"
theme="gray"
size="md"
label="Badge"
class="dark:bg-zinc-600 dark:text-zinc-100"
v-if="store.isHomePage()">
Homepage
</Badge>
<span class="text-sm dark:text-zinc-300" v-if="store.savingPage && store.activePage?.is_template">
Saving template
</span>
<!-- <button @click="showDialog = true">
<FeatherIcon
name="info"
class="mr-4 h-4 w-4 cursor-pointer text-gray-600 dark:text-gray-400" />
</button> -->
<UseDark v-slot="{ isDark, toggleDark }">
<button @click="transitionTheme(toggleDark)">
<FeatherIcon
title="Toggle Theme"
:name="isDark ? 'moon' : 'sun'"
class="h-4 w-4 cursor-pointer text-gray-600 dark:text-gray-400" />
</button>
</UseDark>
<router-link
v-if="store.selectedPage"
:to="{ name: 'preview', params: { pageId: store.selectedPage } }"
title="Preview">
<FeatherIcon name="play" class="h-4 w-4 cursor-pointer text-gray-600 dark:text-gray-400" />
</router-link>
<Button
v-if="!is_developer_mode"
variant="solid"
@click="
() => {
publishing = true;
store.publishPage().finally(() => (publishing = false));
}
"
class="border-0 text-xs dark:bg-zinc-800"
:loading="publishing">
{{ publishing ? "Publishing" : "Publish" }}
</Button>
<div class="flex" v-else>
<Button
variant="solid"
:disabled="Boolean(store.activePage?.is_template)"
@click="
() => {
publishing = true;
store.publishPage().finally(() => (publishing = false));
}
"
class="rounded-br-none rounded-tr-none border-0 pr-1 text-xs dark:bg-zinc-800"
:loading="publishing">
{{ publishing ? "Publishing" : "Publish" }}
</Button>
<Dropdown
:options="[
// { label: 'Publish', onClick: () => publish() },
{ label: 'Save As Template', onClick: () => saveAsTemplate() },
]"
size="sm"
class="flex-1 [&>div>div>div]:w-full"
placement="right">
<template v-slot="{ open }">
<Button
variant="solid"
@click="open"
:disabled="Boolean(store.activePage?.is_template)"
icon="chevron-down"
class="!w-6 justify-start rounded-bl-none rounded-tl-none border-0 pr-0 text-xs dark:bg-zinc-800"></Button>
</template>
</Dropdown>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { webPages } from "@/data/webPage";
import { UseDark } from "@vueuse/components";
import { Badge, Dialog, Dropdown, Tooltip } from "frappe-ui";
import { computed, ref } from "vue";
import { toast } from "vue-sonner";
import useStore from "../store";
const store = useStore();
const publishing = ref(false);
const showDialog = ref(false);
const toolbar = ref(null);
const is_developer_mode = window.is_developer_mode;
const currentlyViewedByText = computed(() => {
const names = store.viewers.map((viewer) => viewer.fullname).map((name) => name.split(" ")[0]);
const count = names.length;
if (count === 0) {
return "";
} else if (count === 1) {
return `${names[0]}`;
} else if (count === 2) {
return `${names.join(" & ")}`;
} else {
return `${names.slice(0, 2).join(", ")} & ${count - 2} others`;
}
});
declare global {
interface Document {
startViewTransition(callback: () => void): void;
}
}
const transitionTheme = (toggleDark: () => void) => {
if (document.startViewTransition && !window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
document.startViewTransition(() => {
toggleDark();
});
} else {
toggleDark();
}
};
const saveAsTemplate = async () => {
toast.promise(
webPages.setValue.submit({
name: store.activePage?.name,
is_template: true,
}),
{
loading: "Saving as template",
success: () => {
store.fetchActivePage(store.selectedPage as string).then((page) => {
store.activePage = page;
});
return "Page saved as template";
},
},
);
};
</script>
<style>
[data-radix-popper-content-wrapper] {
margin-top: 15px !important;
z-index: 20 !important;
}
</style>
|
2302_79757062/builder
|
frontend/src/components/BuilderToolbar.vue
|
Vue
|
agpl-3.0
| 6,623
|
<template>
<div
class="editor flex flex-col"
:style="{
height: height,
}">
<span
class="flex h-8 items-center gap-2 rounded-t-sm bg-gray-50 p-3 py-2 text-xs dark:bg-zinc-800 dark:text-zinc-100"
v-if="label">
{{ label }}
</span>
<div ref="editor" class="h-auto flex-1 overscroll-none border border-gray-200 dark:border-zinc-800" />
<span
class="mt-1 text-xs leading-4 text-gray-600 dark:text-zinc-400"
v-show="description"
v-html="description"></span>
<Button
v-if="showSaveButton"
@click="emit('save', aceEditor?.getValue())"
class="mt-3 w-full text-base dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700">
Save
</Button>
</div>
</template>
<script setup lang="ts">
import { useDark } from "@vueuse/core";
import ace from "ace-builds";
import "ace-builds/src-min-noconflict/ext-searchbox";
import "ace-builds/src-min-noconflict/theme-chrome";
import "ace-builds/src-min-noconflict/theme-twilight";
import { PropType, onMounted, ref, watch } from "vue";
const isDark = useDark();
const props = defineProps({
modelValue: {
type: [Object, String, Array],
},
type: {
type: String as PropType<"JSON" | "HTML" | "Python" | "JavaScript" | "CSS">,
default: "JSON",
},
label: {
type: String,
default: "",
},
readonly: {
type: Boolean,
default: false,
},
height: {
type: String,
default: "250px",
},
showLineNumbers: {
type: Boolean,
default: false,
},
autofocus: {
type: Boolean,
default: true,
},
showSaveButton: {
type: Boolean,
default: false,
},
description: {
type: String,
default: "",
},
});
const emit = defineEmits(["save", "update:modelValue"]);
const editor = ref<HTMLElement | null>(null);
let aceEditor = null as ace.Ace.Editor | null;
onMounted(() => {
setupEditor();
});
const setupEditor = () => {
aceEditor = ace.edit(editor.value as HTMLElement);
resetEditor(props.modelValue as string, true);
aceEditor.setReadOnly(props.readonly);
aceEditor.setOptions({
fontSize: "12px",
useWorker: false,
showGutter: props.showLineNumbers,
wrap: props.showLineNumbers,
});
if (props.type === "CSS") {
import("ace-builds/src-noconflict/mode-css").then(() => {
aceEditor?.session.setMode("ace/mode/css");
});
} else if (props.type === "JavaScript") {
import("ace-builds/src-noconflict/mode-javascript").then(() => {
aceEditor?.session.setMode("ace/mode/javascript");
});
} else if (props.type === "Python") {
import("ace-builds/src-noconflict/mode-python").then(() => {
aceEditor?.session.setMode("ace/mode/python");
});
} else if (props.type === "JSON") {
import("ace-builds/src-noconflict/mode-json").then(() => {
aceEditor?.session.setMode("ace/mode/json");
});
} else {
import("ace-builds/src-noconflict/mode-html").then(() => {
aceEditor?.session.setMode("ace/mode/html");
});
}
aceEditor.on("blur", () => {
try {
let value = aceEditor?.getValue() || "";
if (props.type === "JSON") {
value = JSON.parse(value);
}
if (value === props.modelValue) return;
if (!props.showSaveButton && !props.readonly) {
emit("update:modelValue", value);
}
} catch (e) {
// do nothing
}
});
};
const getModelValue = () => {
let value = props.modelValue || "";
try {
if (props.type === "JSON" || typeof value === "object") {
value = JSON.stringify(value, null, 2);
}
} catch (e) {
// do nothing
}
return value as string;
};
function resetEditor(value: string, resetHistory = false) {
value = getModelValue();
aceEditor?.setValue(value);
aceEditor?.clearSelection();
aceEditor?.setTheme(isDark.value ? "ace/theme/twilight" : "ace/theme/chrome");
props.autofocus && aceEditor?.focus();
if (resetHistory) {
aceEditor?.session.getUndoManager().reset();
}
}
watch(isDark, () => {
aceEditor?.setTheme(isDark.value ? "ace/theme/twilight" : "ace/theme/chrome");
});
watch(
() => props.type,
() => {
setupEditor();
},
);
watch(
() => props.modelValue,
() => {
resetEditor(props.modelValue as string);
},
);
defineExpose({ resetEditor });
</script>
<style scoped>
.editor .ace_editor {
height: 100%;
width: 100%;
border-radius: 5px;
overscroll-behavior: none;
}
.editor :deep(.ace_scrollbar-h) {
display: none;
}
.editor :deep(.ace_search) {
@apply dark:bg-zinc-800 dark:text-zinc-200;
@apply dark:border-zinc-800;
}
.editor :deep(.ace_searchbtn) {
@apply dark:bg-zinc-800 dark:text-zinc-200;
@apply dark:border-zinc-800;
}
.editor :deep(.ace_button) {
@apply dark:bg-zinc-800 dark:text-zinc-200;
}
</style>
|
2302_79757062/builder
|
frontend/src/components/CodeEditor.vue
|
Vue
|
agpl-3.0
| 4,536
|
<template>
<div>
<div class="flex items-center justify-between text-sm font-medium dark:text-zinc-400">
<h3 class="cursor-pointer text-base text-gray-900 dark:text-zinc-300" @click="toggleCollapsed">
{{ sectionName }}
</h3>
<Button
class="dark:text-zinc-400 dark:hover:bg-zinc-700"
:icon="collapsed ? 'plus' : 'minus'"
:variant="'ghost'"
size="sm"
@click="toggleCollapsed"></Button>
</div>
<div v-if="!collapsed">
<div class="mb-4 mt-3 flex flex-col gap-3"><slot /></div>
</div>
</div>
</template>
<script lang="ts" setup>
import { ref, watch } from "vue";
const props = defineProps({
sectionName: {
type: String,
required: true,
},
sectionCollapsed: {
type: [Boolean, Object],
default: false,
},
});
const propCollapsed = ref(props.sectionCollapsed);
const collapsed = ref(false);
const toggleCollapsed = () => {
collapsed.value = !collapsed.value;
};
watch(
() => propCollapsed.value,
(newVal) => {
collapsed.value = newVal as boolean;
},
{ immediate: true },
);
</script>
|
2302_79757062/builder
|
frontend/src/components/CollapsibleSection.vue
|
Vue
|
agpl-3.0
| 1,044
|
<template>
<ColorPicker :modelValue="value as HashString" @update:modelValue="(color) => emit('change', color)">
<template #target="{ togglePopover, isOpen }">
<div class="flex items-center justify-between">
<InputLabel>{{ label }}</InputLabel>
<div class="relative w-full">
<div
class="absolute left-2 top-[6px] z-10 h-4 w-4 rounded shadow-sm"
@click="togglePopover"
:style="{
background: value ? value : `url(/assets/builder/images/color-circle.png) center / contain`,
}"></div>
<Input
type="text"
class="[&>div>input]:pl-8"
placeholder="Set Color"
:modelValue="value"
@update:modelValue="
(value: string | null) => {
value = getRGB(value);
emit('change', value);
}
" />
</div>
</div>
</template>
</ColorPicker>
</template>
<script setup lang="ts">
import { getRGB } from "@/utils/helpers";
import { PropType } from "vue";
import ColorPicker from "./ColorPicker.vue";
import Input from "./Input.vue";
import InputLabel from "./InputLabel.vue";
defineProps({
value: {
type: String as PropType<StyleValue | null>,
default: null,
},
label: {
type: String,
default: "",
},
});
const emit = defineEmits(["change"]);
</script>
|
2302_79757062/builder
|
frontend/src/components/ColorInput.vue
|
Vue
|
agpl-3.0
| 1,268
|
<template>
<Popover transition="default" placement="left" class="!block w-full" popoverClass="!min-w-fit !mr-[30px]">
<template #target="{ togglePopover, isOpen }">
<slot
name="target"
:togglePopover="
() => {
togglePopover();
setSelectorPosition(modelColor);
}
"
:isOpen="isOpen"></slot>
</template>
<template #body="{ close }">
<div
ref="colorPicker"
class="rounded-lg bg-white p-3 shadow-lg dark:bg-zinc-900"
v-on-click-outside="close">
<div
ref="colorMap"
:style="{
background: `
linear-gradient(0deg, black, transparent),
linear-gradient(90deg, white, transparent),
hsl(${hue}, 100%, 50%)
`,
}"
@mousedown.stop="handleSelectorMove"
class="relative m-auto h-24 w-44 rounded-md"
@click.prevent="setColor">
<div
ref="colorSelector"
@mousedown.stop="handleSelectorMove"
class="absolute rounded-full border border-black border-opacity-20 before:absolute before:h-full before:w-full before:rounded-full before:border-2 before:border-white before:bg-[currentColor] after:absolute after:left-[2px] after:top-[2px] after:h-[calc(100%-4px)] after:w-[calc(100%-4px)] after:rounded-full after:border after:border-black after:border-opacity-20 after:bg-transparent"
:style="
{
height: '12px',
width: '12px',
left: `calc(${colorSelectorPosition.x}px - 6px)`,
top: `calc(${colorSelectorPosition.y}px - 6px)`,
color: modelColor || '#FFF',
background: 'transparent',
} as StyleValue
"></div>
</div>
<div
ref="hueMap"
class="relative m-auto mt-2 h-3 w-44 rounded-md"
@click="setHue"
@mousedown="handleHueSelectorMove"
:style="{
background: `
linear-gradient(90deg, hsl(0, 100%, 50%),
hsl(60, 100%, 50%), hsl(120, 100%, 50%),
hsl(180, 100%, 50%), hsl(240, 100%, 50%),
hsl(300, 100%, 50%), hsl(360, 100%, 50%))
`,
}">
<div
ref="hueSelector"
@mousedown="handleHueSelectorMove"
class="absolute rounded-full border border-[rgba(0,0,0,.2)] before:absolute before:h-full before:w-full before:rounded-full before:border-2 before:border-white before:bg-[currentColor] after:absolute after:left-[2px] after:top-[2px] after:h-[calc(100%-4px)] after:w-[calc(100%-4px)] after:rounded-full after:border after:border-[rgba(0,0,0,.2)] after:bg-transparent"
:style="{
height: '12px',
width: '12px',
left: `calc(${hueSelectorPosition.x}px - 6px)`,
color: `hsl(${hue}, 100%, 50%)`,
background: 'transparent',
}"></div>
</div>
<div ref="colorPalette">
<div class="mt-3 flex flex-wrap gap-1.5">
<div
v-for="color in colors"
:key="color"
class="h-3.5 w-3.5 cursor-pointer rounded-full shadow-sm"
@click="
() => {
setSelectorPosition(color);
updateColor();
}
"
:style="{
background: color,
}"></div>
<EyeDropperIcon
v-if="isSupported"
class="text-gray-700 dark:text-zinc-300"
@click="() => open()" />
</div>
</div>
</div>
</template>
</Popover>
</template>
<script setup lang="ts">
import useStore from "@/store";
import { HSVToHex, HexToHSV, getRGB } from "@/utils/helpers";
import { vOnClickOutside } from "@vueuse/components";
import { clamp, useEyeDropper } from "@vueuse/core";
import { Popover } from "frappe-ui";
import { PropType, Ref, StyleValue, computed, nextTick, ref, watch } from "vue";
import EyeDropperIcon from "./Icons/EyeDropper.vue";
const store = useStore();
const hueMap = ref(null) as unknown as Ref<HTMLDivElement>;
const colorMap = ref(null) as unknown as Ref<HTMLDivElement>;
const hueSelector = ref(null) as unknown as Ref<HTMLDivElement>;
const colorSelector = ref(null) as unknown as Ref<HTMLDivElement>;
const colorSelectorPosition = ref({ x: 0, y: 0 });
const hueSelectorPosition = ref({ x: 0, y: 0 });
let currentColor = "#FFF" as HashString;
const { isSupported, sRGBHex, open } = useEyeDropper();
const props = defineProps({
modelValue: {
type: String as PropType<HashString | RGBString | null>,
default: null,
},
});
const modelColor = computed(() => {
return getRGB(props.modelValue);
});
const emit = defineEmits(["update:modelValue"]);
const colors = [
"#FFB3E6",
"#00B3E6",
"#E6B333",
"#3366E6",
"#999966",
"#99FF99",
"#B34D4D",
"#80B300",
] as HashString[];
if (!isSupported.value) {
colors.push("#B34D4D");
}
const setColorSelectorPosition = (color: HashString) => {
const { width, height } = colorMap.value.getBoundingClientRect();
const { s, v } = HexToHSV(color);
let x = clamp(s * width, 0, width);
let y = clamp((1 - v) * height, 0, height);
colorSelectorPosition.value = { x, y };
};
const setHueSelectorPosition = (color: HashString) => {
const { width } = hueMap.value.getBoundingClientRect();
const { h } = HexToHSV(color);
const left = (h / 360) * width;
hueSelectorPosition.value = { x: left, y: 0 };
};
const handleSelectorMove = (ev: MouseEvent) => {
setColor(ev);
const mouseMove = (mouseMoveEvent: MouseEvent) => {
mouseMoveEvent.preventDefault();
setColor(mouseMoveEvent);
};
document.addEventListener("mousemove", mouseMove);
document.addEventListener(
"mouseup",
(mouseUpEvent) => {
document.removeEventListener("mousemove", mouseMove);
mouseUpEvent.preventDefault();
},
{ once: true },
);
};
const handleHueSelectorMove = (ev: MouseEvent) => {
setHue(ev);
store.activeCanvas?.history.pause();
const mouseMove = (mouseMoveEvent: MouseEvent) => {
mouseMoveEvent.preventDefault();
setHue(mouseMoveEvent);
};
document.addEventListener("mousemove", mouseMove);
document.addEventListener(
"mouseup",
(mouseUpEvent) => {
document.removeEventListener("mousemove", mouseMove);
mouseUpEvent.preventDefault();
store.activeCanvas?.history.resume(true);
},
{ once: true },
);
};
function setColor(ev: MouseEvent) {
const clickPointX = ev.clientX;
const clickPointY = ev.clientY;
const colorMapBounds = colorMap.value.getBoundingClientRect();
let pointX = clickPointX - colorMapBounds.left;
let pointY = clickPointY - colorMapBounds.top;
pointX = clamp(pointX, 0, colorMapBounds.width);
pointY = clamp(pointY, 0, colorMapBounds.height);
colorSelectorPosition.value = { x: pointX, y: pointY };
updateColor();
}
function setHue(ev: MouseEvent) {
const hueMapBounds = hueMap.value.getBoundingClientRect();
const { clientX } = ev;
let point = clientX - hueMapBounds.left;
point = clamp(point, 0, hueMapBounds.width);
hueSelectorPosition.value = { x: point, y: 0 };
updateColor();
}
function setSelectorPosition(color: HashString | null) {
if (!color) {
colorSelectorPosition.value = { x: 0, y: 0 };
hueSelectorPosition.value = { x: 0, y: 0 };
return;
}
nextTick(() => {
setColorSelectorPosition(color);
setHueSelectorPosition(color);
});
}
const hue = computed(() => {
if (!hueMap.value) return 0;
const positionX = hueSelectorPosition.value.x || 0;
const width = hueMap.value.getBoundingClientRect().width || 1;
return Math.round((positionX / width) * 360);
});
const updateColor = () => {
nextTick(() => {
const colorMapBounds = colorMap.value.getBoundingClientRect();
const s = Math.round((colorSelectorPosition.value.x / colorMapBounds.width) * 100);
const v = 100 - Math.round((colorSelectorPosition.value.y / colorMapBounds.height) * 100);
const h = hue.value;
currentColor = HSVToHex(h, s, v);
emit("update:modelValue", currentColor);
});
};
watch(sRGBHex, () => {
if (!isSupported.value || !sRGBHex.value) return;
emit("update:modelValue", sRGBHex.value);
});
watch(
() => props.modelValue,
(color) => {
if (color === currentColor) return;
setSelectorPosition(getRGB(color));
},
{ immediate: true },
);
</script>
|
2302_79757062/builder
|
frontend/src/components/ColorPicker.vue
|
Vue
|
agpl-3.0
| 7,909
|
<template>
<Menu
class="fixed z-50 h-fit w-fit min-w-[120px] rounded-lg bg-white p-1 shadow-xl dark:bg-zinc-900"
:style="{ top: y + 'px', left: x + 'px' }"
ref="menu">
<MenuItems static class="text-sm">
<MenuItem
v-slot="{ active, disabled }"
class="block cursor-pointer rounded-md px-3 py-1 dark:text-zinc-50"
v-for="(option, index) in options"
v-show="!option.condition || option.condition()">
<div
@click.prevent.stop="(!option.condition || option.condition()) && handleClick(option.action)"
:class="{
'text-gray-900': !disabled,
'bg-gray-200 dark:bg-zinc-700': active,
'text-gray-400 dark:text-zinc-500': disabled,
}">
{{ option.label }}
</div>
</MenuItem>
</MenuItems>
</Menu>
</template>
<script setup lang="ts">
import { Menu, MenuItem, MenuItems } from "@headlessui/vue";
import { computed, ref } from "vue";
const menu = ref(null) as unknown as typeof Menu;
interface ContextMenuOption {
label: string;
action: CallableFunction;
condition?: () => boolean;
}
const props = defineProps({
posX: {
type: Number,
required: true,
},
posY: {
type: Number,
required: true,
},
options: Array as () => ContextMenuOption[],
});
const x = computed(() => {
const menuWidth = menu.value?.$el.clientWidth;
const windowWidth = window.innerWidth;
const diff = windowWidth - (props.posX + menuWidth);
if (diff < 0) {
return props.posX + diff - 10;
}
return props.posX;
});
const y = computed(() => {
const menuHeight = menu.value?.$el.clientHeight;
const windowHeight = window.innerHeight;
const diff = windowHeight - (props.posY + menuHeight);
if (diff < 0) {
return props.posY + diff - 10;
}
return props.posY;
});
const emit = defineEmits({
select: (action: CallableFunction) => action,
});
const handleClick = (action: CallableFunction) => {
emit("select", action);
};
</script>
|
2302_79757062/builder
|
frontend/src/components/ContextMenu.vue
|
Vue
|
agpl-3.0
| 1,895
|
<template>
<div ref="component">
<div
v-if="!block.hasChildren()"
class="pointer-events-none flex h-full w-full items-center justify-center font-semibold">
Add a block to repeat
</div>
<BuilderBlock
v-else
:data="_data"
:block="block.children[0]"
:preview="index !== 0 || preview"
:breakpoint="breakpoint"
:isChildOfComponent="block.isExtendedFromComponent()"
v-for="(_data, index) in blockData" />
</div>
</template>
<script setup lang="ts">
import useStore from "@/store";
import Block from "@/utils/block";
import { Ref, computed, ref } from "vue";
import BuilderBlock from "./BuilderBlock.vue";
const store = useStore();
const props = defineProps({
block: {
type: Block,
required: true,
},
preview: {
type: Boolean,
default: false,
},
breakpoint: {
type: String,
default: "desktop",
},
data: {
type: Object,
default: null,
},
});
const component = ref(null) as Ref<HTMLElement | null>;
const blockData = computed(() => {
const pageData = props.data || store.pageData;
if (pageData && props.block.getDataKey("key")) {
const data = pageData[props.block.getDataKey("key")];
if (Array.isArray(data)) {
return data.slice(0, 100);
}
return data;
} else {
return [{}];
}
});
defineExpose({
component,
});
</script>
|
2302_79757062/builder
|
frontend/src/components/DataLoaderBlock.vue
|
Vue
|
agpl-3.0
| 1,297
|
<template>
<InlineInput
type="autocomplete"
:label="label"
:enableSlider="true"
:options="[
{
label: 'Auto',
value: 'auto',
},
{
label: 'Fit Content',
value: 'fit-content',
},
{
label: 'Stretch',
value: '100%',
},
]"
:modelValue="blockController.getStyle(props.property)"
:unitOptions="['px', '%', 'vw', 'vh']"
@update:modelValue="(val) => blockController.setStyle(property, val)"></InlineInput>
</template>
<script setup lang="ts">
import { styleProperty } from "@/utils/block";
import blockController from "@/utils/blockController";
import { PropType } from "vue";
import InlineInput from "./InlineInput.vue";
const props = defineProps({
property: {
type: String as PropType<styleProperty>,
required: true,
},
label: {
type: String,
required: true,
},
});
</script>
|
2302_79757062/builder
|
frontend/src/components/DimensionInput.vue
|
Vue
|
agpl-3.0
| 840
|
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2">
<rect width="7" height="9" x="3" y="3" rx="1" />
<rect width="7" height="5" x="14" y="3" rx="1" />
<rect width="7" height="9" x="14" y="12" rx="1" />
<rect width="7" height="5" x="3" y="16" rx="1" />
</g>
</svg>
</template>
|
2302_79757062/builder
|
frontend/src/components/Icons/Blocks.vue
|
Vue
|
agpl-3.0
| 439
|
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
<path
fill="currentColor"
d="M18.3 5.71a.996.996 0 0 0-1.41 0L12 10.59L7.11 5.7A.996.996 0 1 0 5.7 7.11L10.59 12L5.7 16.89a.996.996 0 1 0 1.41 1.41L12 13.41l4.89 4.89a.996.996 0 1 0 1.41-1.41L13.41 12l4.89-4.89c.38-.38.38-1.02 0-1.4z" />
</svg>
</template>
|
2302_79757062/builder
|
frontend/src/components/Icons/Cross.vue
|
Vue
|
agpl-3.0
| 362
|
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
<g fill="none" fill-rule="evenodd">
<path
d="M24 0v24H0V0h24ZM12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035c-.01-.004-.019-.001-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427c-.002-.01-.009-.017-.017-.018Zm.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093c.012.004.023 0 .029-.008l.004-.014l-.034-.614c-.003-.012-.01-.02-.02-.022Zm-.715.002a.023.023 0 0 0-.027.006l-.006.014l-.034.614c0 .012.007.02.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01l-.184-.092Z" />
<path
fill="currentColor"
d="M20.477 3.511a3 3 0 0 0-4.243 0l-1.533 1.533a2.991 2.991 0 0 0-3.41.581l-.713.714a2 2 0 0 0 0 2.829l-6.486 6.485a3 3 0 0 0-.878 2.122v1.8a1.2 1.2 0 0 0 1.2 1.2h1.8a3 3 0 0 0 2.12-.88l6.486-6.484a2 2 0 0 0 2.829 0l.714-.715a2.991 2.991 0 0 0 .581-3.41l1.533-1.532a3 3 0 0 0 0-4.243ZM5.507 17.067l6.485-6.485l1.414 1.414l-6.485 6.486a1 1 0 0 1-.707.293h-1v-1a1 1 0 0 1 .293-.707Z" />
</g>
</svg>
</template>
|
2302_79757062/builder
|
frontend/src/components/Icons/EyeDropper.vue
|
Vue
|
agpl-3.0
| 1,163
|
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24">
<path
fill="currentColor"
d="M20 9V6h-3V4h3q.825 0 1.413.588T22 6v3h-2ZM2 9V6q0-.825.588-1.413T4 4h3v2H4v3H2Zm15 11v-2h3v-3h2v3q0 .825-.588 1.413T20 20h-3ZM4 20q-.825 0-1.413-.588T2 18v-3h2v3h3v2H4Zm12-4H8q-.825 0-1.413-.588T6 14v-4q0-.825.588-1.413T8 8h8q.825 0 1.413.588T18 10v4q0 .825-.588 1.413T16 16Zm-8-2h8v-4H8v4Zm0 0v-4v4Z" />
</svg>
</template>
|
2302_79757062/builder
|
frontend/src/components/Icons/FitScreen.vue
|
Vue
|
agpl-3.0
| 459
|
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 256 256">
<path
fill="currentColor"
d="m213.66 82.34l-56-56A8 8 0 0 0 152 24H56a16 16 0 0 0-16 16v72a8 8 0 0 0 16 0V40h88v48a8 8 0 0 0 8 8h48v120h-24a8 8 0 0 0 0 16h24a16 16 0 0 0 16-16V88a8 8 0 0 0-2.34-5.66ZM160 51.31L188.69 80H160Zm-12.19 145a20.82 20.82 0 0 1-9.19 15.23C133.43 215 127 216 121.13 216a61.34 61.34 0 0 1-15.19-2a8 8 0 0 1 4.31-15.41c4.38 1.2 15 2.7 19.55-.36c.88-.59 1.83-1.52 2.14-3.93c.34-2.67-.71-4.1-12.78-7.59c-9.35-2.7-25-7.23-23-23.11a20.56 20.56 0 0 1 9-14.95c11.84-8 30.71-3.31 32.83-2.76a8 8 0 0 1-4.07 15.48c-4.49-1.17-15.23-2.56-19.83.56a4.54 4.54 0 0 0-2 3.67c-.12.9-.14 1.09 1.11 1.9c2.31 1.49 6.45 2.68 10.45 3.84c9.84 2.83 26.4 7.66 24.16 24.97ZM80 152v38a26 26 0 0 1-52 0a8 8 0 0 1 16 0a10 10 0 0 0 20 0v-38a8 8 0 0 1 16 0Z" />
</svg>
</template>
|
2302_79757062/builder
|
frontend/src/components/Icons/JavaScript.vue
|
Vue
|
agpl-3.0
| 880
|
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 256 256">
<path
fill="currentColor"
d="M224 128a8 8 0 0 1-8 8h-40.07c9.19 7.11 16.07 17.2 16.07 32c0 13.34-7 25.7-19.75 34.79C160.33 211.31 144.61 216 128 216s-32.33-4.69-44.25-13.21C71 193.7 64 181.34 64 168a8 8 0 0 1 16 0c0 17.35 22 32 48 32s48-14.65 48-32c0-14.85-10.54-23.58-38.77-32H40a8 8 0 0 1 0-16h176a8 8 0 0 1 8 8ZM76.33 104a8 8 0 0 0 7.61-10.49a17.3 17.3 0 0 1-.83-5.51c0-18.24 19.3-32 44.89-32c18.84 0 34.16 7.42 41 19.85a8 8 0 0 0 14-7.7C173.33 50.52 152.77 40 128 40c-34.71 0-60.89 20.63-60.89 48a33.73 33.73 0 0 0 1.62 10.49a8 8 0 0 0 7.6 5.51Z" />
</svg>
</template>
|
2302_79757062/builder
|
frontend/src/components/Icons/StrikeThrough.vue
|
Vue
|
agpl-3.0
| 680
|
<template>
<div class="flex items-center justify-between [&>div>input]:!bg-red-600 [&>div>input]:pr-6">
<InputLabel
:class="{
'cursor-ns-resize': enableSlider,
}"
@mousedown="handleMouseDown">
{{ label }}
<Popover trigger="hover" v-if="description" placement="top">
<template #target>
<FeatherIcon name="info" class="ml-1 h-[12px] w-[12px] text-gray-500" />
</template>
<template #body>
<slot name="body">
<div
class="w-fit max-w-52 rounded bg-gray-800 px-2 py-1 text-center text-xs text-white shadow-xl"
v-html="description"></div>
</slot>
</template>
</Popover>
</InputLabel>
<Input
:type="type"
placeholder="unset"
:modelValue="modelValue"
:options="inputOptions"
v-if="type != 'autocomplete'"
@update:modelValue="handleChange"
@keydown.stop="handleKeyDown" />
<Autocomplete
v-if="type == 'autocomplete'"
placeholder="unset"
:modelValue="modelValue"
:options="inputOptions"
@update:modelValue="handleChange"
:showInputAsOption="showInputAsOption"
class="w-full [&>div>select]:text-sm [&>div>select]:text-gray-800 [&>div>select]:dark:border-zinc-700 [&>div>select]:dark:bg-zinc-800 [&>div>select]:dark:text-zinc-200 [&>div>select]:dark:focus:bg-zinc-700" />
</div>
</template>
<script setup lang="ts">
import { isNumber } from "@tiptap/vue-3";
import { Popover } from "frappe-ui";
import FeatherIcon from "frappe-ui/src/components/FeatherIcon.vue";
import { PropType, computed } from "vue";
import Autocomplete from "./Autocomplete.vue";
import Input from "./Input.vue";
import InputLabel from "./InputLabel.vue";
const props = defineProps({
modelValue: {
type: [String, Number],
default: null,
},
label: {
type: String,
default: "",
},
description: {
type: String,
default: "",
},
type: {
type: String,
default: "text",
},
unitOptions: {
type: Array as PropType<string[]>,
default: () => [],
},
options: {
type: Array,
default: () => [],
},
enableSlider: {
type: Boolean,
default: false,
},
changeFactor: {
type: Number,
default: 1,
},
minValue: {
type: Number,
default: 0,
},
maxValue: {
type: Number,
default: null,
},
showInputAsOption: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(["update:modelValue"]);
type Option = {
label: string;
value: string;
};
const inputOptions = computed(() => {
return (props.options || []).map((option) => {
if (typeof option === "string" || (typeof option === "number" && props.type === "autocomplete")) {
return {
label: option,
value: option,
};
}
return option;
}) as Option[];
});
// TODO: Refactor
const handleChange = (value: string | number | null | { label: string; value: string }) => {
if (typeof value === "object" && value !== null && "value" in value) {
value = value.value;
}
if (value && typeof value === "string") {
let [_, number, unit] = value.match(/([0-9]+)([a-z%]*)/) || ["", "", ""];
if (!unit && props.unitOptions.length && number) {
value = number + props.unitOptions[0];
}
}
emit("update:modelValue", value);
};
const handleMouseDown = (e: MouseEvent) => {
if (!props.enableSlider) {
return;
}
const number = ((props.modelValue + "" || "") as string).match(/([0-9]+)/)?.[0] || "0";
const startY = e.clientY;
const startValue = Number(number);
const handleMouseMove = (e: MouseEvent) => {
let diff = (startY - e.clientY) * props.changeFactor;
diff = Math.round(diff);
incrementOrDecrement(diff, startValue);
};
const handleMouseUp = () => {
window.removeEventListener("mousemove", handleMouseMove);
};
window.addEventListener("mousemove", handleMouseMove);
window.addEventListener("mouseup", handleMouseUp, { once: true });
};
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "ArrowUp" || e.key === "ArrowDown") {
const step = e.key === "ArrowUp" ? 1 : -1;
incrementOrDecrement(step);
e.preventDefault();
}
};
const incrementOrDecrement = (step: number, initialValue: null | number = null) => {
const value = props.modelValue + "" || "";
let [_, number, unit] = value.match(/([0-9]+)([a-z%]*)/) || ["", "", ""];
if (!unit && props.unitOptions.length && !isNaN(Number(number))) {
unit = props.unitOptions[0];
}
let newValue = (initialValue != null ? Number(initialValue) : Number(number)) + step;
if (isNumber(props.minValue) && newValue <= props.minValue) {
newValue = props.minValue;
}
if (isNumber(props.maxValue) && newValue >= props.maxValue) {
newValue = props.maxValue;
}
handleChange(newValue + "" + unit);
};
</script>
|
2302_79757062/builder
|
frontend/src/components/InlineInput.vue
|
Vue
|
agpl-3.0
| 4,607
|
<template>
<div class="relative w-full">
<FormControl
class="relative [&>div>input]:focus-visible:ring-zinc-700 [&>div>input]:dark:border-zinc-700 [&>div>input]:dark:bg-zinc-800 [&>div>input]:dark:text-zinc-200 [&>div>input]:dark:focus:border-zinc-600 [&>div>input]:dark:focus:bg-zinc-700 [&>div>input]:dark:focus-visible:outline-0 [&>div>input]:dark:focus-visible:ring-zinc-700 [&>div>select]:text-sm [&>div>select]:text-gray-800 [&>div>select]:dark:border-zinc-700 [&>div>select]:dark:bg-zinc-800 [&>div>select]:dark:text-zinc-200 [&>div>select]:dark:focus:bg-zinc-700"
:type="type"
:class="{
'text-sm [&>div>input]:pr-5': !['select', 'checkbox'].includes(type),
}"
@change="
($event: Event) => {
if (type === 'checkbox') {
emit('update:modelValue', ($event.target as HTMLInputElement).checked);
} else {
emit('update:modelValue', ($event.target as HTMLInputElement).value);
}
}
"
@input="($event: Event) => emit('input', ($event.target as HTMLInputElement).value)"
autocomplete="off"
v-bind="attrs"
:modelValue="data"></FormControl>
<div
class="absolute right-[1px] top-[3px] cursor-pointer p-1 text-gray-700 dark:text-zinc-300"
@click="clearValue"
v-if="!['select', 'checkbox'].includes(type) && !hideClearButton"
v-show="data">
<CrossIcon />
</div>
</div>
</template>
<script lang="ts" setup>
import { useVModel } from "@vueuse/core";
import { useAttrs } from "vue";
import CrossIcon from "./Icons/Cross.vue";
const props = defineProps(["modelValue", "type", "hideClearButton"]);
const emit = defineEmits(["update:modelValue", "input"]);
const data = useVModel(props, "modelValue", emit);
defineOptions({
inheritAttrs: false,
});
const attrs = useAttrs();
const clearValue = () => {
data.value = "";
};
</script>
|
2302_79757062/builder
|
frontend/src/components/Input.vue
|
Vue
|
agpl-3.0
| 1,816
|
<template>
<span
class="inline-flex w-1/2 min-w-20 max-w-40 items-center text-xs leading-5 text-gray-700 dark:text-zinc-400">
<slot />
</span>
</template>
|
2302_79757062/builder
|
frontend/src/components/InputLabel.vue
|
Vue
|
agpl-3.0
| 161
|
<template>
<div
class="group"
:class="{
'opacity-40': !updating,
'opacity-70': updating,
}"
@click.stop>
<div
class="margin-handler pointer-events-none absolute flex w-full bg-yellow-200"
:style="{
height: topMarginHandlerHeight + 'px',
top: `calc(0% - ${topMarginHandlerHeight}px)`,
}"
ref="topMarginHandler">
<div
class="pointer-events-auto absolute left-[50%] rounded-full border-2 border-yellow-800 bg-yellow-400 hover:scale-125"
v-show="canvasProps.scale > 0.5"
:style="{
borderWidth: handleBorderWidth,
bottom: topHandle.bottom,
left: topHandle.left,
height: topHandle.height + 'px',
width: topHandle.width + 'px',
}"
:class="{
'cursor-ns-resize': !disableHandlers,
hidden: updating,
}"
@mousedown.stop="handleMargin($event, Position.Top)" />
<div class="m-auto text-sm text-yellow-900" v-show="updating">
{{ blockStyles.marginTop || "auto" }}
</div>
</div>
<div
class="margin-handler pointer-events-none absolute bottom-0 flex w-full bg-yellow-200"
:style="{
height: bottomMarginHandlerHeight + 'px',
bottom: `calc(0% - ${bottomMarginHandlerHeight}px)`,
}"
ref="bottomMarginHandler">
<div
class="pointer-events-auto absolute left-[50%] rounded-full border-2 border-yellow-800 bg-yellow-400 hover:scale-125"
v-show="canvasProps.scale > 0.5"
:style="{
borderWidth: handleBorderWidth,
bottom: bottomHandle.bottom,
left: bottomHandle.left,
height: bottomHandle.height + 'px',
width: bottomHandle.width + 'px',
}"
:class="{
'cursor-ns-resize': !disableHandlers,
hidden: updating,
}"
@mousedown.stop="handleMargin($event, Position.Bottom)" />
<div class="m-auto text-sm text-yellow-900" v-show="updating">
{{ blockStyles.marginBottom || "auto" }}
</div>
</div>
<div
class="margin-handler pointer-events-none absolute left-0 flex h-full bg-yellow-200"
:style="{
width: leftMarginHandlerWidth + 'px',
left: `calc(0% - ${leftMarginHandlerWidth}px)`,
}"
ref="leftMarginHandler">
<div
class="pointer-events-auto absolute top-[50%] rounded-full border-2 border-yellow-800 bg-yellow-400 hover:scale-125"
v-show="canvasProps.scale > 0.5"
:style="{
borderWidth: handleBorderWidth,
right: leftHandle.right,
top: leftHandle.top,
height: leftHandle.height + 'px',
width: leftHandle.width + 'px',
}"
:class="{
'cursor-ew-resize': !disableHandlers,
hidden: updating,
}"
@mousedown.stop="handleMargin($event, Position.Left)" />
<div class="m-auto text-sm text-yellow-900" v-show="updating">
{{ blockStyles.marginLeft || "auto" }}
</div>
</div>
<div
class="margin-handler pointer-events-none absolute right-0 flex h-full bg-yellow-200"
:style="{
width: rightMarginHandlerWidth + 'px',
right: `calc(0% - ${rightMarginHandlerWidth}px)`,
}"
ref="rightMarginHandler">
<div
class="pointer-events-auto absolute top-[50%] rounded-full border-2 border-yellow-800 bg-yellow-400 hover:scale-125"
v-show="canvasProps.scale > 0.5"
:style="{
borderWidth: handleBorderWidth,
right: rightHandle.right,
top: rightHandle.top,
height: rightHandle.height + 'px',
width: rightHandle.width + 'px',
}"
:class="{
'cursor-ew-resize': !disableHandlers,
hidden: updating,
}"
@mousedown.stop="handleMargin($event, Position.Right)" />
<div class="m-auto text-sm text-yellow-900" v-show="updating">
{{ blockStyles.marginRight || "auto" }}
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { clamp } from "@vueuse/core";
import { computed, inject, ref, watchEffect } from "vue";
import Block from "../utils/block";
import { getNumberFromPx } from "../utils/helpers";
const props = defineProps({
targetBlock: {
type: Block,
required: true,
},
target: {
type: [HTMLElement, SVGElement],
required: true,
},
disableHandlers: {
type: Boolean,
default: false,
},
onUpdate: {
type: Function,
default: null,
},
breakpoint: {
type: String,
default: "desktop",
},
});
const updating = ref(false);
const emit = defineEmits(["update"]);
const canvasProps = inject("canvasProps") as CanvasProps;
watchEffect(() => {
emit("update", updating.value);
});
const blockStyles = computed(() => {
let styleObj = props.targetBlock.baseStyles;
if (props.breakpoint === "mobile") {
styleObj = { ...styleObj, ...props.targetBlock.mobileStyles };
} else if (props.breakpoint === "tablet") {
styleObj = { ...styleObj, ...props.targetBlock.tabletStyles };
}
return styleObj;
});
const topMarginHandlerHeight = computed(() => {
blockStyles.value.marginTop;
blockStyles.value.display;
blockStyles.value.margin;
let marginTop = window.getComputedStyle(props.target).marginTop;
let value = getNumberFromPx(marginTop) * canvasProps.scale;
return value;
});
const bottomMarginHandlerHeight = computed(() => {
blockStyles.value.marginBottom;
blockStyles.value.display;
blockStyles.value.margin;
let marginBottom = window.getComputedStyle(props.target).marginBottom;
let value = getNumberFromPx(marginBottom) * canvasProps.scale;
return value;
});
const leftMarginHandlerWidth = computed(() => {
blockStyles.value.marginLeft;
blockStyles.value.display;
blockStyles.value.margin;
let marginLeft = window.getComputedStyle(props.target).marginLeft;
let value = getNumberFromPx(marginLeft) * canvasProps.scale;
return value;
});
const rightMarginHandlerWidth = computed(() => {
blockStyles.value.marginRight;
blockStyles.value.display;
blockStyles.value.margin;
let marginRight = window.getComputedStyle(props.target).marginRight;
let value = getNumberFromPx(marginRight) * canvasProps.scale;
return value;
});
const handleBorderWidth = computed(() => {
return `${clamp(1 * canvasProps.scale, 1, 2)}px`;
});
const topHandle = computed(() => {
const width = clamp(16 * canvasProps.scale, 8, 32);
const height = clamp(4 * canvasProps.scale, 2, 8);
return {
width: width,
height: height,
bottom: `clamp(0px, calc(4px * ${canvasProps.scale}), 12px)`,
left: `calc(50% - ${width / 2}px)`,
};
});
const bottomHandle = computed(() => {
const width = clamp(16 * canvasProps.scale, 8, 32);
const height = clamp(4 * canvasProps.scale, 2, 8);
return {
width: width,
height: height,
bottom: `clamp(-16px, calc(-8px * ${canvasProps.scale}), 2px)`,
left: `calc(50% - ${width / 2}px)`,
};
});
const leftHandle = computed(() => {
const width = clamp(4 * canvasProps.scale, 2, 8);
const height = clamp(16 * canvasProps.scale, 8, 32);
return {
width: width,
height: height,
right: `clamp(0px, calc(4px * ${canvasProps.scale}), 12px)`,
top: `calc(50% - ${height / 2}px)`,
};
});
const rightHandle = computed(() => {
const width = clamp(4 * canvasProps.scale, 2, 8);
const height = clamp(16 * canvasProps.scale, 8, 32);
return {
width: width,
height: height,
right: `clamp(-16px, calc(-8px * ${canvasProps.scale}), 2px)`,
top: `calc(50% - ${height / 2}px)`,
};
});
enum Position {
Top = "top",
Right = "right",
Bottom = "bottom",
Left = "left",
}
const handleMargin = (ev: MouseEvent, position: Position) => {
if (props.disableHandlers) return;
updating.value = true;
const startY = ev.clientY;
const startX = ev.clientX;
const target = ev.target as HTMLElement;
const startTop = getNumberFromPx(blockStyles.value.marginTop) || 0;
const startBottom = getNumberFromPx(blockStyles.value.marginBottom) || 0;
const startLeft = getNumberFromPx(blockStyles.value.marginLeft) || 0;
const startRight = getNumberFromPx(blockStyles.value.marginRight) || 0;
// to disable cursor jitter
const docCursor = document.body.style.cursor;
document.body.style.cursor = window.getComputedStyle(target).cursor;
const mousemove = (mouseMoveEvent: MouseEvent) => {
let movement = 0;
let affectingAxis = null;
props.onUpdate && props.onUpdate();
if (position === Position.Top) {
movement = Math.max(startTop + mouseMoveEvent.clientY - startY, 0);
props.targetBlock.setStyle("marginTop", movement + "px");
affectingAxis = "y";
} else if (position === Position.Bottom) {
movement = Math.max(startBottom + mouseMoveEvent.clientY - startY, 0);
props.targetBlock.setStyle("marginBottom", movement + "px");
affectingAxis = "y";
} else if (position === Position.Left) {
movement = Math.max(startLeft + mouseMoveEvent.clientX - startX, 0);
props.targetBlock.setStyle("marginLeft", movement + "px");
affectingAxis = "x";
} else if (position === Position.Right) {
movement = Math.max(startRight + mouseMoveEvent.clientX - startX, 0);
props.targetBlock.setStyle("marginRight", movement + "px");
affectingAxis = "x";
}
if (mouseMoveEvent.shiftKey) {
props.targetBlock.setStyle("marginTop", movement + "px");
props.targetBlock.setStyle("marginBottom", movement + "px");
props.targetBlock.setStyle("marginLeft", movement + "px");
props.targetBlock.setStyle("marginRight", movement + "px");
} else if (mouseMoveEvent.altKey) {
if (affectingAxis === "y") {
props.targetBlock.setStyle("marginTop", movement + "px");
props.targetBlock.setStyle("marginBottom", movement + "px");
} else if (affectingAxis === "x") {
props.targetBlock.setStyle("marginLeft", movement + "px");
props.targetBlock.setStyle("marginRight", movement + "px");
}
}
mouseMoveEvent.preventDefault();
};
document.addEventListener("mousemove", mousemove);
document.addEventListener(
"mouseup",
(mouseUpEvent) => {
document.body.style.cursor = docCursor;
document.removeEventListener("mousemove", mousemove);
updating.value = false;
mouseUpEvent.preventDefault();
},
{ once: true }
);
};
</script>
|
2302_79757062/builder
|
frontend/src/components/MarginHandler.vue
|
Vue
|
agpl-3.0
| 9,816
|
<template>
<div ref="objectEditor" class="flex flex-col gap-2" @paste="pasteObj">
<div v-for="(value, key) in obj" :key="key" class="flex gap-2">
<Input
placeholder="Property"
:modelValue="key"
@update:modelValue="(val: string) => replaceKey(key, val)"
class="rounded-md text-sm text-gray-800 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-200 dark:focus:bg-zinc-700" />
<Input
placeholder="Value"
:modelValue="value"
@update:modelValue="(val: string) => updateObjectValue(key, val)"
class="rounded-md text-sm text-gray-800 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-200 dark:focus:bg-zinc-700" />
<Button
variant="outline"
icon="x"
class="p-2 dark:border-zinc-600 dark:bg-zinc-800 dark:text-gray-100 dark:outline-0 dark:hover:bg-zinc-700 dark:hover:text-gray-100"
@click="deleteObjectKey(key as string)"></Button>
</div>
<Button
variant="subtle"
label="Add"
class="dark:bg-zinc-800 dark:text-gray-100"
@click="addObjectKey"></Button>
<p
class="rounded-sm bg-gray-100 p-2 text-2xs text-gray-800 dark:bg-zinc-800 dark:text-zinc-300"
v-show="description">
<span v-html="description"></span>
</p>
</div>
</template>
<script setup lang="ts">
import { mapToObject, replaceMapKey } from "@/utils/helpers";
import { ref } from "vue";
import Input from "./Input.vue";
const props = defineProps<{
obj: Record<string, string>;
description?: string;
}>();
const emit = defineEmits({
"update:obj": (obj: Record<string, string>) => true,
});
const addObjectKey = () => {
const map = new Map(Object.entries(props.obj));
map.set("", "");
emit("update:obj", mapToObject(map));
};
const updateObjectValue = (key: string, value: string) => {
const map = new Map(Object.entries(props.obj));
map.set(key, value);
emit("update:obj", mapToObject(map));
};
const replaceKey = (oldKey: string, newKey: string) => {
const map = new Map(Object.entries(props.obj));
emit("update:obj", mapToObject(replaceMapKey(map, oldKey, newKey)));
};
const deleteObjectKey = (key: string) => {
const map = new Map(Object.entries(props.obj));
map.delete(key);
emit("update:obj", mapToObject(map));
};
const objectEditor = ref<HTMLElement | null>(null);
const pasteObj = (e: ClipboardEvent) => {
const text = e.clipboardData?.getData("text/plain");
if (text) {
if (!text.includes(":")) return;
const map = new Map(Object.entries(props.obj));
try {
const objString = text.match(/{[^{}]+}/)?.[0];
if (!objString) throw new Error("Invalid object");
const obj = new Function("return " + objString)();
if (typeof obj === "object") {
for (const [key, value] of Object.entries(obj)) {
map.set(key, value as string);
}
map.delete("");
}
} catch (e) {
const lines = text.split(";");
for (const line of lines) {
const [key, value] = line.split(":");
if (!key || !value) continue;
map.set(key.trim(), value.replace(";", "").trim());
}
map.delete("");
}
emit("update:obj", mapToObject(map));
}
};
</script>
|
2302_79757062/builder
|
frontend/src/components/ObjectEditor.vue
|
Vue
|
agpl-3.0
| 3,052
|
<template>
<div class="flex w-full items-center justify-between">
<InputLabel v-if="label">{{ label }}</InputLabel>
<TabButtons
class="w-full min-w-[150px] [&>div>button[aria-checked='false']]:dark:!bg-transparent [&>div>button[aria-checked='false']]:dark:!text-zinc-400 [&>div>button[aria-checked='true']]:dark:!bg-zinc-700 [&>div>button]:items-center [&>div>button]:dark:!bg-zinc-700 [&>div>button]:dark:!text-zinc-100 [&>div]:h-7 [&>div]:dark:!bg-zinc-800"
:buttons="options"
:modelValue="modelValue"
@update:modelValue="$emit('update:modelValue', $event)"></TabButtons>
</div>
</template>
<script setup lang="ts">
import { TabButtons } from "frappe-ui";
import { PropType } from "vue";
import InputLabel from "./InputLabel.vue";
defineProps({
modelValue: {
type: [String, Number, Boolean],
},
options: {
type: Array as PropType<{ label: string; value: string | number; icon?: string; hideLabel?: boolean }[]>,
default: () => [],
},
label: {
type: String,
default: "",
},
});
const emit = defineEmits(["update:modelValue"]);
</script>
|
2302_79757062/builder
|
frontend/src/components/OptionToggle.vue
|
Vue
|
agpl-3.0
| 1,074
|
<template>
<div
class="group"
:class="{
'opacity-40': !updating,
'opacity-70': updating,
}"
@click.stop>
<div
class="padding-handler pointer-events-none absolute flex w-full bg-purple-400"
:style="{
height: topPaddingHandlerHeight + 'px',
}"
ref="topPaddingHandler">
<div
class="pointer-events-auto absolute left-[50%] rounded-full border-2 border-purple-500 bg-purple-400 hover:scale-125"
v-show="canvasProps.scale > 0.5"
:style="{
borderWidth: handleBorderWidth,
bottom: topHandle.bottom,
left: topHandle.left,
height: topHandle.height + 'px',
width: topHandle.width + 'px',
}"
:class="{
'cursor-ns-resize': !disableHandlers,
hidden: updating,
}"
@mousedown.stop="handlePadding($event, Position.Top)" />
<div class="m-auto text-sm text-purple-900" v-show="updating">
{{ blockStyles.paddingTop }}
</div>
</div>
<div
class="padding-handler pointer-events-none absolute bottom-0 flex w-full bg-purple-400"
:style="{
height: bottomPaddingHandlerHeight + 'px',
}"
ref="bottomPaddingHandler">
<div
class="pointer-events-auto absolute left-[50%] rounded-full border-2 border-purple-500 bg-purple-400 hover:scale-125"
v-show="canvasProps.scale > 0.5"
:style="{
borderWidth: handleBorderWidth,
top: bottomHandle.top,
left: bottomHandle.left,
height: bottomHandle.height + 'px',
width: bottomHandle.width + 'px',
}"
:class="{
'cursor-ns-resize': !disableHandlers,
hidden: updating,
}"
@mousedown.stop="handlePadding($event, Position.Bottom)" />
<div class="m-auto text-sm text-purple-900" v-show="updating">
{{ blockStyles.paddingBottom }}
</div>
</div>
<div
class="padding-handler pointer-events-none absolute left-0 flex h-full bg-purple-400"
:style="{
width: leftPaddingHandlerWidth + 'px',
}"
ref="leftPaddingHandler">
<div
class="pointer-events-auto absolute top-[50%] rounded-full border-2 border-purple-500 bg-purple-400 hover:scale-125"
v-show="canvasProps.scale > 0.5"
:style="{
borderWidth: handleBorderWidth,
right: leftHandle.right,
top: leftHandle.top,
height: leftHandle.height + 'px',
width: leftHandle.width + 'px',
}"
:class="{
'cursor-ew-resize': !disableHandlers,
hidden: updating,
}"
@mousedown.stop="handlePadding($event, Position.Left)" />
<div class="m-auto text-sm text-purple-900" v-show="updating">
{{ blockStyles.paddingLeft }}
</div>
</div>
<div
class="padding-handler pointer-events-none absolute right-0 flex h-full bg-purple-400"
:style="{
width: rightPaddingHandlerWidth + 'px',
}"
ref="rightPaddingHandler">
<div
class="pointer-events-auto absolute top-[50%] rounded-full border-2 border-purple-500 bg-purple-400 hover:scale-125"
v-show="canvasProps.scale > 0.5"
:style="{
borderWidth: handleBorderWidth,
left: rightHandle.left,
top: rightHandle.top,
height: rightHandle.height + 'px',
width: rightHandle.width + 'px',
}"
:class="{
'cursor-ew-resize': !disableHandlers,
hidden: updating,
}"
@mousedown.stop="handlePadding($event, Position.Right)" />
<div class="m-auto text-sm text-purple-900" v-show="updating">
{{ blockStyles.paddingRight }}
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { clamp } from "@vueuse/core";
import { computed, inject, ref, watchEffect } from "vue";
import Block from "../utils/block";
import { getNumberFromPx } from "../utils/helpers";
import { toast } from "vue-sonner";
const canvasProps = inject("canvasProps") as CanvasProps;
const props = defineProps({
targetBlock: {
type: Block,
required: true,
},
disableHandlers: {
type: Boolean,
default: false,
},
onUpdate: {
type: Function,
default: null,
},
breakpoint: {
type: String,
default: "desktop",
},
target: {
type: [HTMLElement, SVGElement],
required: true,
},
});
const updating = ref(false);
const emit = defineEmits(["update"]);
watchEffect(() => {
emit("update", updating.value);
});
const blockStyles = computed(() => {
let styleObj = props.targetBlock.baseStyles;
if (props.breakpoint === "mobile") {
styleObj = { ...styleObj, ...props.targetBlock.mobileStyles };
} else if (props.breakpoint === "tablet") {
styleObj = { ...styleObj, ...props.targetBlock.tabletStyles };
}
return styleObj;
});
const topPaddingHandlerHeight = computed(() => {
return getPadding("Top");
});
const bottomPaddingHandlerHeight = computed(() => {
return getPadding("Bottom");
});
const leftPaddingHandlerWidth = computed(() => {
return getPadding("Left");
});
const rightPaddingHandlerWidth = computed(() => {
return getPadding("Right");
});
const getPadding = (side: "Top" | "Left" | "Right" | "Bottom") => {
blockStyles.value.paddingRight;
blockStyles.value.paddingTop;
blockStyles.value.paddingBottom;
blockStyles.value.paddingLeft;
blockStyles.value.padding;
return getNumberFromPx(getComputedStyle(props.target)[`padding${side}`]) * canvasProps.scale;
};
const handleBorderWidth = computed(() => {
return `${clamp(1 * canvasProps.scale, 1, 2)}px`;
});
const topHandle = computed(() => {
const width = clamp(16 * canvasProps.scale, 8, 32);
const height = clamp(4 * canvasProps.scale, 2, 8);
return {
width: width,
height: height,
bottom: `clamp(-20px, calc(-6px * ${canvasProps.scale}), -8px)`,
left: `calc(50% - ${width / 2}px)`,
};
});
const bottomHandle = computed(() => {
const width = clamp(16 * canvasProps.scale, 8, 32);
const height = clamp(4 * canvasProps.scale, 2, 8);
return {
width: width,
height: height,
top: `clamp(-20px, calc(-6px * ${canvasProps.scale}), -8px)`,
left: `calc(50% - ${width / 2}px)`,
};
});
const leftHandle = computed(() => {
const width = clamp(4 * canvasProps.scale, 2, 8);
const height = clamp(16 * canvasProps.scale, 8, 32);
return {
width: width,
height: height,
right: `clamp(-20px, calc(-6px * ${canvasProps.scale}), -8px)`,
top: `calc(50% - ${height / 2}px)`,
};
});
const rightHandle = computed(() => {
const width = clamp(4 * canvasProps.scale, 2, 8);
const height = clamp(16 * canvasProps.scale, 8, 32);
return {
width: width,
height: height,
left: `clamp(-20px, calc(-6px * ${canvasProps.scale}), -8px)`,
top: `calc(50% - ${height / 2}px)`,
};
});
enum Position {
Top = "top",
Right = "right",
Bottom = "bottom",
Left = "left",
}
const messageShown = ref(false);
const handlePadding = (ev: MouseEvent, position: Position) => {
if (props.disableHandlers) return;
// if (!messageShown.value && !(ev.shiftKey || ev.altKey)) {
// showToast();
// messageShown.value = true;
// }
updating.value = true;
const startY = ev.clientY;
const startX = ev.clientX;
const target = ev.target as HTMLElement;
const startTop = getNumberFromPx(blockStyles.value.paddingTop) || 5;
const startBottom = getNumberFromPx(blockStyles.value.paddingBottom) || 5;
const startLeft = getNumberFromPx(blockStyles.value.paddingLeft) || 5;
const startRight = getNumberFromPx(blockStyles.value.paddingRight) || 5;
// to disable cursor jitter
const docCursor = document.body.style.cursor;
document.body.style.cursor = window.getComputedStyle(target).cursor;
const mousemove = (mouseMoveEvent: MouseEvent) => {
let movement = 0;
let affectingAxis = null;
props.onUpdate && props.onUpdate();
if (position === Position.Top) {
movement = Math.max(startTop + mouseMoveEvent.clientY - startY, 0);
props.targetBlock.setStyle("paddingTop", movement + "px");
affectingAxis = "y";
} else if (position === Position.Bottom) {
movement = Math.max(startBottom + startY - mouseMoveEvent.clientY, 0);
props.targetBlock.setStyle("paddingBottom", movement + "px");
affectingAxis = "y";
} else if (position === Position.Left) {
movement = Math.max(startLeft + mouseMoveEvent.clientX - startX, 0);
props.targetBlock.setStyle("paddingLeft", movement + "px");
affectingAxis = "x";
} else if (position === Position.Right) {
movement = Math.max(startRight + startX - mouseMoveEvent.clientX, 0);
props.targetBlock.setStyle("paddingRight", movement + "px");
affectingAxis = "x";
}
if (mouseMoveEvent.altKey) {
if (affectingAxis === "y") {
props.targetBlock.setStyle("paddingTop", movement + "px");
props.targetBlock.setStyle("paddingBottom", movement + "px");
} else if (affectingAxis === "x") {
props.targetBlock.setStyle("paddingLeft", movement + "px");
props.targetBlock.setStyle("paddingRight", movement + "px");
}
} else if (mouseMoveEvent.shiftKey) {
props.targetBlock.setStyle("paddingTop", movement + "px");
props.targetBlock.setStyle("paddingBottom", movement + "px");
props.targetBlock.setStyle("paddingLeft", movement + "px");
props.targetBlock.setStyle("paddingRight", movement + "px");
}
mouseMoveEvent.preventDefault();
mouseMoveEvent.stopPropagation();
};
document.addEventListener("mousemove", mousemove);
document.addEventListener(
"mouseup",
(mouseUpEvent) => {
document.body.style.cursor = docCursor;
document.removeEventListener("mousemove", mousemove);
updating.value = false;
mouseUpEvent.preventDefault();
},
{ once: true }
);
};
let showToast = () =>
toast('Press "shift" key to apply padding to all sides and "alt" key to apply padding on either sides.');
</script>
|
2302_79757062/builder
|
frontend/src/components/PaddingHandler.vue
|
Vue
|
agpl-3.0
| 9,464
|
<template>
<div class="flex h-[70vh] gap-5">
<div class="flex flex-col gap-3">
<div class="flex h-full w-48 flex-col justify-between gap-1">
<div class="flex flex-col gap-1">
<a
v-for="script in attachedScriptResource.data"
href="#"
:class="{
'text-gray-600 dark:text-gray-500': activeScript !== script,
'font-medium dark:text-zinc-200': activeScript === script,
}"
@click="selectScript(script)"
class="group flex items-center justify-between gap-1 text-sm last-of-type:mb-2">
<div class="flex w-[90%] items-center gap-1">
<CSSIcon class="shrink-0" v-if="script.script_type === 'CSS'" />
<JavaScriptIcon class="shrink-0" v-if="script.script_type === 'JavaScript'" />
<span
class="truncate"
@blur="updateScriptName($event, script)"
@keydown.enter.stop.prevent="script.editable = false"
@dblclick.stop="script.editable = true"
:contenteditable="script.editable">
{{ script.script_name }}
</span>
</div>
<FeatherIcon name="trash" class="h-3 w-3" @click.stop="deleteScript(script.name)"></FeatherIcon>
</a>
<div class="flex w-full gap-2">
<Dropdown
:options="[
{ label: 'JavaScript', onClick: () => addScript('JavaScript') },
{ label: 'CSS', onClick: () => addScript('CSS') },
]"
size="sm"
class="flex-1 [&>div>div>div]:w-full"
placement="right">
<template v-slot="{ open }">
<Button
class="w-full text-xs dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700"
@click="open">
New Script
</Button>
</template>
</Dropdown>
<Dropdown
v-if="clientScriptResource.data && clientScriptResource.data.length > 0"
:options="clientScriptOptions"
size="sm"
class="max-w-60 flex-1 [&>div>div>div]:w-full">
<template v-slot="{ open }">
<Button
class="w-full text-xs dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700"
@click="open">
Attach Script
</Button>
</template>
</Dropdown>
</div>
</div>
<div class="text-xs text-gray-600 dark:text-zinc-300">
<b>Note:</b>
All client scripts are executed in preview mode and on published pages.
</div>
</div>
</div>
<div
class="flex h-full w-full items-center justify-center rounded bg-gray-100 text-base text-gray-600 dark:bg-zinc-900 dark:text-zinc-500"
v-show="!activeScript">
Add Script
</div>
<div v-if="activeScript" class="flex h-full w-full flex-col">
<CodeEditor
ref="scriptEditor"
:modelValue="activeScript.script"
:label="activeScript.script_name"
:type="activeScript.script_type as 'JavaScript' | 'CSS'"
class="flex-1"
height="auto"
:autofocus="false"
:show-save-button="true"
@save="updateScript"
:show-line-numbers="true"></CodeEditor>
</div>
</div>
</template>
<script setup lang="ts">
import { posthog } from "@/telemetry";
import { BuilderPage } from "@/types/Builder/BuilderPage";
import { createListResource, createResource, Dropdown } from "frappe-ui";
import { computed, nextTick, PropType, ref, watch } from "vue";
import { toast } from "vue-sonner";
import CodeEditor from "./CodeEditor.vue";
import CSSIcon from "./Icons/CSS.vue";
import JavaScriptIcon from "./Icons/JavaScript.vue";
const scriptEditor = ref<typeof CodeEditor | null>(null);
type attachedScript = {
script: string;
script_type: string;
name: string;
script_name: string;
editable: boolean;
};
const activeScript = ref<attachedScript | null>(null);
const props = defineProps({
page: {
type: Object as PropType<BuilderPage>,
required: true,
},
});
const attachedScriptResource = createListResource({
doctype: "Builder Page Client Script",
parent: "Builder Page",
filters: {
parent: props.page.name,
},
fields: [
"builder_script.script",
"builder_script.script_type",
"builder_script.name as script_name",
"name",
],
orderBy: "`tabBuilder Page Client Script`.creation asc",
auto: true,
onSuccess: (data: attachedScript[]) => {
if (data && data.length > 0 && !activeScript.value) {
selectScript(data[0]);
}
},
});
const clientScriptResource = createListResource({
doctype: "Builder Client Script",
fields: ["script", "script_type", "name"],
pageLength: 100,
auto: true,
});
const selectScript = (script: attachedScript) => {
activeScript.value = script;
nextTick(() => {
scriptEditor.value?.resetEditor(script.script, true);
});
};
const updateScript = (value: string) => {
console.log(value);
if (!activeScript.value) return;
clientScriptResource.setValue
.submit({
name: activeScript.value.script_name,
script: value,
})
.then(async () => {
await attachedScriptResource.reload();
attachedScriptResource.data?.forEach((script: attachedScript) => {
if (script.script_name === activeScript.value?.script_name) {
activeScript.value = script;
}
});
toast.success("Script saved successfully");
})
.catch((e: { message: string; exc: string }) => {
const error_message = e.exc.split("\n").slice(-2)[0];
toast.error("Failed to save script", {
description: error_message,
});
});
};
const addScript = (scriptType: "JavaScript" | "CSS") => {
clientScriptResource.insert
.submit({
script_type: scriptType,
script: scriptType === "JavaScript" ? "// Write your script here\n" : "/* Write your CSS here */\n",
})
.then((res: { name: string; script_type: string; script: string }) => {
attachedScriptResource.insert
.submit({
parent: props.page.name,
parenttype: "Builder Page",
parentfield: "client_scripts",
builder_script: res.name,
})
.then(async () => {
posthog.capture("builder_client_script_added", {
script_type: res.script_type,
});
await attachedScriptResource.reload();
attachedScriptResource.data?.forEach((script: attachedScript) => {
if (script.script_name === res.name) {
selectScript(script);
}
});
});
});
};
const attachScript = (builder_script_name: string) => {
attachedScriptResource.insert
.submit({
parent: props.page.name,
parenttype: "Builder Page",
parentfield: "client_scripts",
builder_script: builder_script_name,
})
.then(async () => {
posthog.capture("builder_client_script_attached");
await attachedScriptResource.reload();
attachedScriptResource.data?.forEach((script: attachedScript) => {
if (script.script_name === builder_script_name) {
selectScript(script);
}
});
});
};
const deleteScript = (scriptName: string) => {
activeScript.value = null;
attachedScriptResource.delete.submit(scriptName).then(() => {
attachedScriptResource.reload();
});
};
const updateScriptName = (ev: Event, script: attachedScript) => {
const target = ev.target as HTMLElement;
const newName = target.innerText.trim();
createResource({
url: "frappe.client.rename_doc",
})
.submit({
doctype: "Builder Client Script",
old_name: script?.script_name,
new_name: newName,
})
.then(async () => {
await attachedScriptResource.reload();
await clientScriptResource.reload();
attachedScriptResource.data?.forEach((script: attachedScript) => {
if (script.script_name === newName) {
selectScript(script);
}
});
});
};
const clientScriptOptions = computed(() =>
clientScriptResource.data?.map((script: { name: string; script_type: string }) => ({
label: script.name,
onClick: () => attachScript(script.name),
})),
);
watch(
() => props.page,
async () => {
activeScript.value = null;
attachedScriptResource.filters.parent = props.page.name;
await attachedScriptResource.reload();
if (attachedScriptResource.data && attachedScriptResource.data.length > 0) {
selectScript(attachedScriptResource.data[0]);
}
},
);
</script>
<style scoped>
:deep(.editor > .ace_editor) {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
</style>
|
2302_79757062/builder
|
frontend/src/components/PageClientScriptManager.vue
|
Vue
|
agpl-3.0
| 8,065
|
<template>
<div>
<div class="flex flex-row flex-wrap gap-3">
<h3 class="mb-1 w-full text-sm font-medium text-gray-900 dark:text-zinc-300">Page Options</h3>
<InlineInput
label="Title"
type="text"
class="w-full text-sm [&>label]:w-[60%] [&>label]:min-w-[180px]"
:modelValue="page.page_title"
@update:modelValue="(val) => webPages.setValue.submit({ name: page.name, page_title: val })" />
<InlineInput
type="text"
class="w-full text-sm [&>label]:w-[60%] [&>label]:min-w-[180px]"
label="Route"
:modelValue="page.route"
@update:modelValue="(val) => webPages.setValue.submit({ name: page.name, route: val })" />
<!-- TODO: Fix option arrangement and placements -->
<OptionToggle
:label="'Dynamic Route?'"
:modelValue="page.dynamic_route ? 'Yes' : 'No'"
@update:modelValue="
(val) => {
webPages.setValue.submit({ name: page.name, dynamic_route: val === 'Yes' });
page.dynamic_route = val === 'Yes' ? 1 : 0;
}
"
:options="[
{ label: 'Yes', value: 'Yes' },
{ label: 'No', value: 'No' },
]"
ß></OptionToggle>
<!-- Dynamic Route Variables -->
<div v-if="page.dynamic_route" class="mb-3 mt-3 w-full">
<h3 class="text-sm font-medium text-gray-900 dark:text-zinc-300">Route Values</h3>
<div class="mt-5 flex flex-row flex-wrap gap-5">
<InlineInput
v-for="(variable, index) in dynamicVariables"
:key="index"
type="text"
:label="variable.replace(/_/g, ' ')"
class="w-full text-sm"
:modelValue="store.routeVariables[variable]"
@update:modelValue="(val) => store.setRouteVariable(variable, val)" />
</div>
</div>
<!-- favicon -->
<InlineInput
label="Favicon"
type="text"
class="w-full text-sm [&>label]:w-[60%] [&>label]:min-w-[180px]"
:modelValue="page.favicon"
:disabled="true"
@update:modelValue="(val) => webPages.setValue.submit({ name: page.name, favicon: val })" />
<div class="flex w-full justify-end">
<FileUploader
file-types="image/ico"
class="text-base [&>div>button]:dark:bg-zinc-800 [&>div>button]:dark:text-zinc-200 [&>div>button]:dark:hover:bg-zinc-700"
@success="
(file: FileDoc) => {
webPages.setValue.submit({ name: page.name, favicon: file.file_url }).then(() => {
page.favicon = file.file_url;
});
}
">
<template v-slot="{ file, progress, uploading, openFileSelector }">
<div class="flex items-center space-x-2">
<Button @click="openFileSelector">
{{
uploading ? `Uploading ${progress}%` : page.favicon ? "Change Favicon" : "Upload Favicon"
}}
</Button>
<Button
v-if="page.favicon"
@click="
() => {
page.favicon = '';
webPages.setValue.submit({ name: page.name, favicon: '' });
}
">
Remove
</Button>
</div>
</template>
</FileUploader>
</div>
<div class="mt-5 flex w-full flex-col gap-2">
<Button
v-if="page.published && !store.isHomePage(page)"
@click="() => setHomePage(page)"
class="block text-base dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700">
Set as Home Page
</Button>
<Button
v-if="page.published && store.isHomePage(page)"
@click="() => unsetHomePage()"
class="block text-base dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700">
Unset as Home Page
</Button>
<Button
v-if="page.published"
@click="() => store.openPageInBrowser(page)"
class="block text-base dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700">
View Published Page
</Button>
<Button
v-if="page.published"
@click="() => unpublishPage()"
class="block text-base dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700">
Unpublish Page
</Button>
<hr class="my-2 dark:border-zinc-800" v-if="page.published" />
<Button
@click="() => store.openInDesk(page)"
class="block text-base dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700">
Open in Desk
</Button>
<Button
@click="() => store.openBuilderSettings()"
class="block text-base dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700">
Open Builder Settings
</Button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { builderSettings } from "@/data/builderSettings";
import { webPages } from "@/data/webPage";
import useStore from "@/store";
import { BuilderPage } from "@/types/Builder/BuilderPage";
import { FileUploader } from "frappe-ui";
import { computed } from "vue";
import { toast } from "vue-sonner";
import InlineInput from "./InlineInput.vue";
import OptionToggle from "./OptionToggle.vue";
const store = useStore();
const props = defineProps<{
page: BuilderPage;
}>();
const dynamicVariables = computed(() => {
return (props.page.route?.match(/<\w+>/g) || []).map((match) => match.slice(1, -1));
});
const unpublishPage = () => {
webPages.setValue
.submit({
name: props.page.name,
published: false,
})
.then(() => {
toast.success("Page unpublished");
store.setPage(props.page.name);
builderSettings.reload();
});
};
const setHomePage = (page: BuilderPage) => {
builderSettings.setValue
.submit({
home_page: page.route,
})
.then(() => {
toast.success("Home Page set");
});
};
const unsetHomePage = () => {
builderSettings.setValue
.submit({
home_page: "",
})
.then(() => {
toast.success("Home Page unset");
});
};
</script>
|
2302_79757062/builder
|
frontend/src/components/PageOptions.vue
|
Vue
|
agpl-3.0
| 5,583
|
<template>
<router-link
:to="{ name: 'builder', params: { pageId: page.page_name } }"
v-if="mode === 'grid'"
class="max-w-[250px] flex-grow basis-52">
<div
class="group relative mr-2 w-full overflow-hidden rounded-md shadow hover:cursor-pointer dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200">
<img
width="250"
height="140"
:src="page.preview"
onerror="this.src='/assets/builder/images/fallback.png'"
class="w-full overflow-hidden rounded-lg bg-gray-50 object-cover p-2 dark:bg-zinc-900" />
<div class="flex items-center justify-between border-t-[1px] px-3 dark:border-zinc-800">
<span class="inline-block max-w-[160px] py-2 text-sm text-gray-700 dark:text-zinc-200">
<div class="flex items-center gap-1">
<p class="truncate">
{{ page.page_title || page.page_name }}
</p>
</div>
<UseTimeAgo v-slot="{ timeAgo }" :time="page.modified">
<p class="mt-1 block text-xs text-gray-500">Edited {{ timeAgo }}</p>
</UseTimeAgo>
</span>
<Dropdown :options="actions" size="sm" placement="right">
<template v-slot="{ open }">
<FeatherIcon
name="more-vertical"
class="h-4 w-4 text-gray-500 hover:text-gray-700"
@click="open"></FeatherIcon>
</template>
</Dropdown>
</div>
</div>
</router-link>
<router-link
v-if="mode === 'list'"
:key="page.page_name"
:to="{ name: 'builder', params: { pageId: page.page_name } }"
class="h-fit w-full flex-grow">
<div
class="group relative mr-2 flex w-full overflow-hidden rounded-md shadow hover:cursor-pointer dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200">
<img
width="250"
height="140"
:src="page.preview"
onerror="this.src='/assets/builder/images/fallback.png'"
class="block w-44 overflow-hidden rounded-lg bg-gray-50 object-cover p-2 dark:bg-zinc-900" />
<div class="flex flex-1 items-start justify-between border-t-[1px] p-3 px-3 dark:border-zinc-800">
<span class="flex h-full flex-col justify-between text-sm text-gray-700 dark:text-zinc-200">
<div>
<div class="flex items-center gap-1">
<p class="truncate">
{{ page.page_title || page.page_name }}
</p>
</div>
<div class="mt-2 flex items-center gap-1">
<FeatherIcon name="globe" class="h-3 w-3 text-gray-500 hover:text-gray-700"></FeatherIcon>
<p class="text-xs text-gray-600">
{{ page.route }}
</p>
</div>
</div>
<div class="flex items-baseline gap-1">
<p class="mt-1 block text-xs text-gray-500">Created By {{ page.owner }}</p>
·
<UseTimeAgo v-slot="{ timeAgo }" :time="page.modified">
<p class="mt-1 block text-xs text-gray-500">Edited {{ timeAgo }}</p>
</UseTimeAgo>
</div>
</span>
<div class="flex items-center gap-2">
<Badge theme="green" v-if="page.published" class="dark:bg-green-900 dark:text-green-400">
Published
</Badge>
<Dropdown :options="actions" size="sm" placement="right">
<template v-slot="{ open }">
<FeatherIcon
name="more-vertical"
class="h-4 w-4 text-gray-500 hover:text-gray-700"
@click="open"></FeatherIcon>
</template>
</Dropdown>
</div>
</div>
</div>
</router-link>
</template>
<script setup lang="ts">
import { webPages } from "@/data/webPage";
import useStore from "@/store";
import { BuilderPage } from "@/types/Builder/BuilderPage";
import { confirm } from "@/utils/helpers";
import { UseTimeAgo } from "@vueuse/components";
import { Badge, Dropdown, createDocumentResource } from "frappe-ui";
const store = useStore();
const props = defineProps<{
page: BuilderPage;
mode: "grid" | "list";
}>();
const duplicatePage = async (page: BuilderPage) => {
const webPageResource = await createDocumentResource({
doctype: "Builder Page",
name: page.page_name,
auto: true,
});
await webPageResource.get.promise;
const pageCopy = webPageResource.doc as BuilderPage;
pageCopy.page_name = `${pageCopy.page_name}-copy`;
pageCopy.page_title = `${pageCopy.page_title} Copy`;
await webPages.insert.submit(pageCopy);
};
const deletePage = async (page: BuilderPage) => {
const confirmed = await confirm(
`Are you sure you want to delete <b title=${page.page_name}>${page.page_title}</b>?`,
);
if (confirmed) {
await webPages.delete.submit(page.name);
}
};
const actions = [
{
label: "Duplicate",
onClick: () => duplicatePage(props.page),
icon: "copy",
},
{
label: "View in Desk",
onClick: () => store.openInDesk(props.page),
icon: "arrow-up-right",
},
{
label: "Delete",
onClick: () => deletePage(props.page),
icon: "trash",
},
];
</script>
|
2302_79757062/builder
|
frontend/src/components/PagePreviewCard.vue
|
Vue
|
agpl-3.0
| 4,705
|
<template>
<div class="flex flex-col gap-4">
<div class="flex gap-2">
<Button
@click="showClientScriptEditor()"
class="flex-1 text-base dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700">
Client Script
</Button>
<Button
@click="showServerScriptEditor()"
class="flex-1 text-base dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700">
Data Script
</Button>
</div>
<CodeEditor v-model="store.pageData" type="JSON" label="Data Preview" :readonly="true"></CodeEditor>
<Dialog
style="z-index: 40"
class="overscroll-none"
:options="{
title: currentScriptEditor == 'data' ? 'Data Script' : 'Client Script',
size: '7xl',
}"
v-model="showDialog">
<template #body-content>
<div v-if="currentScriptEditor == 'client'">
<PageClientScriptManager :page="store.activePage as BuilderPage"></PageClientScriptManager>
</div>
<div v-else>
<CodeEditor
class="overscroll-none"
v-model="page.page_data_script"
type="Python"
height="65vh"
@save="savePageDataScript"
:showSaveButton="true"
description='Use Data Script to provide dynamic data to your web page.<br>
<b>Example:</b> data.events = frappe.get_list("Event")<br><br>
For more details on how to write data script, refer to <b><a class="underline" href="https://docs.frappe.io/builder/data-script" target="_blank">this documentation</a></b>.
'
:show-line-numbers="true"></CodeEditor>
</div>
</template>
</Dialog>
</div>
</template>
<script lang="ts" setup>
import { webPages } from "@/data/webPage";
import useStore from "@/store";
import { posthog } from "@/telemetry";
import { BuilderPage } from "@/types/Builder/BuilderPage";
import { Dialog } from "frappe-ui";
import { defineComponent, ref } from "vue";
import { toast } from "vue-sonner";
import CodeEditor from "./CodeEditor.vue";
import PageClientScriptManager from "./PageClientScriptManager.vue";
const store = useStore();
const showDialog = ref(false);
const props = defineProps<{
page: BuilderPage;
}>();
const currentScriptEditor = ref<"client" | "data">("client");
const savePageDataScript = (value: string) => {
webPages.setValue
.submit({
name: props.page.name,
page_data_script: value,
})
.then(() => {
posthog.capture("builder_page_data_script_saved");
showDialog.value = false;
props.page.page_data_script = value;
store.setPageData(props.page);
toast.success("Data script saved");
})
.catch((e: { message: string; exc: string; messages: [string] }) => {
let errorMessage = e.exc?.split("\n").slice(-2)[0];
if (!errorMessage) {
errorMessage = e.messages[0];
}
toast.error("Failed to save script", {
description: defineComponent({
template: `<div>${errorMessage}</div>`,
}),
});
});
};
const showClientScriptEditor = () => {
currentScriptEditor.value = "client";
showDialog.value = true;
};
const showServerScriptEditor = () => {
currentScriptEditor.value = "data";
showDialog.value = true;
};
</script>
<style></style>
|
2302_79757062/builder
|
frontend/src/components/PageScript.vue
|
Vue
|
agpl-3.0
| 3,083
|
<template>
<div
class="absolute z-20"
:class="{
'top-0 h-full w-1 hover:cursor-ew-resize': side === 'left' || side === 'right',
'left-0 right-0 h-1 hover:cursor-ns-resize': side === 'top' || side === 'bottom',
'left-0': side === 'left',
'right-0': side === 'right',
'top-0': side === 'top',
'bottom-0': side === 'bottom',
'bg-gray-300 dark:bg-zinc-700': dragActive,
}"
@mousedown.prevent="resize">
<slot />
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
const props = defineProps({
maxDimension: {
type: Number,
default: 350,
},
minDimension: {
type: Number,
default: 280,
},
dimension: {
type: Number,
default: 300,
},
side: {
type: String,
default: "right",
validator: (value: string) => ["left", "right", "top", "bottom"].includes(value),
},
resizeSensitivity: {
type: Number,
default: 1,
},
});
const emit = defineEmits({
resize: (width) => width,
});
const dragActive = ref(false);
defineExpose({ dragActive });
function resize(ev: MouseEvent) {
const startX = ev.clientX;
const startY = ev.clientY;
const startDimension = props.dimension;
const target = ev.target as HTMLElement;
// to disable cursor jitter
const docCursor = document.body.style.cursor;
document.body.style.cursor = window.getComputedStyle(target).cursor;
const mousemove = (mouseMoveEvent: MouseEvent) => {
let movement = 0;
if (["top", "bottom"].includes(props.side)) {
movement =
(mouseMoveEvent.clientY - startY) * (props.side === "top" ? -1 : 1) * props.resizeSensitivity;
} else {
movement =
(mouseMoveEvent.clientX - startX) * (props.side === "left" ? -1 : 1) * props.resizeSensitivity;
}
let newDimension = startDimension + movement;
// clamp width between min and max
newDimension = Math.min(Math.max(props.minDimension, newDimension), props.maxDimension);
emit("resize", newDimension);
dragActive.value = true;
mouseMoveEvent.preventDefault();
};
document.addEventListener("mousemove", mousemove);
document.addEventListener(
"mouseup",
(mouseUpEvent) => {
document.body.style.cursor = docCursor;
document.removeEventListener("mousemove", mousemove);
dragActive.value = false;
mouseUpEvent.preventDefault();
},
{ once: true },
);
}
</script>
|
2302_79757062/builder
|
frontend/src/components/PanelResizer.vue
|
Vue
|
agpl-3.0
| 2,286
|
<template>
<div class="items-top relative flex justify-between">
<InputLabel class="items-center">Placement</InputLabel>
<div class="relative h-fit w-fit">
<div class="group grid grid-cols-3 rounded-sm bg-gray-200 p-1.5 dark:bg-zinc-800">
<div
v-for="option in placementOptions"
:key="option"
class="group/option flex h-5 w-5 cursor-pointer items-center justify-center opacity-50"
:class="{
'!justify-start': option.includes('left'),
'!justify-end': option.includes('right'),
'!items-start': option.includes('top'),
'!items-end': option.includes('bottom'),
}">
<div
@click="setAlignment(option)"
@dblclick="setAlignment(option, true)"
class="hidden gap-[2px] opacity-0 hover:opacity-100 group-hover/option:flex"
:class="{
'flex-row': direction === 'row',
'flex-col': direction === 'column',
'items-center':
(direction === 'column' &&
(option === 'top-middle' || option === 'middle-middle' || option === 'bottom-middle')) ||
(direction === 'row' &&
(option === 'middle-left' || option === 'middle-middle' || option === 'middle-right')),
'items-end':
(direction === 'column' &&
(option === 'top-right' || option === 'middle-right' || option === 'bottom-right')) ||
(direction === 'row' &&
(option === 'bottom-left' || option === 'bottom-middle' || option === 'bottom-right')),
}">
<div
class="rounded-sm bg-gray-500 dark:bg-zinc-500"
:class="{
'h-2 w-1': direction === 'row',
'h-1 w-2': direction === 'column',
}"></div>
<div
class="rounded-sm bg-gray-500 dark:bg-zinc-500"
:class="{
'h-3 w-1': direction === 'row',
'h-1 w-3': direction === 'column',
}"></div>
<div
class="rounded-sm bg-gray-500 dark:bg-zinc-500"
:class="{
'h-2 w-1': direction === 'row',
'h-1 w-2': direction === 'column',
}"></div>
</div>
</div>
</div>
<div
class="pointer-events-none absolute top-0 flex h-full w-full cursor-pointer gap-[2px] rounded-sm p-1.5"
:style="{
'flex-direction': direction,
'justify-content': justifyContent,
'align-items': alignItems,
}">
<div
class="rounded-sm bg-gray-600 dark:bg-zinc-400"
:class="{
'h-1 w-2': direction === 'column',
'h-2 w-1': direction === 'row',
}"></div>
<div
class="rounded-sm bg-gray-600 dark:bg-zinc-400"
:class="{
'h-1 w-3': direction === 'column',
'h-3 w-1': direction === 'row',
}"></div>
<div
class="rounded-sm bg-gray-600 dark:bg-zinc-400"
:class="{
'h-1 w-2': direction === 'column',
'h-2 w-1': direction === 'row',
}"></div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import blockController from "@/utils/blockController";
import { computed } from "vue";
import InputLabel from "./InputLabel.vue";
const placementOptions = [
"top-left",
"top-middle",
"top-right",
"middle-left",
"middle-middle",
"middle-right",
"bottom-left",
"bottom-middle",
"bottom-right",
];
const direction = computed(() => blockController.getStyle("flexDirection") as string);
const justifyContent = computed(() => blockController.getStyle("justifyContent") as string);
const alignItems = computed(() => blockController.getStyle("alignItems") as string);
const setAlignment = (alignment: string, spaceBetween: boolean = false) => {
switch (alignment) {
case "top-right":
blockController.setStyle("justifyContent", direction.value === "row" ? "flex-end" : "flex-start");
blockController.setStyle("alignItems", direction.value === "row" ? "flex-start" : "flex-end");
break;
case "top-middle":
blockController.setStyle("justifyContent", direction.value === "row" ? "center" : "flex-start");
blockController.setStyle("alignItems", direction.value === "row" ? "flex-start" : "center");
break;
case "top-left":
blockController.setStyle("justifyContent", "flex-start");
blockController.setStyle("alignItems", "flex-start");
break;
case "middle-right":
blockController.setStyle("justifyContent", direction.value === "row" ? "flex-end" : "center");
blockController.setStyle("alignItems", direction.value === "row" ? "center" : "flex-end");
break;
case "middle-middle":
blockController.setStyle("justifyContent", "center");
blockController.setStyle("alignItems", "center");
break;
case "middle-left":
blockController.setStyle("justifyContent", direction.value === "row" ? "flex-start" : "center");
blockController.setStyle("alignItems", direction.value === "row" ? "center" : "flex-start");
break;
case "bottom-right":
blockController.setStyle("justifyContent", "flex-end");
blockController.setStyle("alignItems", "flex-end");
break;
case "bottom-middle":
blockController.setStyle("justifyContent", direction.value === "row" ? "center" : "flex-end");
blockController.setStyle("alignItems", direction.value === "row" ? "flex-end" : "center");
break;
case "bottom-left":
blockController.setStyle("justifyContent", direction.value === "row" ? "flex-start" : "flex-end");
blockController.setStyle("alignItems", direction.value === "row" ? "flex-end" : "flex-start");
break;
}
if (spaceBetween) {
blockController.setStyle("justifyContent", "space-between");
}
};
</script>
|
2302_79757062/builder
|
frontend/src/components/PlacementControl.vue
|
Vue
|
agpl-3.0
| 5,454
|
<template>
<div></div>
</template>
<script setup></script>
<style>
@font-face {
font-family: "InterVar";
font-weight: 100 900;
font-display: swap;
font-style: normal;
src:
url("/assets/builder/fonts/Inter/Inter.var.woff2?v=3.19") format("woff2-variations"),
url("/assets/builder/fonts/Inter/Inter.var.woff2?v=3.19") format("woff2");
src: url("/assets/builder/fonts/Inter/Inter.var.woff2?v=3.19") format("woff2") tech("variations");
}
@font-face {
font-family: "InterVar";
font-weight: 100 900;
font-display: swap;
font-style: italic;
src:
url("/assets/builder/fonts/Inter/Inter-Italic.var.woff2?v=3.19") format("woff2-variations"),
url("/assets/builder/fonts/Inter/Inter-Italic.var.woff2?v=3.19") format("woff2");
src: url("/assets/builder/fonts/Inter/Inter-Italic.var.woff2?v=3.19") format("woff2") tech("variations");
}
@tailwind base;
@layer base {
ul,
ol {
list-style: revert;
padding: revert;
}
}
p:empty:before {
content: "";
display: inline-block;
}
.__text_block__ {
overflow-wrap: break-word;
}
.__text_block__ a {
color: var(--link-color);
text-decoration: underline;
background-color: transparent;
}
</style>
|
2302_79757062/builder
|
frontend/src/components/Reset.vue
|
Vue
|
agpl-3.0
| 1,158
|
<template>
<div
class="group relative mr-2 w-full overflow-hidden rounded-md shadow hover:cursor-pointer dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200"
@click="() => $emit('click', page)">
<img
width="250"
height="140"
:src="page.preview"
onerror="this.src='/assets/builder/images/fallback.png'"
class="w-full overflow-hidden rounded-lg bg-gray-50 object-cover p-2 dark:bg-zinc-900" />
<div class="flex items-center justify-between border-t-[1px] px-3 dark:border-zinc-800">
<span class="inline-block max-w-[160px] py-2 text-sm text-gray-700 dark:text-zinc-200">
<div class="flex items-center gap-1">
<p class="truncate">
{{ page.template_name || page.page_title || page.page_name }}
</p>
</div>
</span>
<router-link
:key="page.page_name"
@click.stop="() => $emit('click', null)"
:to="{ name: 'builder', params: { pageId: page.page_name } }"
v-if="is_developer_mode">
<FeatherIcon name="edit" class="h-4 w-4 text-gray-500 hover:text-gray-700"></FeatherIcon>
</router-link>
</div>
</div>
</template>
<script setup lang="ts">
import { BuilderPage } from "@/types/Builder/BuilderPage";
const is_developer_mode = window.is_developer_mode;
defineProps<{
page: BuilderPage;
}>();
</script>
|
2302_79757062/builder
|
frontend/src/components/TemplatePagePreview.vue
|
Vue
|
agpl-3.0
| 1,281
|
<template>
<div class="flex min-h-[50vh] flex-wrap gap-6">
<div
@click="() => loadPage('new')"
class="group relative mr-2 h-fit w-full max-w-[250px] flex-grow basis-52 overflow-hidden rounded-md shadow hover:cursor-pointer dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200">
<img
width="250"
height="140"
:src="'/assets/builder/images/fallback.png'"
class="w-full overflow-hidden rounded-lg bg-gray-50 object-cover p-2 dark:bg-zinc-900" />
<div class="flex items-center justify-between border-t-[1px] px-3 dark:border-zinc-800">
<span class="inline-block max-w-[160px] py-2 text-sm text-gray-700 dark:text-zinc-200">
<div class="flex items-center gap-1">
<p class="truncate">Blank</p>
</div>
</span>
</div>
</div>
<TemplatePagePreview
class="h-fit max-w-[250px] flex-grow basis-52"
v-for="page in templates.data"
:page="page"
@click="(p) => duplicatePage(p)"></TemplatePagePreview>
</div>
</template>
<script setup lang="ts">
import { templates, webPages } from "@/data/webPage";
import router from "@/router";
import { BuilderPage } from "@/types/Builder/BuilderPage";
import { createDocumentResource } from "frappe-ui";
import TemplatePagePreview from "./TemplatePagePreview.vue";
const emit = defineEmits(["templateSelected"]);
const loadPage = async (pageName: string = "new") => {
emit("templateSelected", null);
await new Promise((resolve) => setTimeout(resolve, 500));
router.push({ name: "builder", params: { pageId: pageName } });
};
const duplicatePage = async (page?: BuilderPage) => {
if (!page) {
return emit("templateSelected", null);
}
const webPageResource = await createDocumentResource({
doctype: "Builder Page",
name: page.page_name,
auto: true,
});
await webPageResource.get.promise;
const pageCopy = webPageResource.doc as BuilderPage;
pageCopy.page_title = `${pageCopy.page_title}`;
pageCopy.is_template = 0;
const newPage = await webPages.insert.submit(pageCopy);
loadPage(newPage.name);
};
</script>
|
2302_79757062/builder
|
frontend/src/components/TemplateSelector.vue
|
Vue
|
agpl-3.0
| 2,031
|
<template>
<component
:is="block.getTag()"
ref="component"
@click.stop
@dblclick.stop
:key="editor"
class="__text_block__ shrink-0">
<div v-html="textContent" v-show="!editor && textContent" @click="handleClick"></div>
<bubble-menu
ref="menu"
:editor="editor"
:tippy-options="{
appendTo: overlayElement,
onCreate: (instance) => {
watch(
() => canvasProps,
() => {
if (canvasProps?.panning || canvasProps?.scaling) {
instance.hide();
} else {
instance.show();
}
},
{ deep: true },
);
},
}"
v-if="editor"
class="z-50 rounded-md border border-gray-300 bg-white p-1 text-lg shadow-2xl">
<div v-if="settingLink" class="flex">
<Input
v-model="textLink"
placeholder="https://example.com"
class="link-input w-56 text-sm"
@keydown.enter="
() => {
if (!linkInput) return;
setLink(linkInput?.getInputValue());
}
"
ref="linkInput" />
<Button @click="() => setLink(linkInput?.getInputValue())" class="ml-1">
<FeatherIcon class="h-3 w-3" name="check" />
</Button>
<Button
@click="
() => {
textLink = '';
setLink(null);
}
"
class="ml-1">
<FeatherIcon class="h-3 w-3" name="x" />
</Button>
</div>
<div v-show="!settingLink" class="flex gap-1">
<button
@click="setHeading(1)"
class="rounded px-2 py-1 text-sm hover:bg-gray-100"
:class="{ 'bg-gray-200': block.getElement() === 'h1' }">
<code>H1</code>
</button>
<button
@click="setHeading(2)"
class="rounded px-2 py-1 text-sm hover:bg-gray-100"
:class="{ 'bg-gray-200': block.getElement() === 'h2' }">
<code>H2</code>
</button>
<button
@click="setHeading(3)"
class="rounded px-2 py-1 text-sm hover:bg-gray-100"
:class="{ 'bg-gray-200': block.getElement() === 'h3' }">
<code>H3</code>
</button>
<button
v-show="!block.isHeader()"
@click="editor?.chain().focus().toggleBold().run()"
class="rounded px-2 py-1 hover:bg-gray-100"
:class="{ 'bg-gray-200': editor.isActive('bold') }">
<FeatherIcon class="h-3 w-3" name="bold" />
</button>
<button
v-show="!block.isHeader()"
@click="editor?.chain().focus().toggleItalic().run()"
class="rounded px-2 py-1 hover:bg-gray-100"
:class="{ 'bg-gray-200': editor.isActive('italic') }">
<FeatherIcon class="h-3 w-3" name="italic" />
</button>
<button
v-show="!block.isHeader()"
@click="editor?.chain().focus().toggleStrike().run()"
class="rounded px-2 py-1 hover:bg-gray-100"
:class="{ 'bg-gray-200': editor.isActive('strike') }">
<StrikeThroughIcon />
</button>
<button
v-show="!block.isHeader()"
@click="
() => {
if (!editor) return;
enableLinkInput();
}
"
class="rounded px-2 py-1 hover:bg-gray-100"
:class="{ 'bg-gray-200': editor.isActive('link') }">
<FeatherIcon class="h-3 w-3" name="link" />
</button>
</div>
</bubble-menu>
<editor-content
@click="handleClick"
:editor="editor"
v-if="editor && showEditor"
class="relative z-50"
@keydown="handleKeydown" />
<slot />
</component>
</template>
<script setup lang="ts">
import useStore from "@/store";
import Block from "@/utils/block";
import blockController from "@/utils/blockController";
import { setFontFromHTML } from "@/utils/fontManager";
import { getDataForKey } from "@/utils/helpers";
import { Color } from "@tiptap/extension-color";
import { FontFamily } from "@tiptap/extension-font-family";
import { Link } from "@tiptap/extension-link";
import TextStyle from "@tiptap/extension-text-style";
import StarterKit from "@tiptap/starter-kit";
import { BubbleMenu, Editor, EditorContent, Extension } from "@tiptap/vue-3";
import { Input } from "frappe-ui";
import { Plugin, PluginKey } from "prosemirror-state";
import { Ref, computed, inject, nextTick, onBeforeMount, onBeforeUnmount, ref, watch } from "vue";
import StrikeThroughIcon from "./Icons/StrikeThrough.vue";
const store = useStore();
const dataChanged = ref(false);
const settingLink = ref(false);
const textLink = ref("");
const linkInput = ref(null) as Ref<typeof Input | null>;
const component = ref(null) as Ref<HTMLElement | null>;
const overlayElement = document.querySelector("#overlay") as HTMLElement;
let editor: Ref<Editor | null> = ref(null);
const props = defineProps({
block: {
type: Block,
required: true,
},
preview: {
type: Boolean,
default: false,
},
data: {
type: Object,
default: () => ({}),
},
});
const canvasProps = !props.preview ? (inject("canvasProps") as CanvasProps) : null;
const FontFamilyPasteRule = Extension.create({
name: "fontFamilyPasteRule",
addProseMirrorPlugins() {
return [
new Plugin({
key: new PluginKey("fontFamilyPasteRule"),
props: {
transformPastedHTML(html) {
const div = document.createElement("div");
div.innerHTML = html;
const removeFontFamily = (element: HTMLElement) => {
if (element.style) {
element.style.fontFamily = "";
}
for (let i = 0; i < element.children.length; i++) {
removeFontFamily(element.children[i] as HTMLElement);
}
};
removeFontFamily(div);
return div.innerHTML;
},
},
}),
];
},
});
const textContent = computed(() => {
let innerHTML = props.block.getInnerHTML();
if (props.data) {
if (props.block.getDataKey("property") === "innerHTML") {
innerHTML = getDataForKey(props.data, props.block.getDataKey("key")) || innerHTML;
}
}
return String(innerHTML ?? "");
});
const isEditable = computed(() => {
return store.editableBlock === props.block;
});
const showEditor = computed(() => {
return !((props.block.isLink() || props.block.isButton()) && props.block.hasChildren());
});
onBeforeMount(() => {
let html = props.block.getInnerHTML() || "";
setFontFromHTML(html);
});
watch(
() => isEditable.value,
(editable) => {
editor.value?.setEditable(editable);
if (editable) {
store.activeCanvas?.history.pause();
editor.value?.commands.focus("all");
} else {
store.activeCanvas?.history.resume(dataChanged.value);
dataChanged.value = false;
}
},
{ immediate: true },
);
watch(
() => textContent.value,
(newValue, oldValue) => {
const isSame = newValue === editor.value?.getHTML();
if (isSame) {
return;
}
editor.value?.commands.setContent(newValue || "", false);
},
);
if (!props.preview) {
watch(
() => store.activeCanvas?.isSelected(props.block),
() => {
// only load editor if block is selected for performance reasons
if (store.activeCanvas?.isSelected(props.block) && !blockController.multipleBlocksSelected()) {
editor.value = new Editor({
content: textContent.value,
extensions: [
StarterKit,
TextStyle,
Color,
FontFamily,
Link.configure({
openOnClick: false,
}),
FontFamilyPasteRule,
],
enablePasteRules: false,
onUpdate({ editor }) {
let innerHTML = editor.isEmpty ? "" : editor.getHTML();
if (
props.block.isHeader() &&
!(
editor.isActive("heading", { level: 1 }) ||
editor.isActive("heading", { level: 2 }) ||
editor.isActive("heading", { level: 3 })
)
) {
innerHTML = editor.getText();
}
if (props.block.getInnerHTML() === innerHTML) {
return;
}
dataChanged.value = true;
props.block.setInnerHTML(innerHTML);
},
onSelectionUpdate: ({ editor }) => {
settingLink.value = false;
textLink.value = "";
},
autofocus: false,
injectCSS: false,
});
// @ts-ignore
props.block.__proto__.editor = editor.value;
editor.value?.setEditable(isEditable.value);
} else {
editor.value?.destroy();
editor.value = null;
// @ts-ignore
props.block.__proto__.editor = null;
}
},
{ immediate: true },
);
onBeforeUnmount(() => {
editor.value?.destroy();
});
}
const handleKeydown = (e: KeyboardEvent) => {
if (e.key === "k" && e.metaKey) {
enableLinkInput();
}
};
const enableLinkInput = () => {
settingLink.value = true;
// check if link is already set on selection
const link = editor.value?.isActive("link") ? editor.value?.getAttributes("link").href : null;
textLink.value = link || "";
nextTick(() => {
if (linkInput.value) {
const input = document.querySelector(".link-input") as HTMLInputElement;
input.focus();
}
});
};
const setLink = (value: string | null) => {
if (!value && !textLink.value) {
editor.value?.chain().focus().unsetLink().run();
} else {
editor.value
?.chain()
.focus()
.setLink({ href: value || textLink.value })
.run();
textLink.value = "";
}
settingLink.value = false;
};
const setHeading = (level: 1 | 2 | 3) => {
props.block.setBaseStyle("font-size", level === 1 ? "2rem" : level === 2 ? "1.5rem" : "1.25rem");
props.block.setBaseStyle("font-weight", "bold");
const tag = `h${level}`;
if (props.block.element === tag) {
props.block.element = "p";
} else {
props.block.element = tag;
}
nextTick(() => {
props.block.selectBlock();
});
};
const handleClick = (e: MouseEvent) => {
if (isEditable.value) {
e.stopPropagation();
}
};
defineExpose({
component,
});
</script>
<style>
.__text_block__ [contenteditable="true"] {
caret-color: currentcolor !important;
}
</style>
|
2302_79757062/builder
|
frontend/src/components/TextBlock.vue
|
Vue
|
agpl-3.0
| 9,512
|
import { createListResource } from "frappe-ui";
const builderBlockTemplate = createListResource({
method: "GET",
doctype: "Block Template",
fields: ["template_name", "category", "preview", "block", "name"],
orderBy: "modified desc",
cache: "block_template",
start: 0,
pageLength: 100,
auto: true,
});
export default builderBlockTemplate;
|
2302_79757062/builder
|
frontend/src/data/builderBlockTemplate.ts
|
TypeScript
|
agpl-3.0
| 348
|
import { createDocumentResource } from "frappe-ui";
const builderSettings = createDocumentResource({
doctype: "Builder Settings",
name: "Builder Settings",
});
export { builderSettings };
|
2302_79757062/builder
|
frontend/src/data/builderSettings.ts
|
TypeScript
|
agpl-3.0
| 192
|
import { createListResource } from "frappe-ui";
const webComponent = createListResource({
method: "GET",
doctype: "Builder Component",
fields: ["component_name", "block", "name", "for_web_page", "component_id"],
orderBy: "modified desc",
cache: "components",
start: 0,
pageLength: 100,
auto: true,
});
export default webComponent;
|
2302_79757062/builder
|
frontend/src/data/webComponent.ts
|
TypeScript
|
agpl-3.0
| 341
|
import { createListResource } from "frappe-ui";
const webPages = createListResource({
method: "GET",
doctype: "Builder Page",
fields: [
"name",
"route",
"page_name",
"preview",
"page_title",
"creation",
"published",
"dynamic_route",
"modified_by",
"modified",
"is_template",
"owner",
],
filters: {
is_template: 0,
},
auto: true,
cache: "pages",
orderBy: "modified desc",
pageLength: 50,
});
const templates = createListResource({
method: "GET",
doctype: "Builder Page",
fields: [
"name",
"route",
"blocks",
"page_name",
"preview",
"page_title",
"creation",
"published",
"dynamic_route",
"modified",
"is_template",
"template_name",
"owner",
],
filters: {
is_template: 1,
},
cache: "templates",
orderBy: "modified desc",
pageLength: 50,
auto: true,
});
export { templates, webPages };
|
2302_79757062/builder
|
frontend/src/data/webPage.ts
|
TypeScript
|
agpl-3.0
| 859
|
@import "frappe-ui/src/style.css";
@layer base {
ul,
ol {
list-style: revert;
padding: revert;
}
}
/* to match style of tip tap editor for new lines */
p:empty::before {
content: "";
display: inline-block;
}
.__text_block__ {
overflow-wrap: break-word;
}
.__text_block__ a {
color: var(--link-color);
text-decoration: underline;
background-color: transparent;
}
@layer utilities {
/* Chrome, Safari and Opera */
.no-scrollbar::-webkit-scrollbar {
display: none;
}
.no-scrollbar {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none;
}
}
|
2302_79757062/builder
|
frontend/src/index.css
|
CSS
|
agpl-3.0
| 581
|
import { Button, Dialog, FeatherIcon, FormControl, FrappeUI } from "frappe-ui";
import { createPinia } from "pinia";
import { createApp } from "vue";
import "./index.css";
import router from "./router";
import "./setupFrappeUIResource";
import "./telemetry";
import "./utils/arrayFunctions";
import App from "@/App.vue";
const app = createApp(App);
const pinia = createPinia();
app.use(router);
app.use(FrappeUI);
app.use(pinia);
window.name = "frappe-builder";
app.component("Button", Button);
app.component("FormControl", FormControl);
app.component("Dialog", Dialog);
app.component("FeatherIcon", FeatherIcon);
app.mount("#app");
declare global {
interface Window {
is_developer_mode?: boolean;
}
}
window.is_developer_mode = process.env.NODE_ENV === "development";
|
2302_79757062/builder
|
frontend/src/main.ts
|
TypeScript
|
agpl-3.0
| 780
|
<template>
<div class="page-builder h-screen flex-col overflow-hidden bg-gray-100 dark:bg-zinc-800">
<BuilderToolbar class="relative z-30"></BuilderToolbar>
<div>
<BuilderLeftPanel
v-show="store.showLeftPanel"
class="no-scrollbar absolute bottom-0 left-0 top-[var(--toolbar-height)] z-20 overflow-auto border-r-[1px] bg-white shadow-lg dark:border-gray-800 dark:bg-zinc-900"></BuilderLeftPanel>
<BuilderCanvas
ref="fragmentCanvas"
:key="store.fragmentData.block?.blockId"
v-if="store.editingMode === 'fragment' && store.fragmentData.block"
:block-data="store.fragmentData.block"
:canvas-styles="{
width: (store.fragmentData.block.getStyle('width') + '').endsWith('px') ? '!fit-content' : null,
padding: '40px',
}"
:style="{
left: `${store.showLeftPanel ? store.builderLayout.leftPanelWidth : 0}px`,
right: `${store.showRightPanel ? store.builderLayout.rightPanelWidth : 0}px`,
}"
class="canvas-container absolute bottom-0 top-[var(--toolbar-height)] flex justify-center overflow-hidden bg-gray-400 p-10 dark:bg-zinc-700">
<template v-slot:header>
<div
class="absolute left-0 right-0 top-0 z-20 flex items-center justify-between bg-white p-2 text-sm text-gray-800 dark:bg-zinc-900 dark:text-zinc-400">
<div class="flex items-center gap-1 text-xs">
<a @click="store.exitFragmentMode" class="cursor-pointer">Page</a>
<FeatherIcon name="chevron-right" class="h-3 w-3" />
{{ store.fragmentData.fragmentName }}
</div>
<Button
class="text-xs dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700"
@click="saveAndExitFragmentMode">
{{ store.fragmentData.saveActionLabel || "Save" }}
</Button>
</div>
</template>
</BuilderCanvas>
<BuilderCanvas
v-show="store.editingMode === 'page'"
ref="pageCanvas"
v-if="store.pageBlocks[0]"
:block-data="store.pageBlocks[0]"
:canvas-styles="{
minHeight: '1000px',
}"
:style="{
left: `${store.showLeftPanel ? store.builderLayout.leftPanelWidth : 0}px`,
right: `${store.showRightPanel ? store.builderLayout.rightPanelWidth : 0}px`,
}"
class="canvas-container absolute bottom-0 top-[var(--toolbar-height)] flex justify-center overflow-hidden bg-gray-200 p-10 dark:bg-zinc-800"></BuilderCanvas>
<BuilderRightPanel
v-show="store.showRightPanel"
class="no-scrollbar absolute bottom-0 right-0 top-[var(--toolbar-height)] z-20 overflow-auto border-l-[1px] bg-white shadow-lg dark:border-gray-800 dark:bg-zinc-900"></BuilderRightPanel>
<Dialog
style="z-index: 40"
v-model="store.showHTMLDialog"
class="overscroll-none"
:options="{
title: 'HTML Code',
size: '6xl',
}">
<template #body-content>
<CodeEditor
:modelValue="store.editableBlock?.getInnerHTML()"
type="HTML"
height="60vh"
:showLineNumbers="true"
:showSaveButton="true"
@save="
(val) => {
store.editableBlock?.setInnerHTML(val);
store.showHTMLDialog = false;
}
"
required />
</template>
</Dialog>
</div>
</div>
</template>
<script setup lang="ts">
import BuilderCanvas from "@/components/BuilderCanvas.vue";
import BuilderLeftPanel from "@/components/BuilderLeftPanel.vue";
import BuilderRightPanel from "@/components/BuilderRightPanel.vue";
import BuilderToolbar from "@/components/BuilderToolbar.vue";
import webComponent from "@/data/webComponent";
import { webPages } from "@/data/webPage";
import { sessionUser } from "@/router";
import useStore from "@/store";
import { BuilderComponent } from "@/types/Builder/BuilderComponent";
import { BuilderPage } from "@/types/Builder/BuilderPage";
import { getUsersInfo } from "@/usersInfo";
import Block, { styleProperty } from "@/utils/block";
import blockController from "@/utils/blockController";
import getBlockTemplate from "@/utils/blockTemplate";
import {
addPxToNumber,
copyToClipboard,
detachBlockFromComponent,
getBlockCopy,
getCopyWithoutParent,
isCtrlOrCmd,
isHTMLString,
isJSONString,
isTargetEditable,
} from "@/utils/helpers";
import { useActiveElement, useDebounceFn, useEventListener, useMagicKeys, useStorage } from "@vueuse/core";
import { Dialog } from "frappe-ui";
import { Ref, computed, onActivated, onDeactivated, provide, ref, watch, watchEffect } from "vue";
import { useRoute, useRouter } from "vue-router";
import { toast } from "vue-sonner";
import CodeEditor from "../components/CodeEditor.vue";
const route = useRoute();
const router = useRouter();
const store = useStore();
declare global {
interface Window {
store: typeof store;
blockController: typeof blockController;
}
}
window.store = store;
window.blockController = blockController;
const pageCanvas = ref<InstanceType<typeof BuilderCanvas> | null>(null);
const fragmentCanvas = ref<InstanceType<typeof BuilderCanvas> | null>(null);
provide("pageCanvas", pageCanvas);
provide("fragmentCanvas", fragmentCanvas);
// to disable page zoom
useEventListener(
document,
"wheel",
(event) => {
const { ctrlKey } = event;
if (ctrlKey) {
event.preventDefault();
return;
}
},
{ passive: false },
);
useEventListener(document, "copy", (e) => {
if (isTargetEditable(e)) return;
e.preventDefault();
if (store.activeCanvas?.selectedBlocks.length) {
const componentDocuments: BuilderComponent[] = [];
store.activeCanvas?.selectedBlocks.forEach((block: Block) => {
const components = block.getUsedComponentNames();
components.forEach((componentName) => {
const component = store.getComponent(componentName);
if (component) {
componentDocuments.push(component);
}
});
});
const blocksToCopy = store.activeCanvas?.selectedBlocks.map((block) => {
if (!Boolean(block.extendedFromComponent) && block.isChildOfComponent) {
return detachBlockFromComponent(block);
}
return getCopyWithoutParent(block);
});
// just copy non components
const dataToCopy = {
blocks: blocksToCopy,
components: componentDocuments,
};
copyToClipboard(dataToCopy, e, "builder-copied-blocks");
}
});
useEventListener(document, "paste", async (e) => {
if (isTargetEditable(e)) return;
e.stopPropagation();
const clipboardItems = Array.from(e.clipboardData?.items || []);
// paste image from clipboard
if (clipboardItems.some((item) => item.type.includes("image"))) {
e.preventDefault();
const file = clipboardItems.find((item) => item.type.includes("image"))?.getAsFile();
if (file) {
store.uploadFile(file).then((res: { fileURL: string; fileName: string }) => {
const selectedBlocks = blockController.getSelectedBlocks();
const parentBlock = selectedBlocks.length
? selectedBlocks[0]
: (store.activeCanvas?.getFirstBlock() as Block);
let imageBlock = null as unknown as Block;
if (parentBlock.isImage()) {
imageBlock = parentBlock;
} else {
imageBlock = parentBlock.addChild(getBlockCopy(getBlockTemplate("image")));
}
imageBlock.setAttribute("src", res.fileURL);
});
}
return;
}
const data = e.clipboardData?.getData("builder-copied-blocks") as string;
// paste blocks directly
if (data && isJSONString(data)) {
const dataObj = JSON.parse(data) as { blocks: Block[]; components: BuilderComponent[] };
for (const component of dataObj.components) {
delete component.for_web_page;
await store.createComponent(component, true);
}
if (store.activeCanvas?.selectedBlocks.length && dataObj.blocks[0].blockId !== "root") {
let parentBlock = store.activeCanvas.selectedBlocks[0];
while (parentBlock && !parentBlock.canHaveChildren()) {
parentBlock = parentBlock.getParentBlock() as Block;
}
dataObj.blocks.forEach((block: BlockOptions) => {
parentBlock.addChild(getBlockCopy(block), null, true);
});
} else {
store.pushBlocks(dataObj.blocks);
}
// check if data is from builder and a list of blocks and components
// if yes then create components and then blocks
return;
}
let text = e.clipboardData?.getData("text/plain") as string;
if (!text) {
return;
}
if (isHTMLString(text)) {
e.preventDefault();
// paste html
if (blockController.isHTML()) {
blockController.setInnerHTML(text);
} else {
let block = null as unknown as Block | BlockOptions;
block = getBlockTemplate("html");
if (text.startsWith("<svg")) {
if (text.includes("<image")) {
toast.warning("Warning", {
description: "SVG with inlined image in it is not supported. Please paste it as PNG instead.",
});
return;
}
const dom = new DOMParser().parseFromString(text, "text/html");
const svg = dom.body.querySelector("svg") as SVGElement;
const width = svg.getAttribute("width") || "100";
const height = svg.getAttribute("height") || "100";
if (width && block.baseStyles) {
block.baseStyles.width = addPxToNumber(parseInt(width));
svg.removeAttribute("width");
}
if (height && block.baseStyles) {
block.baseStyles.height = addPxToNumber(parseInt(height));
svg.removeAttribute("height");
}
text = svg.outerHTML;
}
block.innerHTML = text;
const parentBlock = blockController.getSelectedBlocks()[0];
if (parentBlock) {
parentBlock.addChild(block);
} else {
store.pushBlocks([block]);
}
}
return;
}
// try pasting figma text styles
if (text.includes(":") && !store.editableBlock) {
e.preventDefault();
// strip out all comments: line-height: 115%; /* 12.65px */ -> line-height: 115%;
const strippedText = text.replace(/\/\*.*?\*\//g, "").replace(/\n/g, "");
const styleObj = strippedText.split(";").reduce((acc: BlockStyleMap, curr) => {
const [key, value] = curr.split(":").map((item) => (item ? item.trim() : "")) as [
styleProperty,
StyleValue,
];
if (blockController.isText() && !blockController.isLink()) {
if (
[
"font-family",
"font-size",
"font-weight",
"line-height",
"letter-spacing",
"text-align",
"text-transform",
"color",
].includes(key)
) {
if (key === "font-family") {
acc[key] = (value + "").replace(/['"]+/g, "");
if (String(value).toLowerCase().includes("inter")) {
acc["font-family"] = "";
}
} else {
acc[key] = value;
}
}
} else if (["width", "height", "box-shadow", "background", "border-radius"].includes(key)) {
acc[key] = value;
}
return acc;
}, {});
Object.entries(styleObj).forEach(([key, value]) => {
blockController.setBaseStyle(key as styleProperty, value);
});
return;
}
// if selected block is container, create a new text block inside it and set the text
if (blockController.isContainer()) {
e.preventDefault();
const block = getBlockTemplate("text");
block.innerHTML = text;
blockController.getSelectedBlocks()[0].addChild(block);
return;
}
});
// TODO: Refactor with useMagicKeys
useEventListener(document, "keydown", (e) => {
if (isTargetEditable(e)) return;
if (e.key === "z" && isCtrlOrCmd(e) && !e.shiftKey && store.activeCanvas?.history.canUndo) {
store.activeCanvas?.history.undo();
e.preventDefault();
return;
}
if (e.key === "z" && e.shiftKey && isCtrlOrCmd(e) && store.activeCanvas?.history.canRedo) {
store.activeCanvas?.history.redo();
e.preventDefault();
return;
}
if (e.key === "0" && isCtrlOrCmd(e)) {
e.preventDefault();
if (pageCanvas.value) {
if (e.shiftKey) {
pageCanvas.value.setScaleAndTranslate();
} else {
pageCanvas.value.resetZoom();
}
}
return;
}
if (e.key === "ArrowRight" && !blockController.isBLockSelected()) {
e.preventDefault();
if (pageCanvas.value) {
pageCanvas.value.moveCanvas("right");
}
return;
}
if (e.key === "ArrowLeft" && !blockController.isBLockSelected()) {
e.preventDefault();
if (pageCanvas.value) {
pageCanvas.value.moveCanvas("left");
}
return;
}
if (e.key === "ArrowUp" && !blockController.isBLockSelected()) {
e.preventDefault();
if (pageCanvas.value) {
pageCanvas.value.moveCanvas("up");
}
return;
}
if (e.key === "ArrowDown" && !blockController.isBLockSelected()) {
e.preventDefault();
if (pageCanvas.value) {
pageCanvas.value.moveCanvas("down");
}
return;
}
if (e.key === "=" && isCtrlOrCmd(e)) {
e.preventDefault();
if (pageCanvas.value) {
pageCanvas.value.zoomIn();
}
return;
}
if (e.key === "-" && isCtrlOrCmd(e)) {
e.preventDefault();
if (pageCanvas.value) {
pageCanvas.value.zoomOut();
}
return;
}
if (isCtrlOrCmd(e) || e.shiftKey) {
return;
}
if (e.key === "c") {
store.mode = "container";
return;
}
if (e.key === "i") {
store.mode = "image";
return;
}
if (e.key === "t") {
store.mode = "text";
return;
}
if (e.key === "v") {
store.mode = "select";
return;
}
if (e.key === "h") {
store.mode = "move";
return;
}
});
const activeElement = useActiveElement();
const notUsingInput = computed(
() => activeElement.value?.tagName !== "INPUT" && activeElement.value?.tagName !== "TEXTAREA",
);
const { space } = useMagicKeys({
passive: false,
onEventFired(e) {
if (e.key === " " && notUsingInput.value && !isTargetEditable(e)) {
e.preventDefault();
}
},
});
watch(space, (value) => {
if (value && !store.editableBlock) {
store.mode = "move";
} else if (store.mode === "move") {
store.mode = store.lastMode !== "move" ? store.lastMode : "select";
}
});
useEventListener(document, "keydown", (e) => {
if (e.key === "\\" && isCtrlOrCmd(e)) {
e.preventDefault();
if (e.shiftKey) {
store.showLeftPanel = !store.showLeftPanel;
} else {
store.showRightPanel = !store.showRightPanel;
store.showLeftPanel = store.showRightPanel;
}
}
// save page or component
if (e.key === "s" && isCtrlOrCmd(e)) {
e.preventDefault();
if (store.editingMode === "fragment") {
saveAndExitFragmentMode(e);
e.stopPropagation();
}
return;
}
if (e.key === "p" && isCtrlOrCmd(e)) {
e.preventDefault();
store.savePage();
router.push({
name: "preview",
params: {
pageId: store.selectedPage as string,
},
});
}
if (e.key === "c" && isCtrlOrCmd(e) && e.shiftKey) {
if (blockController.isBLockSelected() && !blockController.multipleBlocksSelected()) {
e.preventDefault();
const block = blockController.getSelectedBlocks()[0];
const copiedStyle = useStorage(
"copiedStyle",
{ blockId: "", style: {} },
sessionStorage,
) as Ref<StyleCopy>;
copiedStyle.value = {
blockId: block.blockId,
style: block.getStylesCopy(),
};
}
}
if (e.key === "d" && isCtrlOrCmd(e)) {
if (blockController.isBLockSelected() && !blockController.multipleBlocksSelected()) {
e.preventDefault();
const block = blockController.getSelectedBlocks()[0];
block.duplicateBlock();
}
}
if (isTargetEditable(e)) return;
if ((e.key === "Backspace" || e.key === "Delete") && blockController.isBLockSelected()) {
for (const block of blockController.getSelectedBlocks()) {
store.activeCanvas?.removeBlock(block);
}
clearSelection();
e.stopPropagation();
return;
}
if (e.key === "Escape") {
store.exitFragmentMode(e);
}
// handle arrow keys
if (e.key.startsWith("Arrow") && blockController.isBLockSelected()) {
const key = e.key.replace("Arrow", "").toLowerCase() as "up" | "down" | "left" | "right";
for (const block of blockController.getSelectedBlocks()) {
block.move(key);
}
}
});
const clearSelection = () => {
blockController.clearSelection();
store.editableBlock = null;
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur();
}
};
const saveAndExitFragmentMode = (e: Event) => {
store.fragmentData.saveAction?.(fragmentCanvas.value?.getFirstBlock());
fragmentCanvas.value?.toggleDirty(false);
store.exitFragmentMode(e);
};
onActivated(async () => {
store.realtime.on("doc_viewers", async (data) => {
store.viewers = await getUsersInfo(data.users.filter((user: string) => user !== sessionUser.value));
});
store.realtime.doc_subscribe("Builder Page", route.params.pageId as string);
store.realtime.doc_open("Builder Page", route.params.pageId as string);
if (route.params.pageId === store.selectedPage) {
return;
}
if (!webPages.data) {
await webPages.fetchOne.submit(route.params.pageId as string);
}
if (route.params.pageId && route.params.pageId !== "new") {
store.setPage(route.params.pageId as string);
} else {
await webPages.insert
.submit({
page_title: "My Page",
draft_blocks: [store.getRootBlock()],
})
.then((data: BuilderPage) => {
router.push({ name: "builder", params: { pageId: data.name }, force: true });
store.setPage(data.name);
});
}
});
onDeactivated(() => {
store.realtime.doc_close("Builder Page", store.activePage?.name as string);
store.realtime.off("doc_viewers", () => {});
store.viewers = [];
});
// on tab activation, reload for latest data
useEventListener(document, "visibilitychange", () => {
if (document.visibilityState === "visible" && !fragmentCanvas.value) {
if (route.params.pageId && route.params.pageId !== "new") {
const currentModified = webPages.getRow(store.activePage?.name as string)?.modified;
webComponent.reload();
webPages.fetchOne.submit(store.activePage?.name).then((doc: BuilderPage[]) => {
if (currentModified !== doc[0]?.modified) {
store.setPage(route.params.pageId as string, false);
}
});
}
}
});
watchEffect(() => {
if (fragmentCanvas.value) {
store.activeCanvas = fragmentCanvas.value;
} else {
store.activeCanvas = pageCanvas.value;
}
});
const debouncedPageSave = useDebounceFn(store.savePage, 300);
watch(
() => pageCanvas.value?.block,
() => {
if (
store.selectedPage &&
!store.settingPage &&
store.editingMode === "page" &&
!pageCanvas.value?.canvasProps?.settingCanvas
) {
store.savingPage = true;
debouncedPageSave();
}
},
{
deep: true,
},
);
watch(
() => store.showHTMLDialog,
(value) => {
if (!value) {
store.editableBlock = null;
}
},
);
</script>
<style>
.page-builder {
--left-panel-width: 17rem;
--right-panel-width: 20rem;
--toolbar-height: 3.5rem;
}
</style>
|
2302_79757062/builder
|
frontend/src/pages/PageBuilder.vue
|
Vue
|
agpl-3.0
| 18,222
|
<template>
<div
class="toolbar sticky top-0 z-10 flex h-14 items-center justify-center bg-white p-2 shadow-sm dark:border-b-[1px] dark:border-gray-800 dark:bg-zinc-900"
ref="toolbar">
<div class="absolute left-3 flex items-center">
<router-link class="flex items-center gap-2" :to="{ name: 'home' }">
<img src="/builder_logo.png" alt="logo" class="h-7" />
<h1 class="text-md mt-[2px] font-semibold leading-5 text-gray-800 dark:text-gray-200">Builder</h1>
</router-link>
</div>
</div>
<section class="max-w-800 m-auto mb-32 flex w-3/4 flex-col pt-10">
<div class="mb-6 flex items-center justify-between">
<h1 class="text-lg font-medium text-gray-900 dark:text-zinc-400">All Pages</h1>
<div class="flex gap-4">
<TabButtons
:buttons="[
{ label: 'Grid', value: 'grid' },
{ label: 'List', value: 'list' },
]"
v-model="displayType"
class="w-fit self-end [&>div>button[aria-checked='false']]:dark:!bg-transparent [&>div>button[aria-checked='false']]:dark:!text-zinc-400 [&>div>button[aria-checked='true']]:dark:!bg-zinc-700 [&>div>button]:dark:!bg-zinc-700 [&>div>button]:dark:!text-zinc-100 [&>div]:dark:!bg-zinc-900"></TabButtons>
<div class="relative flex">
<Input
class="w-44 [&>div>input]:dark:bg-zinc-900"
type="text"
placeholder="Filter by title or route"
v-model="searchFilter"
autofocus
@input="
(value: string) => {
searchFilter = value;
}
" />
</div>
<Input
type="select"
class="w-36 [&>div>select]:dark:bg-zinc-900"
v-model="typeFilter"
:options="[
{ label: 'All', value: '' },
{ label: 'Draft', value: 'draft' },
{ label: 'Published', value: 'published' },
{ label: 'Unpublished', value: 'unpublished' },
]" />
<!-- <Button variant="solid" icon-left="plus" @click="() => (showDialog = true)">New</Button> -->
<router-link
:to="{ name: 'builder', params: { pageId: 'new' } }"
@click="
() => {
posthog.capture('builder_new_page_created');
}
">
<Button variant="solid" icon-left="plus">New</Button>
</router-link>
</div>
</div>
<div class="grid-col grid gap-6 auto-fill-[220px]">
<div v-if="!webPages.data?.length && !searchFilter && !typeFilter" class="col-span-full">
<p class="mt-4 text-base text-gray-500">
You don't have any pages yet. Click on the "+ New" button to create a new page.
</p>
</div>
<div v-else-if="!webPages.data?.length" class="col-span-full">
<p class="mt-4 text-base text-gray-500">No matching pages found.</p>
</div>
<router-link
v-if="displayType === 'grid'"
v-for="page in webPages.data"
:key="page.page_name"
@click="
() => {
posthog.capture('builder_page_opened', { page_name: page.page_name });
}
"
:to="{ name: 'builder', params: { pageId: page.page_name } }">
<div
class="group relative mr-2 w-full overflow-hidden rounded-md shadow hover:cursor-pointer dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200">
<img
width="250"
height="140"
:src="page.preview"
onerror="this.src='/assets/builder/images/fallback.png'"
class="w-full overflow-hidden rounded-lg bg-gray-50 object-cover p-2 dark:bg-zinc-900" />
<div class="flex items-center justify-between border-t-[1px] px-3 dark:border-zinc-800">
<span class="inline-block max-w-[160px] py-2 text-sm text-gray-700 dark:text-zinc-200">
<div class="flex items-center gap-1">
<p class="truncate">
{{ page.page_title || page.page_name }}
</p>
</div>
<UseTimeAgo v-slot="{ timeAgo }" :time="page.modified">
<p class="mt-1 block text-xs text-gray-500">Edited {{ timeAgo }}</p>
</UseTimeAgo>
</span>
<Dropdown
:options="[
{
group: 'Actions',
hideLabel: true,
items: [
{ label: 'Duplicate', onClick: () => duplicatePage(page), icon: 'copy' },
{ label: 'View in Desk', onClick: () => store.openInDesk(page), icon: 'arrow-up-right' },
],
},
{
group: 'Delete',
hideLabel: true,
items: [{ label: 'Delete', onClick: () => deletePage(page), icon: 'trash' }],
},
]"
size="xs"
placement="right">
<template v-slot="{ open }">
<FeatherIcon
name="more-vertical"
class="h-4 w-4 text-gray-500 hover:text-gray-700"
@click="open"></FeatherIcon>
</template>
</Dropdown>
</div>
</div>
</router-link>
<router-link
v-for="page in webPages.data"
v-if="displayType === 'list'"
:key="page.page_name"
:to="{ name: 'builder', params: { pageId: page.page_name } }"
@click="
() => {
posthog.capture('builder_page_opened', { page_name: page.page_name });
}
"
class="col-span-full h-fit w-full flex-grow">
<div
class="group relative mr-2 flex w-full overflow-hidden rounded-md shadow hover:cursor-pointer dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200">
<img
width="250"
height="140"
:src="page.preview"
onerror="this.src='/assets/builder/images/fallback.png'"
class="block w-44 overflow-hidden rounded-lg bg-gray-50 object-cover p-2 dark:bg-zinc-900" />
<div class="flex flex-1 items-start justify-between border-t-[1px] p-3 px-3 dark:border-zinc-800">
<span class="flex h-full flex-col justify-between text-sm text-gray-700 dark:text-zinc-200">
<div>
<div class="flex items-center gap-1">
<p class="truncate">
{{ page.page_title || page.page_name }}
</p>
</div>
<div class="mt-2 flex items-center gap-1">
<FeatherIcon name="globe" class="h-3 w-3 text-gray-500 hover:text-gray-700"></FeatherIcon>
<p class="text-xs text-gray-600">
{{ page.route }}
</p>
</div>
</div>
<div class="flex items-baseline gap-1">
<p class="mt-1 block text-xs text-gray-500">Created By {{ page.owner }}</p>
·
<UseTimeAgo v-slot="{ timeAgo }" :time="page.modified">
<p class="mt-1 block text-xs text-gray-500">
Edited {{ timeAgo }} by {{ page.modified_by }}
</p>
</UseTimeAgo>
</div>
</span>
<div class="flex items-center gap-2">
<Badge theme="green" v-if="page.published" class="dark:bg-green-900 dark:text-green-400">
Published
</Badge>
<Dropdown
:options="[
{ label: 'Duplicate', onClick: () => duplicatePage(page), icon: 'copy' },
{ label: 'View in Desk', onClick: () => store.openInDesk(page), icon: 'arrow-up-right' },
{ label: 'Delete', onClick: () => deletePage(page), icon: 'trash' },
]"
size="sm"
placement="right">
<template v-slot="{ open }">
<FeatherIcon
name="more-vertical"
class="h-4 w-4 text-gray-500 hover:text-gray-700"
@click="open"></FeatherIcon>
</template>
</Dropdown>
</div>
</div>
</div>
</router-link>
</div>
<Button
class="m-auto mt-12 w-fit text-sm dark:bg-zinc-900 dark:text-zinc-300"
@click="loadMore"
v-show="webPages.hasNextPage"
variant="subtle"
size="sm">
Load More
</Button>
<Dialog
:options="{
title: 'Select Template',
size: '6xl',
}"
v-model="showDialog">
<template #body-content>
<TemplateSelector @templateSelected="showDialog = false"></TemplateSelector>
</template>
</Dialog>
</section>
</template>
<script setup lang="ts">
import Input from "@/components/Input.vue";
import TemplateSelector from "@/components/TemplateSelector.vue";
import { webPages } from "@/data/webPage";
import useStore from "@/store";
import { posthog } from "@/telemetry";
import { BuilderPage } from "@/types/Builder/BuilderPage";
import { confirm } from "@/utils/helpers";
import { UseTimeAgo } from "@vueuse/components";
import { useStorage, watchDebounced } from "@vueuse/core";
import { Badge, createDocumentResource, Dropdown, TabButtons } from "frappe-ui";
import { onActivated, Ref, ref } from "vue";
const store = useStore();
const displayType = useStorage("displayType", "grid") as Ref<"grid" | "list">;
const searchFilter = ref("");
const typeFilter = ref("");
const showDialog = ref(false);
onActivated(() => {
posthog.capture("builder_landing_page_visited");
});
watchDebounced(
[searchFilter, typeFilter],
() => {
const filters = {
is_template: 0,
} as any;
if (typeFilter.value) {
if (typeFilter.value === "published") {
filters["published"] = true;
} else if (typeFilter.value === "unpublished") {
filters["published"] = false;
} else if (typeFilter.value === "draft") {
filters["draft_blocks"] = ["is", "set"];
}
}
const orFilters = {} as any;
if (searchFilter.value) {
orFilters["page_title"] = ["like", `%${searchFilter.value}%`];
orFilters["route"] = ["like", `%${searchFilter.value}%`];
}
webPages.update({
filters,
orFilters,
});
webPages.fetch();
},
{ debounce: 300 },
);
const deletePage = async (page: BuilderPage) => {
const confirmed = await confirm(
`Are you sure you want to delete page: ${page.page_title || page.page_name}?`,
);
if (confirmed) {
await webPages.delete.submit(page.name);
}
};
const duplicatePage = async (page: BuilderPage) => {
const webPageResource = await createDocumentResource({
doctype: "Builder Page",
name: page.page_name,
auto: true,
});
await webPageResource.get.promise;
const pageCopy = webPageResource.doc as BuilderPage;
pageCopy.page_title = `${pageCopy.page_title} (Copy)`;
delete pageCopy.page_name;
delete pageCopy.route;
await webPages.insert.submit(pageCopy);
};
const loadMore = () => {
webPages.next();
};
</script>
|
2302_79757062/builder
|
frontend/src/pages/PageBuilderLanding.vue
|
Vue
|
agpl-3.0
| 9,925
|
<template>
<div class="flex h-screen flex-col items-center bg-gray-100 p-5 dark:bg-zinc-900">
<div class="relative flex w-full items-center justify-center">
<router-link
:to="{ name: 'builder', params: { pageId: route.params.pageId || 'new' } }"
class="absolute left-5 flex w-fit text-sm text-gray-600 hover:text-gray-900 dark:text-gray-400 hover:dark:text-gray-100">
<FeatherIcon name="arrow-left" class="mr-4 h-4 w-4 cursor-pointer" />
Back to builder
</router-link>
<div class="flex gap-1 text-gray-500 dark:bg-zinc-900 dark:text-zinc-500">
<div
class="w-auto cursor-pointer rounded-md p-1 px-[8px]"
v-for="breakpoint in deviceBreakpoints"
:key="breakpoint.device"
:class="{
'bg-white shadow-sm dark:bg-zinc-700': activeBreakpoint === breakpoint.device,
}"
@click.stop="() => setWidth(breakpoint.device)">
<FeatherIcon
:name="breakpoint.icon"
class="h-6 w-5"
:class="{
'text-gray-700 dark:text-zinc-50': activeBreakpoint === breakpoint.device,
}" />
</div>
</div>
<Button
variant="solid"
@click="
() => {
publishing = true;
store.publishPage().finally(() => (publishing = false));
}
"
class="absolute right-5 border-0 text-xs dark:bg-zinc-800"
:loading="publishing">
{{ publishing ? "Publishing" : "Publish" }}
</Button>
</div>
<div
class="relative mt-5 flex h-[85vh] bg-white"
:style="{
width: width + 'px',
}">
<PanelResizer
class="ml-[-12px]"
side="left"
:dimension="width"
:minDimension="minWidth"
:maxDimension="maxWidth"
:resizeSensitivity="2"
ref="leftPanelRef"
@resize="(val) => (width = val)">
<div class="resize-handler-left h-full w-2 rounded-sm bg-gray-300 dark:bg-zinc-600"></div>
</PanelResizer>
<iframe
:src="previewRoute"
frameborder="0"
v-if="previewRoute"
class="flex-1 rounded-sm"
ref="previewWindow"></iframe>
<div
v-if="loading || resizing"
class="absolute flex h-full w-full flex-1 items-center justify-center bg-gray-700 bg-zinc-700 bg-opacity-80 text-xl font-semibold text-gray-400 transition-all dark:bg-opacity-80 dark:text-zinc-400">
{{ loading ? "Loading..." : "Resizing..." }}
</div>
<PanelResizer
class="mr-[-8px]"
side="right"
:dimension="width"
:minDimension="minWidth"
:maxDimension="maxWidth"
:resizeSensitivity="2"
ref="rightPanelRef"
@resize="(val) => (width = val)">
<div class="resize-handler-left h-full w-2 rounded-sm bg-gray-300 dark:bg-zinc-600"></div>
</PanelResizer>
</div>
</div>
</template>
<script lang="ts" setup>
import PanelResizer from "@/components/PanelResizer.vue";
import router from "@/router";
import useStore from "@/store";
import { posthog } from "@/telemetry";
import { useEventListener } from "@vueuse/core";
import { Ref, computed, onActivated, ref, watch, watchEffect } from "vue";
import { useRoute } from "vue-router";
const route = useRoute();
const maxWidth = window.innerWidth * 0.92;
const minWidth = 400;
let previewRoute = ref("");
const width = ref(maxWidth);
const loading = ref(false);
const store = useStore();
const publishing = ref(false);
const deviceBreakpoints = [
{
icon: "monitor",
device: "desktop",
width: 1400,
},
{
icon: "tablet",
device: "tablet",
width: 800,
},
{
icon: "smartphone",
device: "mobile",
width: 420,
},
];
const leftPanelRef = ref<InstanceType<typeof PanelResizer> | null>(null);
const rightPanelRef = ref<InstanceType<typeof PanelResizer> | null>(null);
const resizing = computed(() => leftPanelRef.value?.dragActive || rightPanelRef.value?.dragActive);
const activeBreakpoint = computed(() => {
const tabletBreakpoint = deviceBreakpoints.find((b) => b.device === "tablet");
const mobileBreakpoint = deviceBreakpoints.find((b) => b.device === "mobile");
if (width.value <= (mobileBreakpoint?.width || minWidth)) {
return "mobile";
}
if (width.value <= (tabletBreakpoint?.width || maxWidth)) {
return "tablet";
}
return "desktop";
});
const previewWindow = ref(null) as Ref<HTMLIFrameElement | null>;
useEventListener(document, "keydown", (ev) => {
if (ev.key === "Escape" && router.currentRoute.value.name === "preview") {
history.back();
}
});
// hack to relay mouseup event from iframe to parent
watchEffect(() => {
if (previewWindow.value) {
loading.value = true;
previewWindow.value.addEventListener("load", () => {
setTimeout(() => {
loading.value = false;
}, 100);
previewWindow.value?.addEventListener("mousedown", (ev) => {
document.dispatchEvent(new MouseEvent("mousedown", ev));
});
previewWindow.value?.contentWindow?.document.addEventListener("mouseup", (ev) => {
document.dispatchEvent(new MouseEvent("mouseup", ev));
});
previewWindow.value?.contentWindow?.document.addEventListener("mousemove", (ev) => {
document.dispatchEvent(new MouseEvent("mousemove", ev));
});
});
}
});
const setWidth = (device: string) => {
const breakpoint = deviceBreakpoints.find((b) => b.device === device);
if (breakpoint) {
if (breakpoint.device === "desktop") {
width.value = maxWidth;
} else {
width.value = breakpoint.width;
}
}
};
const setPreviewURL = () => {
let queryParams = {
page: route.params.pageId,
...store.routeVariables,
};
previewRoute.value = `/api/method/builder.api.get_page_preview_html?${Object.entries(queryParams)
.map(([key, value]) => `${key}=${value}`)
.join("&")}`;
};
watch(
() => route.params.pageId,
() => {
setPreviewURL();
},
{ immediate: true },
);
onActivated(() => {
posthog.capture("builder_page_preview_viewed");
});
</script>
|
2302_79757062/builder
|
frontend/src/pages/PagePreview.vue
|
Vue
|
agpl-3.0
| 5,709
|
import { createResource } from "frappe-ui";
import { ref } from "vue";
import { NavigationGuardNext, RouteLocationNormalized, createRouter, createWebHistory } from "vue-router";
let hasPermission: null | boolean = null;
let sessionUser = ref("Guest");
function validatePermission(next: NavigationGuardNext) {
if (hasPermission) {
next();
} else {
alert("You do not have permission to access this page");
window.location.href = "/login";
}
}
const validateVisit = function (
to: RouteLocationNormalized,
from: RouteLocationNormalized,
next: NavigationGuardNext,
) {
if (document.cookie.includes("user_id") && !document.cookie.includes("user_id=Guest")) {
sessionUser.value = decodeURIComponent(document.cookie.split("user_id=")[1].split(";")[0]);
if (hasPermission === null) {
createResource({
url: "frappe.client.has_permission",
caches: "has_permission",
})
.submit({
doctype: "Builder Page",
docname: null,
perm_type: "write",
})
.then((res: { has_permission: boolean }) => {
hasPermission = res.has_permission;
validatePermission(next);
})
.catch(() => {
hasPermission = false;
validatePermission(next);
});
} else {
validatePermission(next);
}
} else {
validatePermission(next);
}
};
const routes = [
{
path: "/",
beforeEnter: validateVisit,
redirect: "/home",
},
{
path: "/page",
beforeEnter: validateVisit,
redirect: "/home",
},
{
path: "/home",
name: "home",
beforeEnter: validateVisit,
component: () => import("@/pages/PageBuilderLanding.vue"),
},
{
path: "/page/:pageId",
name: "builder",
beforeEnter: validateVisit,
component: () => import("@/pages/PageBuilder.vue"),
},
{
path: "/page/:pageId/preview",
name: "preview",
beforeEnter: validateVisit,
component: () => import("@/pages/PagePreview.vue"),
},
];
declare global {
interface Window {
builder_path: string;
}
}
let builder_path = window.builder_path || "/builder";
if (builder_path.startsWith("{{")) {
builder_path = "/builder";
}
const router = createRouter({
history: createWebHistory(builder_path),
routes,
});
export { sessionUser };
export default router;
|
2302_79757062/builder
|
frontend/src/router.ts
|
TypeScript
|
agpl-3.0
| 2,190
|
// Placed in separate file to setup frappe resource fetcher before loading the app.
import { frappeRequest, setConfig } from "frappe-ui";
setConfig("resourceFetcher", frappeRequest);
|
2302_79757062/builder
|
frontend/src/setupFrappeUIResource.ts
|
TypeScript
|
agpl-3.0
| 183
|
import { posthog } from "@/telemetry";
import { UseRefHistoryReturn } from "@vueuse/core";
import { FileUploadHandler, createDocumentResource } from "frappe-ui";
import { defineStore } from "pinia";
import { nextTick } from "vue";
import { toast } from "vue-sonner";
import BlockLayers from "./components/BlockLayers.vue";
import BuilderCanvas from "./components/BuilderCanvas.vue";
import builderBlockTemplate from "./data/builderBlockTemplate";
import { builderSettings } from "./data/builderSettings";
import webComponent from "./data/webComponent";
import { webPages } from "./data/webPage";
import { BlockTemplate } from "./types/Builder/BlockTemplate";
import { BuilderComponent } from "./types/Builder/BuilderComponent";
import { BuilderPage } from "./types/Builder/BuilderPage";
import Block from "./utils/block";
import getBlockTemplate from "./utils/blockTemplate";
import {
confirm,
getBlockCopy,
getBlockInstance,
getBlockObject,
getBlockString,
getCopyWithoutParent,
} from "./utils/helpers";
import RealTimeHandler from "./utils/realtimeHandler";
const useStore = defineStore("store", {
state: () => ({
editableBlock: <Block | null>null,
settingPage: false,
editingMode: <EditingMode>"page",
activeBreakpoint: "desktop",
selectedPage: <string | null>null,
pageData: <{ [key: string]: [] }>{},
mode: <BuilderMode>"select", // check setEvents in BuilderCanvas for usage
lastMode: <BuilderMode>"select",
activeCanvas: <InstanceType<typeof BuilderCanvas> | null>null,
activeLayers: <InstanceType<typeof BlockLayers> | null>null,
history: {
pause: () => {},
resume: () => {},
} as UseRefHistoryReturn<{}, {}>,
hoveredBlock: <string | null>null,
hoveredBreakpoint: <string | null>null,
routeVariables: <{ [key: string]: string }>{},
autoSave: true,
pageBlocks: <Block[]>[],
propertyFilter: <string | null>null,
builderLayout: {
rightPanelWidth: 275,
leftPanelWidth: 280,
scriptEditorHeight: 300,
},
pageName: "Home",
route: "/",
guides: {
showX: false,
showY: false,
x: 0,
y: 0,
},
leftPanelActiveTab: <LeftSidebarTabOption>"Layers",
rightPanelActiveTab: <RightSidebarTabOption>"Properties",
showRightPanel: <boolean>true,
showLeftPanel: <boolean>true,
components: <BlockComponent[]>[],
showHTMLDialog: false,
activePage: <BuilderPage | null>null,
savingPage: false,
realtime: new RealTimeHandler(),
viewers: <UserInfo[]>[],
componentMap: <Map<string, Block>>new Map(),
fragmentData: {
block: <Block | null>null,
saveAction: <Function | null>null,
saveActionLabel: <string | null>null,
fragmentName: <string | null>null,
},
}),
actions: {
clearBlocks() {
this.activeCanvas?.clearCanvas();
},
pushBlocks(blocks: BlockOptions[]) {
let parent = this.activeCanvas?.getFirstBlock();
let firstBlock = getBlockInstance(blocks[0]);
if (this.editingMode === "page" && firstBlock.isRoot() && this.activeCanvas?.block) {
this.activeCanvas.setRootBlock(firstBlock);
} else {
for (let block of blocks) {
parent?.children.push(getBlockInstance(block));
}
}
},
getFirstBlock() {
return this.activeCanvas?.getFirstBlock();
},
getBlockCopy(block: BlockOptions | Block, retainId = false): Block {
return getBlockCopy(block, retainId);
},
getRootBlock() {
return getBlockInstance(getBlockTemplate("body"));
},
getPageBlocks() {
return [this.activeCanvas?.getFirstBlock()];
},
async setPage(pageName: string, resetCanvas = true) {
this.settingPage = true;
if (!pageName) {
return;
}
const page = await this.fetchActivePage(pageName);
this.activePage = page;
const blocks = JSON.parse(page.draft_blocks || page.blocks || "[]");
this.editPage(!resetCanvas);
if (!Array.isArray(blocks)) {
this.pushBlocks([blocks]);
}
if (blocks.length === 0) {
this.pageBlocks = [getBlockInstance(getBlockTemplate("body"))];
} else {
this.pageBlocks = [getBlockInstance(blocks[0])];
}
this.pageBlocks = [getBlockInstance(blocks[0] || getBlockTemplate("body"))];
this.pageName = page.page_name as string;
this.route = page.route || "/" + this.pageName.toLowerCase().replace(/ /g, "-");
this.selectedPage = page.name;
const variables = localStorage.getItem(`${page.name}:routeVariables`) || "{}";
this.routeVariables = JSON.parse(variables);
await this.setPageData(this.activePage);
this.activeCanvas?.setRootBlock(this.pageBlocks[0], resetCanvas);
nextTick(() => {
this.settingPage = false;
});
},
async fetchActivePage(pageName: string) {
const webPageResource = await createDocumentResource({
doctype: "Builder Page",
name: pageName,
auto: true,
});
await webPageResource.get.promise;
const page = webPageResource.doc as BuilderPage;
return page;
},
getImageBlock(imageSrc: string, imageAlt: string = "") {
const imageBlock = getBlockTemplate("image");
if (!imageBlock.attributes) {
imageBlock.attributes = {};
}
imageBlock.attributes.src = imageSrc;
return imageBlock;
},
getVideoBlock(videoSrc: string) {
const videoBlock = getBlockTemplate("video");
if (!videoBlock.attributes) {
videoBlock.attributes = {};
}
videoBlock.attributes.src = videoSrc;
return videoBlock;
},
selectBlock(block: Block, e: MouseEvent | null, scrollLayerIntoView = true, scrollBlockIntoView = false) {
this.activeCanvas?.history?.pause();
if (this.settingPage) {
return;
}
if (e && e.shiftKey) {
this.activeCanvas?.selectBlockRange(block);
} else if (e && e.metaKey) {
this.activeCanvas?.toggleBlockSelection(block);
} else {
this.activeCanvas?.selectBlock(block);
}
if (scrollLayerIntoView) {
// TODO: move to layers?
nextTick(() => {
document
.querySelector(`[data-block-layer-id="${block.blockId}"]`)
?.scrollIntoView({ behavior: "instant", block: "center", inline: "center" });
});
}
this.activeCanvas?.history?.resume();
this.editableBlock = null;
if (scrollBlockIntoView) {
this.activeCanvas?.scrollBlockIntoView(block);
}
},
editComponent(block?: Block | null, componentName?: string) {
if (!block?.isExtendedFromComponent() && !componentName) {
return;
}
componentName = componentName || (block?.extendedFromComponent as string);
const component = this.getComponent(componentName);
const componentBlock = this.getComponentBlock(componentName);
this.editOnCanvas(
componentBlock,
(block: Block) => {
webComponent.setValue
.submit({
name: componentName,
block: getBlockObject(block),
})
.then((data: BuilderComponent) => {
this.componentMap.set(data.name, getBlockInstance(data.block));
toast.success("Component saved!");
});
},
"Save Component",
component.component_name,
);
},
editBlockTemplate(blockTemplateName: string) {
const blockTemplate = this.getBlockTemplate(blockTemplateName);
const blockTemplateBlock = this.getBlockTemplateBlock(blockTemplateName);
this.editOnCanvas(
blockTemplateBlock,
(block: Block) => {
this.saveBlockTemplate(block, blockTemplateName);
},
"Save Template",
blockTemplate.template_name,
);
},
getBlockTemplateBlock(blockTemplateName: string) {
return getBlockInstance(this.getBlockTemplate(blockTemplateName).block);
},
getBlockTemplate(blockTemplateName: string) {
return builderBlockTemplate.getRow(blockTemplateName) as BlockTemplate;
},
isComponentUsed(componentName: string) {
// TODO: Refactor or reduce complexity
const checkComponent = (block: Block) => {
if (block.extendedFromComponent === componentName) {
return true;
}
if (block.children) {
for (const child of block.children) {
if (checkComponent(child)) {
return true;
}
}
}
return false;
};
for (const block of this.activeCanvas?.getFirstBlock()?.children || []) {
if (checkComponent(block)) {
return true;
}
}
return false;
},
editPage(retainSelection = false) {
if (!retainSelection) {
this.activeCanvas?.clearSelection();
}
this.editingMode = "page";
},
getComponentBlock(componentName: string) {
if (!this.componentMap.has(componentName)) {
this.componentMap.set(
componentName,
getBlockInstance(this.getComponent(componentName)?.block || getBlockTemplate("fallback-component")),
);
}
return this.componentMap.get(componentName) as Block;
},
getComponent(componentName: string) {
return webComponent.getRow(componentName) as BuilderComponent;
},
createComponent(obj: BuilderComponent, updateExisting = false) {
const component = this.getComponent(obj.name);
if (component) {
const existingComponent = component.block;
const newComponent = obj.block;
if (updateExisting && existingComponent !== newComponent) {
return webComponent.setValue.submit({
name: obj.name,
block: obj.block,
});
} else {
return;
}
}
return webComponent.insert
.submit(obj)
.then(() => {
this.componentMap.set(obj.name, getBlockInstance(obj.block));
})
.catch(() => {
console.log(`There was an error while creating ${obj.component_name}`);
});
},
getComponentName(componentId: string) {
let componentObj = webComponent.getRow(componentId);
if (!componentObj) {
return componentId;
}
return componentObj.component_name;
},
uploadFile: async (file: File) => {
const uploader = new FileUploadHandler();
let fileDoc = {
file_url: "",
file_name: "",
};
const upload = uploader.upload(file, {
private: false,
folder: "Home/Builder Uploads",
optimize: true,
upload_endpoint: "/api/method/builder.api.upload_builder_asset",
});
await new Promise((resolve) => {
toast.promise(upload, {
loading: "Uploading...",
success: (data: { file_name: string; file_url: string }) => {
fileDoc.file_name = data.file_name;
fileDoc.file_url = data.file_url;
resolve(fileDoc);
return "Uploaded";
},
error: () => "Failed to upload",
duration: 500,
});
});
return {
fileURL: fileDoc.file_url,
fileName: fileDoc.file_name,
};
},
async publishPage() {
await this.waitTillPageIsSaved();
return webPages.runDocMethod
.submit({
name: this.selectedPage as string,
method: "publish",
...this.routeVariables,
})
.then(async () => {
posthog.capture("builder_page_published", {
page: this.selectedPage,
});
this.activePage = await this.fetchActivePage(this.selectedPage as string);
this.openPageInBrowser(this.activePage as BuilderPage);
});
},
openPageInBrowser(page: BuilderPage) {
let route = page.route;
if (page.dynamic_route && this.pageData) {
const routeVariables = (route?.match(/<\w+>/g) || []).map((match: string) => match.slice(1, -1));
routeVariables.forEach((variable: string) => {
if (this.routeVariables[variable]) {
route = route?.replace(`<${variable}>`, this.routeVariables[variable]);
}
});
}
window.open(`/${route}`, "builder-preview");
},
savePage() {
this.pageBlocks = this.getPageBlocks() as Block[];
const pageData = JSON.stringify(this.pageBlocks.map((block) => getCopyWithoutParent(block)));
const args = {
name: this.selectedPage,
draft_blocks: pageData,
};
return webPages.setValue.submit(args).finally(() => {
this.savingPage = false;
this.activeCanvas?.toggleDirty(false);
});
},
setPageData(page?: BuilderPage) {
if (!page || !page.page_data_script) {
this.pageData = {};
return;
}
return webPages.runDocMethod
.submit({
method: "get_page_data",
name: page.name,
...this.routeVariables,
})
.then((data: { message: { [key: string]: [] } }) => {
this.pageData = data.message;
})
.catch((e: { exc: string | null }) => {
const error_message = e.exc?.split("\n").slice(-2)[0];
toast.error("There was an error while fetching page data", {
description: error_message,
});
});
},
setRouteVariable(variable: string, value: string) {
this.routeVariables[variable] = value;
localStorage.setItem(`${this.selectedPage}:routeVariables`, JSON.stringify(this.routeVariables));
this.setPageData(this.activePage as BuilderPage);
},
openInDesk(page: BuilderPage) {
window.open(`/app/builder-page/${page.page_name}`, "_blank");
},
openBuilderSettings() {
window.open("/app/builder-settings", "_blank");
},
editHTML(block: Block) {
this.editableBlock = block;
nextTick(() => {
this.showHTMLDialog = true;
});
},
isHomePage(page: BuilderPage | null = null) {
return builderSettings.doc.home_page === (page || this.activePage)?.route;
},
async waitTillPageIsSaved() {
// small delay so that all the save requests are triggered
await new Promise((resolve) => setTimeout(resolve, 100));
return new Promise((resolve) => {
const interval = setInterval(() => {
if (!this.savingPage) {
clearInterval(interval);
resolve(null);
}
}, 100);
});
},
async saveBlockTemplate(
block: Block,
templateName: string,
category: BlockTemplate["category"] = "Basic",
previewImage: string = "",
) {
const blockString = getBlockString(block);
const args = {
name: templateName,
template_name: templateName,
block: blockString,
} as BlockTemplate;
if (builderBlockTemplate.getRow(templateName)) {
await builderBlockTemplate.setValue.submit(args);
} else {
args["category"] = category;
args["preview"] = previewImage;
await builderBlockTemplate.insert.submit(args);
}
toast.success("Block template saved!");
},
editOnCanvas(
block: Block,
saveAction: (block: Block) => void,
saveActionLabel: string = "Save",
fragmentName?: string,
) {
this.fragmentData = {
block,
saveAction,
saveActionLabel,
fragmentName: fragmentName || block.getBlockDescription(),
};
this.editingMode = "fragment";
},
async exitFragmentMode(e?: Event) {
if (this.editingMode === "page") {
return;
}
e?.preventDefault();
if (this.activeCanvas?.isDirty) {
const exit = await confirm("Are you sure you want to exit without saving?");
if (!exit) {
return;
}
}
this.activeCanvas?.clearSelection();
this.editingMode = "page";
// reset fragmentData
this.fragmentData = {
block: null,
saveAction: null,
saveActionLabel: null,
fragmentName: null,
};
},
},
});
export default useStore;
|
2302_79757062/builder
|
frontend/src/store.ts
|
TypeScript
|
agpl-3.0
| 14,739
|
import { createResource } from "frappe-ui";
import "../../../frappe/frappe/public/js/lib/posthog.js";
declare global {
interface Window {
posthog: {
init: (projectToken: string, options: any) => void;
identify: (userId: string) => void;
startSessionRecording: () => void;
capture: (eventName: string, data?: any) => void;
};
}
}
type PosthogSettings = {
posthog_project_id: string;
posthog_host: string;
enable_telemetry: boolean;
telemetry_site_age: number;
record_session: boolean;
posthog_identify: string;
};
let posthog = {
init: (projectToken: string, options: any) => {},
identify: (userId: string) => {},
startSessionRecording: () => {},
capture: (eventName: string, data?: any) => {},
};
createResource({
url: "builder.api.get_posthog_settings",
method: "GET",
auto: true,
onSuccess: (posthogSettings: PosthogSettings) => {
if (!posthogSettings.enable_telemetry || !posthogSettings.posthog_project_id) {
return;
}
window.posthog.init(posthogSettings.posthog_project_id, {
api_host: posthogSettings.posthog_host,
person_profiles: "identified_only",
autocapture: false,
capture_pageview: false,
capture_pageleave: false,
enable_heatmaps: false,
disable_session_recording: true,
loaded: (ph: typeof posthog) => {
ph.identify(posthogSettings?.posthog_identify || window.location.host);
posthog = ph;
if (posthogSettings.record_session) {
ph.startSessionRecording();
}
},
});
},
});
export { posthog };
|
2302_79757062/builder
|
frontend/src/telemetry.ts
|
TypeScript
|
agpl-3.0
| 1,504
|
export interface BlockTemplate{
creation: string
name: string
modified: string
owner: string
modified_by: string
docstatus: 0 | 1 | 2
parent?: string
parentfield?: string
parenttype?: string
idx?: number
/** Template Name : Data */
template_name: string
/** Block : JSON */
block: any
/** Preview : Data */
preview: string
/** Category : Select */
category?: "Basic" | "Structure"
}
|
2302_79757062/builder
|
frontend/src/types/Builder/BlockTemplate.ts
|
TypeScript
|
agpl-3.0
| 401
|
export interface BuilderClientScript{
creation: string
name: string
modified: string
owner: string
modified_by: string
docstatus: 0 | 1 | 2
parent?: string
parentfield?: string
parenttype?: string
idx?: number
/** Script Type : Autocomplete */
script_type: any
/** Script : Code */
script: string
/** Public URL : Read Only */
public_url?: string
}
|
2302_79757062/builder
|
frontend/src/types/Builder/BuilderClientScript.ts
|
TypeScript
|
agpl-3.0
| 365
|
export interface BuilderComponent {
creation: string;
name: string;
modified: string;
owner: string;
modified_by: string;
docstatus: 0 | 1 | 2;
parent?: string;
parentfield?: string;
parenttype?: string;
idx?: number;
/** Component Name : Data */
component_name?: string;
/** Block : JSON */
block: string;
/** For Web Page : Link - Builder Page */
for_web_page?: string;
/** Component ID : Data */
component_id?: string;
}
|
2302_79757062/builder
|
frontend/src/types/Builder/BuilderComponent.ts
|
TypeScript
|
agpl-3.0
| 442
|
import { BuilderPageClientScript } from './BuilderPageClientScript'
export interface BuilderPage{
creation: string
name: string
modified: string
owner: string
modified_by: string
docstatus: 0 | 1 | 2
parent?: string
parentfield?: string
parenttype?: string
idx?: number
/** Published : Check */
published?: 0 | 1
/** Page Name : Data */
page_name?: string
/** Route : Data */
route?: string
/** Dynamic Route : Check - Map route parameters into form variables. Example <code>/profile/<user></code> */
dynamic_route?: 0 | 1
/** Is Template : Check */
is_template?: 0 | 1
/** Template Name : Data */
template_name?: string
/** Blocks : JSON */
blocks?: any
/** Draft Blocks : JSON */
draft_blocks?: any
/** Page Data Script : Code - data.events = frappe.get_list("Event")
<br>
<b>Note:</b> Each key value of data should be a list. */
page_data_script?: string
/** Client Scripts : Table MultiSelect - Builder Page Client Script */
client_scripts?: BuilderPageClientScript[]
/** Page Preview : Data */
preview?: string
/** Favicon : Attach Image - An icon file with .ico extension. Should be 16 x 16 px.
You can generate using favicon-generator.org */
favicon?: string
/** Title : Data */
page_title?: string
/** Description : Small Text */
meta_description?: string
/** Image : Attach Image */
meta_image?: string
}
|
2302_79757062/builder
|
frontend/src/types/Builder/BuilderPage.ts
|
TypeScript
|
agpl-3.0
| 1,360
|
export interface BuilderPageClientScript{
creation: string
name: string
modified: string
owner: string
modified_by: string
docstatus: 0 | 1 | 2
parent?: string
parentfield?: string
parenttype?: string
idx?: number
/** Builder Script : Link - Builder Client Script */
builder_script: string
}
|
2302_79757062/builder
|
frontend/src/types/Builder/BuilderPageClientScript.ts
|
TypeScript
|
agpl-3.0
| 304
|
export interface BuilderSettings{
creation: string
name: string
modified: string
owner: string
modified_by: string
docstatus: 0 | 1 | 2
parent?: string
parentfield?: string
parenttype?: string
idx?: number
/** Script : Code - Global script that will be loaded with every page built with Frappe Builder */
script?: string
/** Script Public URL : Read Only */
script_public_url?: string
/** Style : Code - Global style that will be loaded with every page built with Frappe Builder */
style?: string
/** Style Public URL : Read Only */
style_public_url?: string
/** Favicon : Attach Image - An icon file with .ico extension. Should be 16 x 16 px.<br>You can generate using <a href="https://favicon-generator.org" target="_blank">favicon-generator.org</a> */
favicon?: string
/** Auto convert images to WebP : Check - Beta: All the images uploaded to Canvas will be auto converted to WebP for better page performance. */
auto_convert_images_to_webp?: 0 | 1
/** Home Page : Data */
home_page?: string
}
|
2302_79757062/builder
|
frontend/src/types/Builder/BuilderSettings.ts
|
TypeScript
|
agpl-3.0
| 1,022
|
import { createResource } from "frappe-ui";
import { reactive } from "vue";
let usersByName = reactive({}) as { [key: string]: UserInfo };
export async function getUsersInfo(emails: string[]) {
const usersToFetch = [] as string[];
const usersInfo = [] as UserInfo[];
emails.forEach((email) => {
if (!usersByName[email]) {
usersToFetch.push(email);
} else {
usersInfo.push(usersByName[email]);
}
});
if (usersToFetch.length) {
await createResource({
method: "POST",
url: `/api/method/frappe.desk.form.load.get_user_info_for_viewers`,
})
.submit({
users: JSON.stringify(usersToFetch),
})
.then((res: { [key: string]: UserInfo }) => {
usersToFetch.forEach((email) => {
usersByName[email] = res[email];
usersInfo.push(usersByName[email]);
});
});
}
return usersInfo as UserInfo[];
}
|
2302_79757062/builder
|
frontend/src/usersInfo.ts
|
TypeScript
|
agpl-3.0
| 844
|
Array.prototype.add = function (...itemsToAdd: any[]) {
itemsToAdd.forEach((item) => {
if (!this.includes(item)) {
this.push(item);
}
});
};
Array.prototype.remove = function (...itemsToRemove: any[]) {
itemsToRemove.forEach((item) => {
const index = this.indexOf(item);
if (index !== -1) {
this.splice(index, 1);
}
});
};
|
2302_79757062/builder
|
frontend/src/utils/arrayFunctions.ts
|
TypeScript
|
agpl-3.0
| 344
|
import useStore from "@/store";
import { Editor } from "@tiptap/vue-3";
import { clamp } from "@vueuse/core";
import { CSSProperties, markRaw, nextTick, reactive } from "vue";
import { addPxToNumber, getBlockCopy, getNumberFromPx, getTextContent, kebabToCamelCase } from "./helpers";
export type styleProperty = keyof CSSProperties | `__${string}`;
type BlockDataKeyType = "key" | "attribute" | "style";
export interface BlockDataKey {
key?: string;
type?: BlockDataKeyType;
property?: string;
}
class Block implements BlockOptions {
blockId: string;
children: Array<Block>;
baseStyles: BlockStyleMap;
rawStyles: BlockStyleMap;
mobileStyles: BlockStyleMap;
tabletStyles: BlockStyleMap;
attributes: BlockAttributeMap;
classes: Array<string>;
dataKey?: BlockDataKey | null = null;
blockName?: string;
element?: string;
draggable?: boolean;
innerText?: string;
innerHTML?: string;
extendedFromComponent?: string;
originalElement?: string | undefined;
isChildOfComponent?: string;
referenceBlockId?: string;
isRepeaterBlock?: boolean;
visibilityCondition?: string;
elementBeforeConversion?: string;
parentBlock: Block | null;
customAttributes: BlockAttributeMap;
constructor(options: BlockOptions) {
this.element = options.element;
this.innerHTML = options.innerHTML;
this.extendedFromComponent = options.extendedFromComponent;
this.isRepeaterBlock = options.isRepeaterBlock;
this.isChildOfComponent = options.isChildOfComponent;
this.referenceBlockId = options.referenceBlockId;
this.visibilityCondition = options.visibilityCondition;
this.parentBlock = options.parentBlock || null;
this.dataKey = options.dataKey || null;
if (options.innerText) {
this.innerHTML = options.innerText;
}
this.originalElement = options.originalElement;
if (!options.blockId || options.blockId === "root") {
this.blockId = this.generateId();
} else {
this.blockId = options.blockId;
}
this.children = (options.children || []).map((child: BlockOptions) => {
child.parentBlock = this;
return reactive(new Block(child));
});
this.baseStyles = reactive(options.styles || options.baseStyles || {});
this.rawStyles = reactive(options.rawStyles || {});
this.customAttributes = reactive(options.customAttributes || {});
this.mobileStyles = reactive(options.mobileStyles || {});
this.tabletStyles = reactive(options.tabletStyles || {});
this.attributes = reactive(options.attributes || {});
this.blockName = options.blockName;
delete this.attributes.style;
this.classes = options.classes || [];
if (this.isRoot()) {
this.blockId = "root";
this.draggable = false;
this.removeStyle("minHeight");
}
}
getStyles(breakpoint: string = "desktop"): BlockStyleMap {
let styleObj = {};
if (this.isExtendedFromComponent()) {
styleObj = this.getComponentStyles(breakpoint);
}
styleObj = { ...styleObj, ...this.baseStyles };
if (["mobile", "tablet"].includes(breakpoint)) {
styleObj = { ...styleObj, ...this.tabletStyles };
if (breakpoint === "mobile") {
styleObj = { ...styleObj, ...this.mobileStyles };
}
}
styleObj = { ...styleObj, ...this.rawStyles };
// replace variables with values
// Object.keys(styleObj).forEach((style) => {
// const value = styleObj[style];
// if (typeof value === "string" && value.startsWith("--")) {
// styleObj[style] = this.getVariableValue(value);
// }
// });
return styleObj;
}
hasOverrides(breakpoint: string) {
if (breakpoint === "mobile") {
return Object.keys(this.mobileStyles).length > 0;
}
if (breakpoint === "tablet") {
return Object.keys(this.tabletStyles).length > 0;
}
return false;
}
resetOverrides(breakpoint: string) {
if (breakpoint === "mobile") {
this.mobileStyles = {};
}
if (breakpoint === "tablet") {
this.tabletStyles = {};
}
}
getComponent() {
const store = useStore();
if (this.extendedFromComponent) {
return store.getComponentBlock(this.extendedFromComponent as string);
}
if (this.isChildOfComponent) {
const componentBlock = store.getComponentBlock(this.isChildOfComponent as string);
return (
store.activeCanvas?.findBlock(this.referenceBlockId as string, [componentBlock]) ||
store.activeCanvas?.findBlock(this.blockId as string, [componentBlock]) ||
new Block({})
);
}
return this;
}
getComponentStyles(breakpoint: string): BlockStyleMap {
return this.getComponent()?.getStyles(breakpoint);
}
getAttributes(): BlockAttributeMap {
let attributes = {};
if (this.isExtendedFromComponent()) {
attributes = this.getComponentAttributes();
}
attributes = { ...attributes, ...this.attributes };
return attributes;
}
getComponentAttributes() {
return this.getComponent()?.attributes || {};
}
getClasses() {
let classes = [] as Array<string>;
if (this.isExtendedFromComponent()) {
classes = this.getComponentClasses();
}
classes = [...classes, ...this.classes];
return classes;
}
getComponentClasses() {
return this.getComponent()?.classes || [];
}
getChildren() {
return this.children;
}
hasChildren() {
return this.getChildren().length > 0;
}
getComponentChildren() {
return this.getComponent()?.children || [];
}
getCustomAttributes() {
let customAttributes = {};
if (this.isExtendedFromComponent()) {
customAttributes = this.getComponent()?.customAttributes || {};
}
customAttributes = { ...customAttributes, ...this.customAttributes };
return customAttributes;
}
getRawStyles() {
let rawStyles = {};
if (this.isExtendedFromComponent()) {
rawStyles = this.getComponent()?.rawStyles || {};
}
rawStyles = { ...rawStyles, ...this.rawStyles };
return rawStyles;
}
getVisibilityCondition() {
let visibilityCondition = this.visibilityCondition;
if (this.isExtendedFromComponent() && this.getComponent()?.visibilityCondition) {
visibilityCondition = this.getComponent()?.visibilityCondition;
}
return visibilityCondition;
}
getBlockDescription() {
if (this.extendedFromComponent) {
return this.getComponentBlockDescription();
}
if (this.isHTML()) {
const innerHTML = this.getInnerHTML() || "";
const match = innerHTML.match(/<([a-z]+)[^>]*>/);
if (match) {
return `${match[1]}`;
} else {
return "raw";
}
}
let description = this.blockName || this.originalElement || this.getElement();
if (this.getTextContent() && !this.blockName) {
description += " | " + this.getTextContent();
}
return description;
}
getComponentBlockDescription() {
const store = useStore();
return store.getComponentName(this.extendedFromComponent as string);
}
getTextContent() {
return getTextContent(this.getInnerHTML() || "");
}
isImage() {
return this.getElement() === "img";
}
isVideo() {
return this.getElement() === "video" || this.getInnerHTML()?.startsWith("<video");
}
isForm() {
return this.getElement() === "form";
}
isButton() {
return this.getElement() === "button";
}
isLink() {
return this.getElement() === "a";
}
isSVG() {
return this.getElement() === "svg" || this.getInnerHTML()?.startsWith("<svg");
}
isText() {
return ["span", "h1", "p", "b", "h2", "h3", "h4", "h5", "h6", "label", "a"].includes(
this.getElement() as string,
);
}
isContainer() {
return ["section", "div"].includes(this.getElement() as string);
}
isHeader() {
return ["h1", "h2", "h3", "h4", "h5", "h6"].includes(this.getElement() as string);
}
isInput() {
return (
this.originalElement === "input" || this.getElement() === "input" || this.getElement() === "textarea"
);
}
setStyle(style: styleProperty, value: StyleValue) {
const store = useStore();
let styleObj = this.baseStyles;
style = kebabToCamelCase(style) as styleProperty;
if (store.activeBreakpoint === "mobile") {
styleObj = this.mobileStyles;
} else if (store.activeBreakpoint === "tablet") {
styleObj = this.tabletStyles;
}
if (value === null || value === "") {
delete styleObj[style];
return;
}
styleObj[style] = value;
}
setAttribute(attribute: string, value: string | undefined) {
this.attributes[attribute] = value;
}
removeAttribute(attribute: string) {
this.setAttribute(attribute, undefined);
}
getAttribute(attribute: string) {
return this.getAttributes()[attribute];
}
removeStyle(style: styleProperty) {
delete this.baseStyles[style];
delete this.mobileStyles[style];
delete this.tabletStyles[style];
}
setBaseStyle(style: styleProperty, value: StyleValue) {
style = kebabToCamelCase(style) as styleProperty;
this.baseStyles[style] = value;
}
getStyle(style: styleProperty) {
const store = useStore();
let styleValue = undefined as StyleValue;
if (store.activeBreakpoint === "mobile") {
styleValue = this.mobileStyles[style] || this.tabletStyles[style] || this.baseStyles[style];
} else if (store.activeBreakpoint === "tablet") {
styleValue = this.tabletStyles[style] || this.baseStyles[style];
} else {
styleValue = this.baseStyles[style];
}
if (styleValue === undefined && this.isExtendedFromComponent()) {
styleValue = this.getComponent()?.getStyle(style) as StyleValue;
}
return styleValue;
}
getNativeStyle(style: styleProperty) {
const store = useStore();
if (store.activeBreakpoint === "mobile") {
return this.mobileStyles[style];
}
if (store.activeBreakpoint === "tablet") {
return this.tabletStyles[style];
}
return this.baseStyles[style];
}
generateId() {
return Math.random().toString(36).substr(2, 9);
}
getIcon() {
switch (true) {
case this.isRoot():
return "hash";
case this.isRepeater():
return "database";
case this.isSVG():
return "aperture";
case this.isHTML():
return "code";
case this.isLink():
return "link";
case this.isText():
return "type";
case this.isContainer() && this.isRow():
return "columns";
case this.isContainer() && this.isColumn():
return "credit-card";
case this.isGrid():
return "grid";
case this.isContainer():
return "square";
case this.isImage():
return "image";
case this.isVideo():
return "film";
case this.isForm():
return "file-text";
default:
return "square";
}
}
isRoot() {
return this.originalElement === "body";
}
getTag(): string {
if (this.isButton() || this.isLink()) {
return "div";
}
return this.getElement() || "div";
}
getComponentTag() {
return this.getComponent()?.getTag() || "div";
}
isDiv() {
return this.getElement() === "div";
}
getStylesCopy() {
return {
baseStyles: Object.assign({}, this.baseStyles),
mobileStyles: Object.assign({}, this.mobileStyles),
tabletStyles: Object.assign({}, this.tabletStyles),
};
}
isMovable(): boolean {
return ["absolute", "fixed"].includes(this.getStyle("position") as string);
}
move(direction: "up" | "left" | "down" | "right") {
if (!this.isMovable()) {
return;
}
let top = getNumberFromPx(this.getStyle("top")) || 0;
let left = getNumberFromPx(this.getStyle("left")) || 0;
if (direction === "up") {
top -= 10;
this.setStyle("top", addPxToNumber(top));
} else if (direction === "down") {
top += 10;
this.setStyle("top", addPxToNumber(top));
} else if (direction === "left") {
left -= 10;
this.setStyle("left", addPxToNumber(left));
} else if (direction === "right") {
left += 10;
this.setStyle("left", addPxToNumber(left));
}
}
addChild(child: BlockOptions, index?: number | null, select: boolean = true) {
child.parentBlock = this;
if (index === undefined || index === null) {
index = this.children.length;
}
index = clamp(index, 0, this.children.length);
const childBlock = reactive(new Block(child));
this.children.splice(index, 0, childBlock);
if (select) {
childBlock.selectBlock();
}
if (childBlock.isText()) {
childBlock.makeBlockEditable();
}
if (childBlock.getStyle("position")) {
if (!this.getStyle("position")) {
this.setStyle("position", "relative");
}
}
return childBlock;
}
removeChild(child: Block) {
const index = this.getChildIndex(child);
if (index > -1) {
this.children.splice(index, 1);
}
}
replaceChild(child: Block, newChild: Block) {
newChild.parentBlock = this;
const index = this.getChildIndex(child);
if (index > -1) {
this.children.splice(index, 1, newChild);
}
}
getChildIndex(child: Block) {
return this.children.findIndex((block) => block.blockId === child.blockId);
}
addChildAfter(child: BlockOptions, siblingBlock: Block) {
const siblingIndex = this.getChildIndex(siblingBlock);
return this.addChild(child, siblingIndex + 1);
}
getEditorStyles() {
const styles = reactive({} as BlockStyleMap);
if (this.isRoot()) {
styles.width = "inherit";
styles.overflowX = "hidden";
}
if (this.isImage() && !this.getAttribute("src")) {
styles.background = `repeating-linear-gradient(45deg, rgba(180, 180, 180, 0.8) 0px, rgba(180, 180, 180, 0.8) 1px, rgba(255, 255, 255, 0.2) 0px, rgba(255, 255, 255, 0.2) 50%)`;
styles.backgroundSize = "16px 16px";
}
if (this.isButton() && this.children.length === 0) {
styles.display = "flex";
styles.alignItems = "center";
styles.justifyContent = "center";
}
styles.transition = "unset";
return styles;
}
selectBlock() {
const store = useStore();
nextTick(() => {
store.selectBlock(this, null);
});
}
getParentBlock(): Block | null {
return this.parentBlock || null;
}
selectParentBlock() {
const parentBlock = this.getParentBlock();
if (parentBlock) {
parentBlock.selectBlock();
}
}
getSiblingBlock(direction: "next" | "previous") {
const parentBlock = this.getParentBlock();
let sibling = null as Block | null;
if (parentBlock) {
const index = parentBlock.getChildIndex(this);
if (direction === "next") {
sibling = parentBlock.children[index + 1];
} else {
sibling = parentBlock.children[index - 1];
}
if (sibling) {
return sibling;
}
}
return null;
}
selectSiblingBlock(direction: "next" | "previous") {
const sibling = this.getSiblingBlock(direction);
if (sibling) {
sibling.selectBlock();
}
}
canHaveChildren(): boolean {
return !(
this.isImage() ||
this.isSVG() ||
this.isInput() ||
this.isVideo() ||
(this.isText() && !this.isLink()) ||
this.isExtendedFromComponent()
);
}
updateStyles(styles: BlockStyleObjects) {
this.baseStyles = Object.assign({}, this.baseStyles, styles.baseStyles);
this.mobileStyles = Object.assign({}, this.mobileStyles, styles.mobileStyles);
this.tabletStyles = Object.assign({}, this.tabletStyles, styles.tabletStyles);
}
getBackgroundColor() {
return this.getStyle("backgroundColor") || "transparent";
}
getFontFamily() {
const editor = this.getEditor();
if (this.isText() && editor && editor.isFocused) {
return editor.getAttributes("textStyle").fontFamily;
}
return this.getStyle("fontFamily");
}
setFontFamily(fontFamily: string) {
const editor = this.getEditor();
if (this.isText() && editor && editor.isFocused) {
editor.chain().focus().setFontFamily(fontFamily).run();
} else {
this.setStyle("fontFamily", fontFamily);
}
}
getTextColor() {
const editor = this.getEditor();
const color = editor?.getAttributes("textStyle").color;
if (this.isText() && editor && color && editor.isEditable) {
return color;
} else {
return this.getStyle("color");
}
}
getEditor(): null | Editor {
// @ts-ignore
return this.__proto__.editor || null;
}
setTextColor(color: string) {
const editor = this.getEditor();
if (this.isText() && editor && editor.isEditable) {
editor.chain().setColor(color).run();
} else {
this.setStyle("color", color);
}
}
isHTML() {
return this.originalElement === "__raw_html__";
}
isIframe() {
return this.innerHTML?.startsWith("<iframe");
}
makeBlockEditable() {
const store = useStore();
this.selectBlock();
store.editableBlock = this;
nextTick(() => {
this.getEditor()?.commands.focus("all");
});
}
isExtendedFromComponent() {
return Boolean(this.extendedFromComponent) || Boolean(this.isChildOfComponent);
}
convertToRepeater() {
this.setBaseStyle("display", "flex");
this.setBaseStyle("flexDirection", "column");
this.setBaseStyle("alignItems", "flex-start");
this.setBaseStyle("justifyContent", "flex-start");
this.setBaseStyle("flexWrap", "wrap");
this.setBaseStyle("height", "fit-content");
this.setBaseStyle("gap", "20px");
this.isRepeaterBlock = true;
}
moveChild(child: Block, index: number) {
const childIndex = this.children.findIndex((block) => block.blockId === child.blockId);
if (childIndex > -1) {
this.children.splice(childIndex, 1);
this.children.splice(index, 0, child);
}
}
isRepeater() {
return this.isRepeaterBlock;
}
getDataKey(key: keyof BlockDataKey): string {
let dataKey = (this.dataKey && this.dataKey[key]) || "";
if (!dataKey && this.isExtendedFromComponent()) {
dataKey = this.getComponent()?.getDataKey(key);
}
return dataKey;
}
setDataKey(key: keyof BlockDataKey, value: BlockDataKeyType) {
if (!this.dataKey || !this.dataKey[key]) {
this.dataKey = {
key: "",
type: this.isImage() || this.isLink() ? "attribute" : "key",
property: this.isLink() ? "href" : this.isImage() ? "src" : "innerHTML",
};
}
this.dataKey[key] = value;
}
getInnerHTML(): string {
let innerHTML = this.innerHTML || "";
if (!innerHTML && this.isExtendedFromComponent()) {
innerHTML = this.getComponent().getInnerHTML();
}
return innerHTML;
}
setInnerHTML(innerHTML: string) {
this.innerHTML = innerHTML;
}
toggleVisibility() {
if (this.getStyle("display") === "none") {
this.setStyle("display", this.getStyle("__last_display") || "flex");
this.setStyle("__last_display", null);
} else {
this.setStyle("__last_display", this.getStyle("display"));
this.setStyle("display", "none");
}
}
isVisible() {
return this.getStyle("display") !== "none";
}
extendFromComponent(componentName: string) {
this.extendedFromComponent = componentName;
const component = this.getComponent();
extendWithComponent(this, componentName, component.children);
}
isChildOfComponentBlock() {
return Boolean(this.isChildOfComponent);
}
resetWithComponent() {
const component = this.getComponent();
if (component) {
resetWithComponent(this, this.extendedFromComponent as string, component.children);
}
}
syncWithComponent() {
const component = this.getComponent();
if (component) {
syncBlockWithComponent(this, this, this.extendedFromComponent as string, component.children);
}
}
resetChanges(resetChildren: boolean = false) {
resetBlock(this, resetChildren);
}
convertToLink() {
this.elementBeforeConversion = this.element;
this.element = "a";
}
unsetLink() {
this.removeAttribute("href");
this.removeAttribute("target");
if (this.elementBeforeConversion) {
this.element = this.elementBeforeConversion;
}
}
getElement() {
if (this.isExtendedFromComponent()) {
return this.getComponent()?.element || this.element;
}
return this.element;
}
getUsedComponentNames() {
const store = useStore();
const componentNames = [] as string[];
if (this.extendedFromComponent) {
componentNames.push(this.extendedFromComponent);
}
if (this.isChildOfComponent) {
componentNames.push(this.isChildOfComponent);
}
this.children.forEach((child) => {
componentNames.push(...child.getUsedComponentNames());
});
componentNames.forEach((name) => {
componentNames.push(...store.getComponentBlock(name).getUsedComponentNames());
});
return new Set(componentNames);
}
isFlex() {
return this.getStyle("display") === "flex";
}
isGrid() {
return this.getStyle("display") === "grid";
}
isRow() {
return this.isFlex() && this.getStyle("flexDirection") === "row";
}
isColumn() {
return this.isFlex() && this.getStyle("flexDirection") === "column";
}
duplicateBlock() {
if (this.isRoot()) {
return;
}
const store = useStore();
store.activeCanvas?.history.pause();
const blockCopy = getBlockCopy(this);
const parentBlock = this.getParentBlock();
if (blockCopy.getStyle("position") === "absolute") {
// shift the block a bit
const left = getNumberFromPx(blockCopy.getStyle("left"));
const top = getNumberFromPx(blockCopy.getStyle("top"));
blockCopy.setStyle("left", `${left + 20}px`);
blockCopy.setStyle("top", `${top + 20}px`);
}
let child = null as Block | null;
if (parentBlock) {
child = parentBlock.addChildAfter(blockCopy, this);
} else {
child = store.activeCanvas?.getFirstBlock().addChild(blockCopy) as Block;
}
nextTick(() => {
if (child) {
child.selectBlock();
}
store.activeCanvas?.history.resume(true);
});
}
getPadding() {
const padding = this.getStyle("padding") || "0px";
const paddingTop = this.getStyle("paddingTop");
const paddingBottom = this.getStyle("paddingBottom");
const paddingLeft = this.getStyle("paddingLeft");
const paddingRight = this.getStyle("paddingRight");
if (!paddingTop && !paddingBottom && !paddingLeft && !paddingRight) {
return padding;
}
if (
paddingTop &&
paddingBottom &&
paddingTop === paddingBottom &&
paddingTop === paddingRight &&
paddingTop === paddingLeft
) {
return paddingTop;
}
if (paddingTop && paddingLeft && paddingTop === paddingBottom && paddingLeft === paddingRight) {
return `${paddingTop} ${paddingLeft}`;
} else {
return `${paddingTop || padding} ${paddingRight || padding} ${paddingBottom || padding} ${
paddingLeft || padding
}`;
}
}
setPadding(padding: string) {
// reset padding
this.setStyle("padding", null);
this.setStyle("paddingTop", null);
this.setStyle("paddingBottom", null);
this.setStyle("paddingLeft", null);
this.setStyle("paddingRight", null);
if (!padding) {
return;
}
const paddingArray = padding.split(" ");
if (paddingArray.length === 1) {
this.setStyle("padding", paddingArray[0]);
} else if (paddingArray.length === 2) {
this.setStyle("paddingTop", paddingArray[0]);
this.setStyle("paddingBottom", paddingArray[0]);
this.setStyle("paddingLeft", paddingArray[1]);
this.setStyle("paddingRight", paddingArray[1]);
} else if (paddingArray.length === 3) {
this.setStyle("paddingTop", paddingArray[0]);
this.setStyle("paddingLeft", paddingArray[1]);
this.setStyle("paddingRight", paddingArray[1]);
this.setStyle("paddingBottom", paddingArray[2]);
} else if (paddingArray.length === 4) {
this.setStyle("paddingTop", paddingArray[0]);
this.setStyle("paddingRight", paddingArray[1]);
this.setStyle("paddingBottom", paddingArray[2]);
this.setStyle("paddingLeft", paddingArray[3]);
}
}
setMargin(margin: string) {
// reset margin
this.setStyle("margin", null);
this.setStyle("marginTop", null);
this.setStyle("marginBottom", null);
this.setStyle("marginLeft", null);
this.setStyle("marginRight", null);
if (!margin) {
return;
}
const marginArray = margin.split(" ");
if (marginArray.length === 1) {
this.setStyle("margin", marginArray[0]);
} else if (marginArray.length === 2) {
this.setStyle("marginTop", marginArray[0]);
this.setStyle("marginBottom", marginArray[0]);
this.setStyle("marginLeft", marginArray[1]);
this.setStyle("marginRight", marginArray[1]);
} else if (marginArray.length === 3) {
this.setStyle("marginTop", marginArray[0]);
this.setStyle("marginLeft", marginArray[1]);
this.setStyle("marginRight", marginArray[1]);
this.setStyle("marginBottom", marginArray[2]);
} else if (marginArray.length === 4) {
this.setStyle("marginTop", marginArray[0]);
this.setStyle("marginRight", marginArray[1]);
this.setStyle("marginBottom", marginArray[2]);
this.setStyle("marginLeft", marginArray[3]);
}
}
getMargin() {
const margin = this.getStyle("margin") || "0px";
const marginTop = this.getStyle("marginTop");
const marginBottom = this.getStyle("marginBottom");
const marginLeft = this.getStyle("marginLeft");
const marginRight = this.getStyle("marginRight");
if (!marginTop && !marginBottom && !marginLeft && !marginRight) {
return margin;
}
if (
marginTop &&
marginBottom &&
marginTop === marginBottom &&
marginTop === marginRight &&
marginTop === marginLeft
) {
return marginTop;
}
if (marginTop && marginLeft && marginTop === marginBottom && marginLeft === marginRight) {
return `${marginTop} ${marginLeft}`;
} else {
return `${marginTop || margin} ${marginRight || margin} ${marginBottom || margin} ${
marginLeft || margin
}`;
}
}
}
function extendWithComponent(
block: Block | BlockOptions,
extendedFromComponent: string | undefined,
componentChildren: Block[],
resetOverrides: boolean = true,
) {
resetBlock(block, true, resetOverrides);
block.children?.forEach((child, index) => {
child.isChildOfComponent = extendedFromComponent;
let componentChild = componentChildren[index];
if (child.extendedFromComponent) {
const component = child.getComponent();
child.referenceBlockId = componentChild.blockId;
extendWithComponent(child, child.extendedFromComponent, component.children, false);
} else if (componentChild) {
child.referenceBlockId = componentChild.blockId;
extendWithComponent(child, extendedFromComponent, componentChild.children, resetOverrides);
}
});
}
function resetWithComponent(
block: Block | BlockOptions,
extendedWithComponent: string,
componentChildren: Block[],
resetOverrides: boolean = true,
) {
resetBlock(block, true, resetOverrides);
block.children?.splice(0, block.children.length);
componentChildren.forEach((componentChild) => {
const blockComponent = getBlockCopy(componentChild);
blockComponent.isChildOfComponent = extendedWithComponent;
blockComponent.referenceBlockId = componentChild.blockId;
const childBlock = block.addChild(blockComponent, null, false);
if (componentChild.extendedFromComponent) {
const component = childBlock.getComponent();
resetWithComponent(childBlock, componentChild.extendedFromComponent, component.children, false);
} else {
resetWithComponent(childBlock, extendedWithComponent, componentChild.children, resetOverrides);
}
});
}
function syncBlockWithComponent(
parentBlock: Block,
block: Block,
componentName: string,
componentChildren: Block[],
) {
componentChildren.forEach((componentChild, index) => {
const blockExists = findComponentBlock(componentChild.blockId, parentBlock.children);
if (!blockExists) {
const blockComponent = getBlockCopy(componentChild);
blockComponent.isChildOfComponent = componentName;
blockComponent.referenceBlockId = componentChild.blockId;
resetBlock(blockComponent);
resetWithComponent(blockComponent, componentName, componentChild.children);
block.addChild(blockComponent, index, false);
}
});
block.children.forEach((child) => {
const componentChild = componentChildren.find((c) => c.blockId === child.referenceBlockId);
if (componentChild) {
syncBlockWithComponent(parentBlock, child, componentName, componentChild.children);
}
});
}
function findComponentBlock(blockId: string, blocks: Block[]): Block | null {
for (const block of blocks) {
if (block.referenceBlockId === blockId) {
return block;
}
if (block.children) {
const found = findComponentBlock(blockId, block.children);
if (found) {
return found;
}
}
}
return null;
}
function resetBlock(
block: Block | BlockOptions,
resetChildren: boolean = true,
resetOverrides: boolean = true,
) {
block = markRaw(block);
block.blockId = block.generateId();
if (resetOverrides) {
delete block.innerHTML;
delete block.element;
block.baseStyles = {};
block.rawStyles = {};
block.mobileStyles = {};
block.tabletStyles = {};
block.attributes = {};
block.customAttributes = {};
block.classes = [];
}
if (resetChildren) {
block.children?.forEach((child) => {
resetBlock(child, resetChildren, !Boolean(child.extendedFromComponent));
});
}
}
export default Block;
|
2302_79757062/builder
|
frontend/src/utils/block.ts
|
TypeScript
|
agpl-3.0
| 28,131
|
import useStore from "@/store";
import { CSSProperties, nextTick } from "vue";
import Block, { BlockDataKey } from "./block";
import getBlockTemplate from "./blockTemplate";
const store = useStore();
type styleProperty = keyof CSSProperties;
const blockController = {
clearSelection: () => {
store.activeCanvas?.clearSelection();
},
getFirstSelectedBlock: () => {
return store.activeCanvas?.selectedBlocks[0] as Block;
},
getSelectedBlocks: () => {
return store.activeCanvas?.selectedBlocks || [];
},
isRoot() {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().isRoot();
},
isFlex() {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().isFlex();
},
isGrid() {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().isGrid();
},
setStyle: (style: styleProperty, value: StyleValue) => {
store.activeCanvas?.selectedBlocks.forEach((block) => {
block.setStyle(style, value);
});
},
setBaseStyle: (style: styleProperty, value: StyleValue) => {
store.activeCanvas?.selectedBlocks.forEach((block) => {
block.setBaseStyle(style, value);
});
},
getStyle: (style: styleProperty) => {
let styleValue = "__initial__" as StyleValue;
store.activeCanvas?.selectedBlocks.forEach((block) => {
if (styleValue === "__initial__") {
styleValue = block.getStyle(style);
} else if (styleValue !== block.getStyle(style)) {
styleValue = "Mixed";
}
});
return styleValue;
},
getNativeStyle: (style: styleProperty) => {
let styleValue = "__initial__" as StyleValue;
store.activeCanvas?.selectedBlocks.forEach((block) => {
if (styleValue === "__initial__") {
styleValue = block.getNativeStyle(style);
} else if (styleValue !== block.getNativeStyle(style)) {
styleValue = "Mixed";
}
});
return styleValue;
},
isBLockSelected: () => {
return store.activeCanvas?.selectedBlocks.length || 0 > 0;
},
multipleBlocksSelected: () => {
return store.activeCanvas?.selectedBlocks && store.activeCanvas?.selectedBlocks.length > 1;
},
isText: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().isText();
},
isContainer: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().isContainer();
},
isImage: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().isImage();
},
isVideo: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().isVideo();
},
isButton: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().isButton();
},
isLink: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().isLink();
},
isInput: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().isInput();
},
getAttribute: (attribute: string) => {
let attributeValue = "__initial__" as StyleValue;
store.activeCanvas?.selectedBlocks.forEach((block) => {
if (attributeValue === "__initial__") {
attributeValue = block.getAttribute(attribute);
} else if (attributeValue !== block.getAttribute(attribute)) {
attributeValue = "Mixed";
}
});
return attributeValue;
},
setAttribute: (attribute: string, value: string) => {
store.activeCanvas?.selectedBlocks.forEach((block) => {
block.setAttribute(attribute, value);
});
},
removeAttribute: (attribute: string) => {
store.activeCanvas?.selectedBlocks.forEach((block) => {
block.removeAttribute(attribute);
});
},
getKeyValue: (key: "element" | "innerHTML" | "visibilityCondition") => {
let keyValue = "__initial__" as StyleValue | undefined;
store.activeCanvas?.selectedBlocks.forEach((block) => {
if (keyValue === "__initial__") {
keyValue = block[key];
} else if (keyValue !== block[key]) {
keyValue = "Mixed";
}
});
return keyValue;
},
setKeyValue: (key: "element" | "innerHTML" | "visibilityCondition", value: string) => {
store.activeCanvas?.selectedBlocks.forEach((block) => {
if (key === "element" && block.blockName === "container") {
// reset blockName since it will not be a container anymore
delete block.blockName;
}
block[key] = value;
});
},
getClasses: () => {
let classes = [] as string[];
if (blockController.isBLockSelected()) {
classes = blockController.getFirstSelectedBlock().getClasses() || [];
}
return classes;
},
setClasses: (classes: string[]) => {
const block = store.activeCanvas?.selectedBlocks[0];
if (!block) return;
block.classes = classes;
},
getRawStyles: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().getRawStyles();
},
setRawStyles: (rawStyles: BlockStyleMap) => {
store.activeCanvas?.selectedBlocks.forEach((block) => {
Object.keys(block.rawStyles).forEach((key) => {
if (!rawStyles[key]) {
delete block.rawStyles[key];
}
});
Object.assign(block.rawStyles, rawStyles);
});
},
getCustomAttributes: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().getCustomAttributes();
},
setCustomAttributes: (customAttributes: BlockAttributeMap) => {
store.activeCanvas?.selectedBlocks.forEach((block) => {
Object.keys(block.customAttributes).forEach((key) => {
if (!customAttributes[key]) {
delete block.customAttributes[key];
}
});
Object.assign(block.customAttributes, customAttributes);
});
},
getParentBlock: () => {
return store.activeCanvas?.selectedBlocks[0]?.getParentBlock();
},
setTextColor: (color: string) => {
store.activeCanvas?.selectedBlocks.forEach((block) => {
block.setTextColor(color);
});
},
getTextColor: () => {
let color = "__initial__" as StyleValue;
store.activeCanvas?.selectedBlocks.forEach((block) => {
if (color === "__initial__") {
color = block.getTextColor();
} else if (color !== block.getTextColor()) {
color = "Mixed";
}
});
return color;
},
setFontFamily: (value: string) => {
store.activeCanvas?.selectedBlocks.forEach((block) => {
block.setFontFamily(value);
});
},
getFontFamily: () => {
let fontFamily = "__initial__" as StyleValue;
store.activeCanvas?.selectedBlocks.forEach((block) => {
if (fontFamily === "__initial__") {
fontFamily = block.getFontFamily();
} else if (fontFamily !== block.getFontFamily()) {
fontFamily = "Mixed";
}
});
return fontFamily;
},
isHTML: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().isHTML();
},
getInnerHTML: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().getInnerHTML();
},
setInnerHTML: (value: string) => {
store.activeCanvas?.selectedBlocks.forEach((block) => {
block.setInnerHTML(value);
});
},
getTextContent: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().getTextContent();
},
setDataKey: (key: keyof BlockDataKey, value: string) => {
store.activeCanvas?.selectedBlocks.forEach((block) => {
block.setDataKey(key, value);
});
},
getDataKey: (key: keyof BlockDataKey) => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().getDataKey(key);
},
isRepeater: () => {
return blockController.isBLockSelected() && blockController.getFirstSelectedBlock().isRepeater();
},
getPadding: () => {
let padding = "__initial__" as StyleValue;
blockController.getSelectedBlocks().forEach((block) => {
if (padding === "__initial__") {
padding = block.getPadding();
} else if (padding !== block.getPadding()) {
padding = "Mixed";
}
});
return padding;
},
setPadding: (value: string) => {
blockController.getSelectedBlocks().forEach((block) => {
block.setPadding(value);
});
},
getMargin: () => {
let margin = "__initial__" as StyleValue;
blockController.getSelectedBlocks().forEach((block) => {
if (margin === "__initial__") {
margin = block.getMargin();
} else if (margin !== block.getMargin()) {
margin = "Mixed";
}
});
return margin;
},
setMargin: (value: string) => {
blockController.getSelectedBlocks().forEach((block) => {
block.setMargin(value);
});
},
toggleAttribute: (attribute: string) => {
store.activeCanvas?.selectedBlocks.forEach((block) => {
if (block.getAttribute(attribute) !== undefined) {
block.removeAttribute(attribute);
} else {
block.setAttribute(attribute, "");
}
});
},
convertToLink: () => {
blockController.getSelectedBlocks().forEach((block: Block) => {
if (block.isSVG() || block.isImage()) {
const parentBlock = block.getParentBlock();
if (!parentBlock) return;
const newBlockObj = getBlockTemplate("fit-container");
const newBlock = parentBlock.addChild(newBlockObj, parentBlock.getChildIndex(block));
newBlock.addChild(block);
parentBlock.removeChild(block);
newBlock.convertToLink();
nextTick(() => {
newBlock.selectBlock();
});
} else {
block.convertToLink();
}
});
},
unsetLink: () => {
blockController.getSelectedBlocks().forEach((block) => {
block.unsetLink();
});
},
};
export default blockController;
|
2302_79757062/builder
|
frontend/src/utils/blockController.ts
|
TypeScript
|
agpl-3.0
| 9,315
|
function getBlockTemplate(
type:
| "html"
| "text"
| "image"
| "container"
| "body"
| "fit-container"
| "fallback-component"
| "repeater"
| "video",
): BlockOptions {
switch (type) {
case "html":
return {
name: "HTML",
element: "div",
originalElement: "__raw_html__",
innerHTML: `<div style="color: #8e8e8e;background: #f4f4f4;display:flex;flex-direction:column;position:static;top:auto;left:auto;width: 200px;height: 155px;align-items:center;font-size:18px;justify-content:center"><p><paste html></p></div>`,
baseStyles: {
height: "fit-content",
width: "fit-content",
} as BlockStyleMap,
};
case "text":
return {
name: "Text",
element: "p",
innerHTML: "Text",
baseStyles: {
fontSize: "16px",
width: "fit-content",
height: "fit-content",
lineHeight: "1.4",
minWidth: "10px",
} as BlockStyleMap,
};
case "image":
return {
name: "Image",
element: "img",
baseStyles: {
objectFit: "cover",
flexShrink: 0,
} as BlockStyleMap,
};
case "container":
return {
name: "Container",
element: "div",
blockName: "container",
baseStyles: {
display: "flex",
flexDirection: "column",
flexShrink: 0,
overflow: "hidden",
} as BlockStyleMap,
};
case "body":
return {
element: "div",
originalElement: "body",
attributes: {} as BlockAttributeMap,
baseStyles: {
display: "flex",
flexWrap: "wrap",
flexShrink: 0,
flexDirection: "column",
alignItems: "center",
} as BlockStyleMap,
blockId: "root",
};
case "fit-container":
return {
name: "Container",
element: "div",
blockName: "container",
baseStyles: {
display: "flex",
flexDirection: "column",
flexShrink: 0,
height: "fit-content",
width: "fit-content",
overflow: "hidden",
} as BlockStyleMap,
};
case "fallback-component":
return {
name: "HTML",
element: "p",
originalElement: "__raw_html__",
innerHTML: `<div style="color: red;background: #f4f4f4;display:flex;flex-direction:column;position:static;top:auto;left:auto;width: 600px;height: 275px;align-items:center;font-size: 30px;justify-content:center"><p>Component missing</p></div>`,
baseStyles: {
height: "fit-content",
width: "fit-content",
} as BlockStyleMap,
};
case "repeater":
return {
name: "Repeater",
element: "div",
blockName: "repeater",
baseStyles: {
display: "flex",
flexDirection: "column",
width: "100%",
flexShrink: 0,
minHeight: "300px",
overflow: "hidden",
} as BlockStyleMap,
isRepeaterBlock: true,
};
case "video":
return {
name: "Video",
element: "video",
attributes: {
autoplay: "",
muted: "",
} as BlockAttributeMap,
baseStyles: {
objectFit: "cover",
} as BlockStyleMap,
};
}
}
export default getBlockTemplate;
|
2302_79757062/builder
|
frontend/src/utils/blockTemplate.ts
|
TypeScript
|
agpl-3.0
| 2,987
|
function convertHTMLToBlocks(html: string, skipBody = false) {
const start = html.indexOf("```");
let htmlStripped;
if (start === -1) {
htmlStripped = html;
} else {
const end = html.lastIndexOf("```");
htmlStripped = html.substring(start + 3, end);
}
const doc = new DOMParser().parseFromString(htmlStripped, "text/html");
const { body } = doc;
return parseElement(body, skipBody);
}
function parseElement(element: HTMLElement, skipBody = false): BlockOptions {
const tag = element.tagName.toLowerCase();
const obj: BlockOptions = {
element: tag,
};
if (tag === "body") {
if (skipBody) {
return parseElement(element.children[0] as HTMLElement);
}
obj.originalElement = "body";
obj.element = "div";
}
if (element.style.length) {
obj.styles = {};
for (let i = 0; i < element.style.length; i++) {
const prop = element.style[i];
obj.styles[prop] = element.style.getPropertyValue(prop);
}
}
if (element.attributes.length) {
obj.attributes = {};
for (let i = 0; i < element.attributes.length; i++) {
const attr = element.attributes[i];
if (attr.name !== "style") {
obj.attributes[attr.name] = attr.value;
}
}
}
// classes
if (element.classList.length) {
obj.classes = [];
for (let i = 0; i < element.classList.length; i++) {
obj.classes.push(element.classList[i]);
}
}
if (element.hasChildNodes()) {
obj.children = [];
const { childNodes } = element;
for (let i = 0; i < childNodes.length; i++) {
const child = childNodes[i] as HTMLElement;
if (child.nodeType === Node.ELEMENT_NODE) {
obj.children.push(parseElement(child));
} else if (child.nodeType === Node.TEXT_NODE) {
obj.innerHTML = (child.textContent || "").trim();
}
}
}
return obj;
}
window.convertHTMLToBlocks = convertHTMLToBlocks;
declare global {
interface Window {
convertHTMLToBlocks: typeof convertHTMLToBlocks;
}
}
export default convertHTMLToBlocks;
|
2302_79757062/builder
|
frontend/src/utils/convertHTMLToBlocks.ts
|
TypeScript
|
agpl-3.0
| 1,936
|
import fontList from "@/utils/fontList.json";
import WebFont from "webfontloader";
// TODO: Remove limit on font list
const fontListNames = fontList.items.filter((f) => f.variants.length >= 3).map((font) => font.family);
const requestedFonts = new Set<string>();
const isFontRequested = (font: string) => {
return requestedFonts.has(font);
};
const setFontRequested = (font: string) => {
requestedFonts.add(font);
};
const setFont = (font: string | null, weight: string | null) => {
return new Promise((resolve) => {
if (!font) {
return resolve(font);
}
if (typeof weight !== "string") {
weight = null;
}
weight = weight || "400";
if (weight && ["100", "200", "300", "400", "500", "600", "700", "800", "900"].includes(weight)) {
font = `${font}:${weight}`;
}
if (isFontRequested(font)) {
return resolve(font);
}
setFontRequested(font);
WebFont.load({
google: {
families: [font],
crossOrigin: "anonymous",
},
active: resolve(font),
});
});
};
const getFontWeightOptions = (font: string) => {
const defaultOptions = [{ value: "400", label: "Regular" }];
if (!font) {
return defaultOptions;
}
const fontObj = fontList.items.find((f) => f.family === font);
if (!fontObj) {
return defaultOptions;
}
return fontObj.variants
.filter((variant) => !variant.includes("italic"))
.map((variant) => {
switch (variant) {
case "regular":
return {
value: "400",
label: "Regular",
};
case "100":
return {
value: "100",
label: "Thin",
};
case "200":
return {
value: "200",
label: "Extra Light",
};
case "300":
return {
value: "300",
label: "Light",
};
case "400":
return {
value: "400",
label: "Regular",
};
case "500":
return {
value: "500",
label: "Medium",
};
case "600":
return {
value: "600",
label: "Semi Bold",
};
case "700":
return {
value: "700",
label: "Bold",
};
case "800":
return {
value: "800",
label: "Extra Bold",
};
case "900":
return {
value: "900",
label: "Black",
};
default:
return {
value: variant,
label: variant,
};
}
});
};
function setFontFromHTML(html: string) {
const fontFamilies = html.match(/font-family: ([^;"]+)["|;]/g)?.map((fontFamily) => {
return fontFamily.replace(/font-family: ([^;"]+)["|;]/, "$1");
});
if (fontFamilies) {
fontFamilies.forEach((fontFamily) => {
setFont(fontFamily, null);
});
}
}
export { fontListNames, getFontWeightOptions, setFont, setFontFromHTML };
|
2302_79757062/builder
|
frontend/src/utils/fontManager.ts
|
TypeScript
|
agpl-3.0
| 2,678
|
import { useElementBounding } from "@vueuse/core";
import { reactive } from "vue";
import useStore from "../store";
const store = useStore();
const tracks = [
{
point: 0,
strength: 10,
},
{
point: 0.25,
strength: 2,
},
{
point: 0.5,
strength: 10,
},
{
point: 0.75,
strength: 2,
},
{
point: 1,
strength: 10,
},
];
function setGuides(target: HTMLElement | SVGElement, canvasProps: CanvasProps) {
const threshold = 10;
// TODO: Remove canvas dependency
const canvasElement = target.closest(".canvas") as HTMLElement;
const canvasBounds = reactive(useElementBounding(canvasElement));
const targetBounds = reactive(useElementBounding(target));
const parentBounds = reactive(useElementBounding(target.parentElement as HTMLElement));
const getFinalWidth = (calculatedWidth: number) => {
targetBounds.update();
canvasBounds.update();
parentBounds.update();
const { scale } = canvasProps;
const targetRight = targetBounds.left + calculatedWidth * scale;
let finalWidth = calculatedWidth;
let set = false;
tracks.forEach((track) => {
const canvasRight = canvasBounds.left + canvasBounds.width * track.point;
const parentRight = parentBounds.left + parentBounds.width * track.point;
if (Math.abs(targetRight - canvasRight) < track.strength) {
finalWidth = (canvasRight - targetBounds.left) / scale;
store.guides.x = canvasRight;
set = true;
} else if (Math.abs(targetRight - parentRight) < track.strength) {
finalWidth = (parentRight - targetBounds.left) / scale;
store.guides.x = parentRight;
set = true;
}
});
if (!set) {
store.guides.x = -1;
}
return Math.round(finalWidth);
};
const getFinalHeight = (calculatedHeight: number) => {
targetBounds.update();
canvasBounds.update();
parentBounds.update();
const { scale } = canvasProps;
const targetBottom = targetBounds.top + calculatedHeight * scale;
let finalHeight = calculatedHeight;
let set = false;
tracks.forEach((track) => {
const canvasBottom = canvasBounds.top + canvasBounds.height * track.point;
const parentBottom = parentBounds.top + parentBounds.height * track.point;
if (Math.abs(targetBottom - canvasBottom) < track.strength) {
finalHeight = (canvasBottom - targetBounds.top) / scale;
store.guides.y = canvasBottom;
set = true;
} else if (Math.abs(targetBottom - parentBottom) < track.strength) {
finalHeight = (parentBottom - targetBounds.top) / scale;
store.guides.y = parentBottom;
set = true;
}
});
if (!set) {
store.guides.y = -1;
}
return Math.round(finalHeight);
};
const getPositionOffset = () => {
targetBounds.update();
canvasBounds.update();
let { scale } = canvasProps;
let leftOffset = 0;
let rightOffset = 0;
const canvasHalf = canvasBounds.left + canvasBounds.width / 2;
if (Math.abs(targetBounds.left - canvasBounds.left) < threshold) {
leftOffset = (canvasBounds.left - targetBounds.left) / scale;
store.guides.x = canvasBounds.left;
}
if (Math.abs(targetBounds.left - canvasHalf) < threshold) {
leftOffset = (canvasHalf - targetBounds.left) / scale;
store.guides.x = canvasHalf;
}
if (Math.abs(targetBounds.left - canvasBounds.right) < threshold) {
leftOffset = (canvasBounds.right - targetBounds.left) / scale;
store.guides.x = canvasBounds.right;
}
if (Math.abs(targetBounds.right - canvasBounds.left) < threshold) {
rightOffset = (canvasBounds.left - targetBounds.right) / scale;
store.guides.x = canvasBounds.left;
}
if (Math.abs(targetBounds.right - canvasHalf) < threshold) {
rightOffset = (canvasHalf - targetBounds.right) / scale;
store.guides.x = canvasHalf;
}
if (Math.abs(targetBounds.right - canvasBounds.right) < threshold) {
rightOffset = (canvasBounds.right - targetBounds.right) / scale;
store.guides.x = canvasBounds.right;
}
if ((leftOffset && rightOffset) || (!leftOffset && !rightOffset)) {
store.guides.x = -1;
}
return { leftOffset: Math.round(leftOffset), rightOffset: Math.round(rightOffset) };
};
const showX = () => {
store.guides.x = -1;
store.guides.showX = true;
};
const showY = () => {
store.guides.y = -1;
store.guides.showY = true;
};
const hideX = () => {
store.guides.showX = false;
};
const hideY = () => {
store.guides.showY = false;
};
return {
getFinalWidth,
getFinalHeight,
showX,
showY,
hideX,
hideY,
getPositionOffset,
};
}
export default setGuides;
|
2302_79757062/builder
|
frontend/src/utils/guidesTracker.ts
|
TypeScript
|
agpl-3.0
| 4,475
|
import { confirmDialog } from "frappe-ui";
import { reactive, toRaw } from "vue";
import Block from "./block";
function getNumberFromPx(px: string | number | null | undefined): number {
if (!px) {
return 0;
}
if (typeof px === "number") {
return px;
}
const number = Number(px.replace("px", ""));
if (isNaN(number)) {
return 0;
}
return number;
}
function addPxToNumber(number: number, round: boolean = true): string {
number = round ? Math.round(number) : number;
return `${number}px`;
}
function HexToHSV(color: HashString): { h: number; s: number; v: number } {
const [r, g, b] = color
.replace("#", "")
.match(/.{1,2}/g)
?.map((x) => parseInt(x, 16)) || [0, 0, 0];
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const v = max / 255;
const d = max - min;
const s = max === 0 ? 0 : d / max;
const h =
max === min
? 0
: max === r
? (g - b) / d + (g < b ? 6 : 0)
: max === g
? (b - r) / d + 2
: (r - g) / d + 4;
return { h: h * 60, s, v };
}
function HSVToHex(h: number, s: number, v: number): HashString {
s /= 100;
v /= 100;
h /= 360;
let r = 0,
g = 0,
b = 0;
let i = Math.floor(h * 6);
let f = h * 6 - i;
let p = v * (1 - s);
let q = v * (1 - f * s);
let t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
(r = v), (g = t), (b = p);
break;
case 1:
(r = q), (g = v), (b = p);
break;
case 2:
(r = p), (g = v), (b = t);
break;
case 3:
(r = p), (g = q), (b = v);
break;
case 4:
(r = t), (g = p), (b = v);
break;
case 5:
(r = v), (g = p), (b = q);
break;
}
r = Math.round(r * 255);
g = Math.round(g * 255);
b = Math.round(b * 255);
return `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
}
function getRandomColor() {
return HSVToHex(Math.random() * 360, 25, 100);
}
async function confirm(message: string, title: string = "Confirm"): Promise<boolean> {
return new Promise((resolve) => {
confirmDialog({
title: title,
message: message,
onConfirm: ({ hideDialog }: { hideDialog: Function }) => {
resolve(true);
hideDialog();
},
});
});
}
function getTextContent(html: string | null) {
if (!html || !isHTMLString(html)) {
return html || "";
}
const tmp = document.createElement("div");
tmp.innerHTML = html || "";
const textContent = tmp.textContent || tmp.innerText || "";
tmp.remove();
return textContent;
}
function RGBToHex(rgb: RGBString): HashString {
const [r, g, b] = rgb
.replace("rgb(", "")
.replace(")", "")
.split(",")
.map((x) => parseInt(x));
return `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
}
function getRGB(color: HashString | RGBString | string | null): HashString | null {
if (!color) {
return null;
}
if (color.startsWith("rgb")) {
return RGBToHex(color as RGBString);
} else if (!color.startsWith("#") && color.match(/\b[a-fA-F0-9]{3,6}\b/g)) {
return `#${color}` as HashString;
}
return color as HashString;
}
function isHTMLString(str: string) {
return /<[a-z][\s\S]*>/i.test(str);
}
function copyToClipboard(text: string | object, e: ClipboardEvent, copyFormat = "text/plain") {
if (typeof text !== "string") {
text = JSON.stringify(text);
}
e.clipboardData?.setData(copyFormat, text);
}
function stripExtension(string: string) {
const lastDotPosition = string.lastIndexOf(".");
if (lastDotPosition === -1) {
return string;
}
return string.substr(0, lastDotPosition);
}
function findNearestSiblingIndex(e: MouseEvent) {
let nearestElementIndex = 0;
let minDistance = Number.MAX_VALUE;
let parent = e.target as HTMLElement;
const elements = Array.from(parent.children);
elements.forEach(function (element, index) {
const rect = element.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const distance = Math.sqrt(Math.pow(centerX - e.clientX, 2) + Math.pow(centerY - e.clientY, 2));
if (distance < minDistance) {
minDistance = distance;
nearestElementIndex = index;
const positionBitmask = element.compareDocumentPosition(e.target as Node);
// sourcery skip: possible-incorrect-bitwise-operator
if (positionBitmask & Node.DOCUMENT_POSITION_PRECEDING) {
// before
} else {
nearestElementIndex += 1;
}
}
});
return nearestElementIndex;
}
// converts border-color to borderColor
function kebabToCamelCase(str: string) {
return str.replace(/-([a-z])/g, function (g) {
return g[1].toUpperCase();
});
}
function isJSONString(str: string) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function isTargetEditable(e: Event) {
const target = e.target as HTMLElement;
const isEditable = target.isContentEditable;
const isInput = target.tagName === "INPUT" || target.tagName === "TEXTAREA";
return isEditable || isInput;
}
function getDataForKey(datum: Object, key: string) {
const data = Object.assign({}, datum);
return key.split(".").reduce((d, key) => (d ? d[key] : null), data) as string;
}
function replaceMapKey(map: Map<any, any>, oldKey: string, newKey: string) {
const newMap = new Map();
map.forEach((value, key) => {
if (key === oldKey) {
newMap.set(newKey, value);
} else {
newMap.set(key, value);
}
});
return newMap;
}
const mapToObject = (map: Map<any, any>) => Object.fromEntries(map.entries());
function logObjectDiff(obj1: { [key: string]: {} }, obj2: { [key: string]: {} }, path = []) {
if (!obj1 || !obj2) return;
for (const key in obj1) {
const newPath = path.concat(key);
if (obj2.hasOwnProperty(key)) {
if (typeof obj1[key] === "object" && typeof obj2[key] === "object") {
logObjectDiff(obj1[key], obj2[key], newPath);
} else {
if (obj1[key] !== obj2[key]) {
console.log(`Difference at ${newPath.join(".")} - ${obj1[key]} !== ${obj2[key]}`);
}
}
} else {
// console.log(`Property ${newPath.join(".")} is missing in the second object`);
}
}
for (const key in obj2) {
if (!obj1.hasOwnProperty(key)) {
// console.log(`Property ${key} is missing in the first object`);
}
}
}
function getBlockInstance(options: BlockOptions | string, retainId = true): Block {
if (typeof options === "string") {
options = JSON.parse(options) as BlockOptions;
}
if (!retainId) {
const deleteBlockId = (block: BlockOptions) => {
delete block.blockId;
for (let child of block.children || []) {
deleteBlockId(child);
}
};
deleteBlockId(options);
}
return reactive(new Block(options));
}
function getBlockCopy(block: BlockOptions | Block, retainId = false): Block {
const b = getBlockObjectCopy(block);
return getBlockInstance(b, retainId);
}
function isCtrlOrCmd(e: KeyboardEvent) {
return e.ctrlKey || e.metaKey;
}
const detachBlockFromComponent = (block: Block) => {
const blockCopy = getBlockCopy(block, true);
const component = block.getComponent();
blockCopy.element = block?.getElement();
blockCopy.attributes = block.getAttributes();
blockCopy.classes = block.getClasses();
blockCopy.baseStyles = component?.baseStyles
? { ...component.baseStyles, ...block.baseStyles }
: block.baseStyles;
blockCopy.mobileStyles = component?.mobileStyles
? { ...component.mobileStyles, ...block.mobileStyles }
: block.mobileStyles;
blockCopy.tabletStyles = component?.tabletStyles
? { ...component.tabletStyles, ...block.tabletStyles }
: block.tabletStyles;
blockCopy.customAttributes = component?.customAttributes
? { ...component.customAttributes, ...block.customAttributes }
: block.customAttributes;
blockCopy.rawStyles = component?.rawStyles
? { ...component.rawStyles, ...block.rawStyles }
: block.rawStyles;
blockCopy.isRepeaterBlock = component?.isRepeaterBlock || block.isRepeaterBlock;
blockCopy.visibilityCondition = component?.visibilityCondition || block.visibilityCondition;
blockCopy.innerHTML = block.innerHTML || component?.innerHTML;
delete blockCopy.extendedFromComponent;
delete blockCopy.isChildOfComponent;
delete blockCopy.referenceBlockId;
blockCopy.children = blockCopy.children.map(detachBlockFromComponent);
return getBlockInstance(blockCopy);
};
function getBlockString(block: BlockOptions | Block): string {
return JSON.stringify(getCopyWithoutParent(block));
}
function getBlockObjectCopy(block: BlockOptions | Block): BlockOptions {
return JSON.parse(getBlockString(block));
}
function getCopyWithoutParent(block: BlockOptions | Block): BlockOptions {
const blockCopy = { ...toRaw(block) };
blockCopy.children = blockCopy.children?.map((child) => getCopyWithoutParent(child));
delete blockCopy.parentBlock;
return blockCopy;
}
export {
addPxToNumber,
confirm,
copyToClipboard,
detachBlockFromComponent,
findNearestSiblingIndex,
getBlockCopy,
getBlockInstance,
getBlockObjectCopy as getBlockObject,
getBlockString,
getCopyWithoutParent,
getDataForKey,
getNumberFromPx,
getRandomColor,
getRGB,
getTextContent,
HexToHSV,
HSVToHex,
isCtrlOrCmd,
isHTMLString,
isJSONString,
isTargetEditable,
kebabToCamelCase,
logObjectDiff,
mapToObject,
replaceMapKey,
RGBToHex,
stripExtension,
};
|
2302_79757062/builder
|
frontend/src/utils/helpers.ts
|
TypeScript
|
agpl-3.0
| 9,108
|