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
|
|---|---|---|---|---|---|
import os
import frappe
from datetime import datetime, timedelta
import uuid
import mimetypes
import json
import base64
import magic
from pathlib import Path
from frappe.utils import get_site_path
from frappe.utils import cint
from werkzeug.wrappers import Response
from werkzeug.utils import secure_filename
from drive.api.files import (
get_user_directory,
create_drive_entity,
)
from drive.utils.files import create_thumbnail
@frappe.whitelist(allow_guest=True, methods=["PATCH", "HEAD", "POST", "GET" "OPTIONS", "GET"])
def handle_tus_request(fileID=None):
tus_version = "1.0.0"
tus_checksum_algorithm = "md5,sha1,crc32"
tus_extension = "creation,creation-defer-length,creation-with-upload,expiration,termination"
current_site_url = frappe.utils.get_url() + "/api/method/drive.api.upload.handle_tus_request"
# Lowest is 20MB
# Read site.config to check if bigger payload size is allowed
max_size = 20 * 1024 * 1024 # 20MB
expiry = 259200 # 3 days
response = Response(frappe.request.environ)
if frappe.request.method == "HEAD":
"""
Fetch information about a prior upload and get the offset head
"""
meta = frappe.cache.exists(f"drive_{fileID}")
if meta is None:
response.status_code = 404
return
response.headers.add("Tus-Extension", tus_extension)
response.headers.add("Tus-Resumable", tus_version)
response.headers.add("Tus-Version", tus_version)
response.headers.add("Tus-Max-Size", str(max_size))
response.headers.add(
"Upload-Offset", str(frappe.cache.hget(f"drive_{fileID}", "upload_offset"))
)
response.headers.add("Upload-Length", str(frappe.cache.hget(f"drive_{fileID}", "size")))
response.headers.add("Content-Length", str(frappe.cache.hget(f"drive_{fileID}", "size")))
response.status_code = 200
return response
if frappe.request.method == "POST":
"""
pre-init/preflight checks(perms, server availability)
check if file/folder exists in the specified parent already
create parent folders if webkitRelativePath/fullPath
init an upload session, process the metadata
"""
init_file_id = str(uuid.uuid4())
upload_metadata = frappe.request.headers.get("Upload-Metadata")
upload_length = frappe.request.headers.get("Upload-Length")
temp_path = Path(
frappe.get_site_path(
"private/files/",
get_user_directory(user=frappe.session.user).name,
"uploads",
init_file_id,
)
)
# Parse metadata
metadata = {}
if upload_metadata is not None and upload_metadata != "":
for kv in upload_metadata.split(","):
key, value = kv.rsplit(" ", 1)
decoded_value = base64.b64decode(value.strip()).decode("utf-8")
metadata[key.strip()] = decoded_value
metadata.update(size=upload_length)
metadata.update(date_expiry=datetime.now() + timedelta(seconds=expiry))
metadata.update(upload_offset=0)
metadata.update(upload_temp_path=temp_path)
# todo: reduce extra loop?
for key, value in metadata.items():
frappe.cache.hset(f"drive_{init_file_id}", key, value)
frappe.cache.expire(f"drive_{init_file_id}", expiry)
response.status_code = 201
response.headers.add("Location", str(current_site_url + "?fileID=" + init_file_id))
response.headers.add("Tus-Max-Size", str(max_size))
return response
if frappe.request.method == "PATCH":
"""
write to file based on offset header
read magic bytes to validate type
create drive_entity
create thumbnail if video/image
"""
meta = frappe.cache.exists(f"drive_{fileID}")
if meta is None:
response.status_code = 404
return
response.status_code = 200
file = frappe.request.data
offset_counter = frappe.cache.hget(f"drive_{fileID}", "upload_offset")
temp_path = frappe.cache.hget(f"drive_{fileID}", "upload_temp_path")
# potentially add concat here for multithreading
# create a file for each chunk
# recreate the file from unordered but complete chunks that are split up into different temp files
# will most likely need chunksumming on the client (web crypto api)
with temp_path.open("ab") as f:
for chunk in frappe.request.stream:
if len(chunk) == 0:
return None
f.write(chunk)
offset_counter += len(chunk)
frappe.cache.hset(f"drive_{fileID}", "upload_offset", offset_counter)
f.close()
if str(offset_counter) == frappe.cache.hget(f"drive_{fileID}", "size"):
name = str(uuid.uuid4().hex)
title = frappe.cache.hget(f"drive_{fileID}", "name")
mime_type = magic.from_buffer(open(temp_path, "rb").read(2048), mime=True)
_, file_ext = os.path.splitext(title)
if not file_ext:
file_ext = mimetypes.guess_extension(mime_type)
file_name = name + file_ext
file_size = frappe.cache.hget(f"drive_{fileID}", "size")
last_modified = frappe.cache.hget(f"drive_{fileID}", "lastModified")
parent = frappe.cache.hget(f"drive_{fileID}", "fileParent")
if not parent:
parent = get_user_directory().name
save_path = Path(get_user_directory().path) / f"{secure_filename(file_name)}"
os.rename(temp_path, save_path)
create_drive_entity(
name, title, parent, save_path, file_size, file_ext, mime_type, last_modified
)
if mime_type.startswith(("image", "video")):
frappe.enqueue(
create_thumbnail,
queue="default",
timeout=None,
now=True,
at_front=True,
# will set to false once reactivity in new UI is solved
entity_name=name,
path=save_path,
mime_type=mime_type,
)
frappe.cache.delete(f"drive_{fileID}")
response.headers.add("Upload-Offset", offset_counter)
return response
if (
frappe.request.method == "OPTIONS"
and frappe.request.headers.get("Access-Control-Request-Method", None) is not None
):
"""
used for preflight requests simply returns the server config
"""
meta = frappe.cache.exists(f"drive_{fileID}")
if meta is None:
response.status_code = 404
return
response.headers.add("Tus-Extension", tus_extension)
response.headers.add("Tus-Resumable", tus_version)
response.headers.add("Tus-Version", tus_version)
response.headers.add("Tus-Max-Size", str(max_size))
response.headers.add("Content-Length", str(0))
response.status_code = 204
return
if frappe.request.method == "DELETE":
"""
wipe the file if it exists in the /uploads folder
"""
return response
# background job to wipe file in /uploads if expiry is up
|
2302_79757062/drive
|
drive/api/upload.py
|
Python
|
agpl-3.0
| 7,430
|
from frappe import _
def get_data():
return [
{
"module_name": "Drive",
"color": "grey",
"icon": "octicon octicon-file-directory",
"type": "module",
"label": _("Drive"),
}
]
|
2302_79757062/drive
|
drive/config/desktop.py
|
Python
|
agpl-3.0
| 260
|
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/drive"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "Drive"
|
2302_79757062/drive
|
drive/config/docs.py
|
Python
|
agpl-3.0
| 256
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Drive DocShare", {
// refresh(frm) {
// },
// });
|
2302_79757062/drive
|
drive/drive/doctype/drive_docshare/drive_docshare.js
|
JavaScript
|
agpl-3.0
| 197
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import cint, get_fullname
from drive.api.notifications import notify_share
from drive.api.notifications import notify_mentions
exclude_from_linked_with = True
class DriveDocShare(Document):
def validate(self):
self.validate_general_access()
self.cascade_permissions_downwards()
self.get_doc().run_method("validate_share", self)
self.update_children()
def get_doc(self):
if not getattr(self, "_doc", None):
self._doc = frappe.get_doc(self.share_doctype, self.share_name)
return self._doc
def cascade_permissions_downwards(self):
if self.share or self.write:
self.read = 1
def update_children(self):
children = self.get_children()
new_value = self.valid_until
for child in children:
child.valid_until = new_value
child.save()
return
def validate_general_access(self):
if self.everyone | self.public:
self.user_name = None
self.user_doctype = None
def after_insert(self):
doc = self.get_doc()
owner = get_fullname(self.owner)
entity_document = frappe.db.get_value("Drive Entity", self.share_name, ["document"])
if self.everyone:
doc.add_comment("Shared", _("{0} shared this document with everyone").format(owner))
if self.public:
doc.add_comment("Shared", _("{0} shared this document publicly").format(owner))
if self.user_doctype == "User Group":
doc.add_comment(
"Shared", _("{0} shared this document with {1}").format(owner, (self.user_name))
)
else:
doc.add_comment(
"Shared",
_("{0} shared this document with {1}").format(owner, get_fullname(self.user_name)),
)
if entity_document:
frappe.enqueue(
notify_mentions,
queue="long",
job_id=f"fdoc_{entity_document}",
deduplicate=False, # Users might've gained access here
timeout=None,
now=False,
at_front=False,
entity_name=self.share_name,
document_name=entity_document,
)
if self.share_parent is None:
frappe.enqueue(
notify_share,
queue="long",
job_id=f"fdocshare_{self.name}",
deduplicate=True,
timeout=None,
now=False,
at_front=False,
entity_name=self.share_name,
docshare_name=self.name,
)
def check_share_permission(self):
if not self.flags.ignore_share_permission and not frappe.has_permission(
self.share_doctype, "share", self.get_doc()
):
frappe.throw(_('You need to have "Share" permission'), frappe.PermissionError)
def on_trash(self):
if not self.flags.ignore_share_permission:
self.check_share_permission()
self.get_doc().add_comment(
"Unshared",
_("{0} un-shared this document with {1}").format(
get_fullname(self.owner), get_fullname(self.user_name)
),
)
def get_children(self):
"""Return a generator that yields child Documents."""
child_names = frappe.get_list(
self.doctype, filters={"share_parent": self.name}, pluck="name"
)
for name in child_names:
yield frappe.get_doc(self.doctype, name)
def on_doctype_update():
"""Add index in `tabDocShare` for `(user, document)`"""
frappe.db.add_index("Drive DocShare", ["user_doctype", "user_name"])
frappe.db.add_index("Drive DocShare", ["share_doctype", "share_name"])
|
2302_79757062/drive
|
drive/drive/doctype/drive_docshare/drive_docshare.py
|
Python
|
agpl-3.0
| 4,044
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Drive Document", {
// refresh(frm) {
// },
// });
|
2302_79757062/drive
|
drive/drive/doctype/drive_document/drive_document.js
|
JavaScript
|
agpl-3.0
| 197
|
# 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 DriveDocument(Document):
pass
|
2302_79757062/drive
|
drive/drive/doctype/drive_document/drive_document.py
|
Python
|
agpl-3.0
| 221
|
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Drive Document Version", {
// refresh(frm) {
// },
// });
|
2302_79757062/drive
|
drive/drive/doctype/drive_document_version/drive_document_version.js
|
JavaScript
|
agpl-3.0
| 205
|
# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class DriveDocumentVersion(Document):
pass
|
2302_79757062/drive
|
drive/drive/doctype/drive_document_version/drive_document_version.py
|
Python
|
agpl-3.0
| 228
|
frappe.ui.form.on('Drive Entity', {
// refresh: function(frm) {
// }
});
|
2302_79757062/drive
|
drive/drive/doctype/drive_entity/drive_entity.js
|
JavaScript
|
agpl-3.0
| 78
|
import frappe
from frappe.model.document import Document
from pathlib import Path
import shutil
import uuid
from drive.utils.files import (
get_user_directory,
create_user_directory,
get_new_title,
get_user_thumbnails_directory,
create_user_thumbnails_directory,
create_thumbnail,
)
from drive.utils.user_group import add_new_user_group_docshare, does_exist_user_group_docshare
from frappe.utils import cint
from drive.api.format import mime_to_human
from drive.api.files import get_ancestors_of
from drive.api.files import generate_upward_path
class DriveEntity(Document):
def before_save(self):
self.version = self.version + 1
def before_insert(self):
self.file_kind = mime_to_human(self.mime_type, self.is_group)
def after_insert(self):
self.inherit_permissions()
def on_trash(self):
frappe.db.delete("Drive Favourite", {"entity": self.name})
frappe.db.delete("Drive Entity Log", {"entity_name": self.name})
frappe.db.delete("Drive DocShare", {"share_name": self.name})
frappe.db.delete("Drive Notification", {"notif_doctype_name": self.name})
if self.is_group or self.document:
for child in self.get_children():
has_write_access = frappe.has_permission(
doctype="Drive Entity",
doc=self,
ptype="write",
user=frappe.session.user,
)
child.delete(ignore_permissions=has_write_access)
def after_delete(self):
if self.document:
frappe.delete_doc("Drive Document", self.document)
"""Remove file once document is deleted"""
if self.path:
max_attempts = 3
for attempt in range(max_attempts):
try:
Path(self.path).unlink()
break
except Exception as e:
print(f"Attempt {attempt + 1}: Failed to delete file - {e}")
if self.mime_type:
if self.mime_type.startswith("image") or self.mime_type.startswith("video"):
max_attempts = 3
for attempt in range(max_attempts):
try:
user_thumbnails_directory = get_user_thumbnails_directory()
thumbnail_getpath = Path(user_thumbnails_directory, self.name)
Path(str(thumbnail_getpath) + ".thumbnail").unlink()
break
except Exception as e:
print(f"Attempt {attempt + 1}: Failed to delete thumbnail - {e}")
def on_rollback(self):
if self.flags.file_created:
shutil.rmtree(self.path) if self.is_group else self.path.unlink()
def inherit_permissions(self):
"""Cascade parent permissions to new child entity"""
if self.parent_drive_entity is None:
return
permissions = frappe.get_all(
"Drive DocShare",
fields=[
"name",
"user_doctype",
"user_name",
"read",
"write",
"share",
"everyone",
"public",
"owner",
"creation",
],
filters=dict(share_doctype=self.doctype, share_name=self.parent_drive_entity),
)
parent_folder = frappe.db.get_value(
"Drive Entity",
self.parent_drive_entity,
["name", "owner", "allow_comments", "allow_download"],
as_dict=1,
)
if parent_folder.owner != frappe.session.user:
# Allow the owner of the folder to access the entity
# Defaults to write since its obvious that the current user has write access to the parent
# the subsequent for loop still creates a docShare for this uploaded entity as a side effect
# It just lingers around and is wiped on delete (find a way to avoid the side effect if possible)
self.share(
share_name=self.name,
user=parent_folder.owner,
user_type="User",
read=1,
write=1,
share=1,
notify=0,
protected=1,
)
for permission in permissions:
self.share(
share_name=self.name,
user=permission.user_name,
user_type=permission.user_doctype,
read=permission.read,
write=permission.write,
share=permission.share,
everyone=permission.everyone,
public=permission.public,
notify=0,
protected=1,
)
self.allow_comments = parent_folder.allow_comments
self.allow_download = parent_folder.allow_download
self.save()
def get_children(self):
"""Return a generator that yields child Documents."""
child_names = frappe.get_list(
self.doctype, filters={"parent_drive_entity": self.name}, pluck="name"
)
for name in child_names:
yield frappe.get_doc(self.doctype, name)
@frappe.whitelist()
def move(self, new_parent=None):
"""
Move file or folder to the new parent folder
:param new_parent: Document-name of the new parent folder. Defaults to the user directory
:raises NotADirectoryError: If the new_parent is not a folder, or does not exist
:raises FileExistsError: If a file or folder with the same name already exists in the specified parent folder
:return: DriveEntity doc once file is moved
"""
new_parent = new_parent or get_user_directory(self.owner).name
if new_parent == self.parent_drive_entity:
return self
is_group = frappe.db.get_value("Drive Entity", new_parent, "is_group")
if not is_group:
raise NotADirectoryError()
for child in self.get_children():
if child.name == self.name or new_parent:
frappe.throw(
"Cannot move into itself",
frappe.PermissionError,
)
return
self.parent_drive_entity = new_parent
title = get_new_title(self.title, new_parent)
if title != self.title:
self.rename(title)
self.inherit_permissions()
self.save()
return self
@frappe.whitelist()
def copy(self, new_parent=None, parent_user_directory=None):
"""
Copy file or folder along with its contents to the new parent folder
:param new_parent: Document-name of the new parent folder. Defaults to the user directory
:raises NotADirectoryError: If the new_parent is not a folder, or does not exist
:raises FileExistsError: If a file or folder with the same name already exists in the specified parent folder
"""
title = self.title
if not parent_user_directory:
parent_owner = (
frappe.db.get_value("Drive Entity", new_parent, "owner")
if new_parent
else frappe.session.user
)
try:
parent_user_directory = get_user_directory(parent_owner)
except FileNotFoundError:
parent_user_directory = create_user_directory()
new_parent = new_parent or parent_user_directory.name
parent_is_group = frappe.db.get_value("Drive Entity", new_parent, "is_group")
if not parent_is_group:
raise NotADirectoryError()
if not frappe.has_permission(
doctype="Drive Entity",
doc=new_parent,
ptype="write",
user=frappe.session.user,
):
frappe.throw(
"Cannot paste to this folder due to insufficient permissions",
frappe.PermissionError,
)
if self.name == new_parent or self.name in get_ancestors_of(
"Drive Entity", new_parent
):
frappe.throw("You cannot copy a folder into itself")
title = get_new_title(title, new_parent)
name = uuid.uuid4().hex
if self.is_group:
drive_entity = frappe.get_doc(
{
"doctype": "Drive Entity",
"name": name,
"title": title,
"is_group": 1,
"parent_drive_entity": new_parent,
"color": self.color,
}
)
drive_entity.insert()
for child in self.get_children():
child.copy(name, parent_user_directory)
elif self.document is not None:
drive_doc_content = frappe.db.get_value("Drive Document", self.document, "content")
new_drive_doc = frappe.new_doc("Drive Document")
new_drive_doc.title = title
new_drive_doc.content = drive_doc_content
new_drive_doc.save()
drive_entity = frappe.get_doc(
{
"doctype": "Drive Entity",
"name": name,
"title": title,
"mime_type": self.mime_type,
"parent_drive_entity": new_parent,
"document": new_drive_doc,
}
)
drive_entity.insert()
else:
save_path = Path(parent_user_directory.path) / f"{new_parent}_{title}"
if save_path.exists():
frappe.throw(f"File '{title}' already exists", FileExistsError)
shutil.copy(self.path, save_path)
path = save_path.parent / f"{name}{save_path.suffix}"
save_path.rename(path)
drive_entity = frappe.get_doc(
{
"doctype": "Drive Entity",
"name": name,
"title": title,
"parent_drive_entity": new_parent,
"path": path,
"file_size": self.file_size,
"file_ext": self.file_ext,
"mime_type": self.mime_type,
}
)
drive_entity.flags.file_created = True
drive_entity.insert()
if new_parent == parent_user_directory.name:
drive_entity.share(frappe.session.user, write=1, share=1)
if drive_entity.mime_type:
if drive_entity.mime_type.startswith("image") or drive_entity.mime_type.startswith(
"video"
):
frappe.enqueue(
create_thumbnail,
queue="default",
timeout=None,
now=True,
# will set to false once reactivity in new UI is solved
entity_name=name,
path=path,
mime_type=drive_entity.mime_type,
)
@frappe.whitelist(allow_guest=True)
def rename(self, new_title):
"""
Rename file or folder
:param new_title: New file or folder name
:raises FileExistsError: If a file or folder with the same name already exists in the parent folder
:return: DriveEntity doc once it's renamed
"""
if new_title == self.title:
return self
entity_exists = frappe.db.exists(
{
"doctype": "Drive Entity",
"parent_drive_entity": self.parent_drive_entity,
"title": new_title,
"mime_type": self.mime_type,
"is_group": self.is_group,
}
)
if entity_exists:
suggested_name = get_new_title(
new_title, self.parent_drive_entity, document=self.document, folder=self.is_group
)
frappe.throw(
f"{'Folder' if self.is_group else 'File'} '{new_title}' already exists\n Try '{suggested_name}' ",
FileExistsError,
)
return suggested_name
self.title = new_title
self.save()
return self
@frappe.whitelist()
def change_color(self, new_color):
"""
Change color of a folder
:param new_color: New color selected for folder
:raises InvalidColor: If the color is not a hex value string
:return: DriveEntity doc once it's updated
"""
return frappe.db.set_value(
"Drive Entity", self.name, "color", new_color, update_modified=False
)
@frappe.whitelist()
def set_general_access(self, read, write, everyone, public, share, share_name=None):
"""
Set general sharing access for entity
:param new_access: Dict with new read and write value
"""
if read:
if frappe.session.user == self.owner:
self.share(
share_name=share_name,
read=read,
write=write,
share=0,
everyone=everyone,
public=public,
)
else:
flags = {"ignore_permissions": True} if frappe.session.user == self.owner else None
self.unshare(user=None, user_type=None)
@frappe.whitelist()
def toggle_allow_comments(self, new_value):
"""
Toggle allow comments for entity
"""
self.allow_comments = new_value
if self.is_group:
for child in self.get_children():
child.toggle_allow_comments(new_value)
self.save()
@frappe.whitelist()
def toggle_allow_download(self, new_value):
"""
Toggle allow download for entity
"""
self.allow_download = new_value
if self.is_group:
for child in self.get_children():
child.toggle_allow_download(new_value)
self.save()
@frappe.whitelist()
def share(
self,
share_name=None,
user=None,
user_type=None,
read=1,
write=0,
share=0,
everyone=0,
public=0,
notify=0,
protected=0,
):
"""
Share this file or folder with the specified user.
If it has already been shared, update permissions.
Share defaults to one to let the non owner user unshare a file.
:param user: User with whom this is to be shared
:param write: 1 if write permission is to be granted. Defaults to 0
:param share: 1 if share permission is to be granted. Defaults to 0
:param notify: 1 if the user should be notified. Defaults to 1
"""
if frappe.session.user != self.owner:
if not frappe.has_permission(
doctype="Drive Entity",
doc=self,
ptype="share",
user=frappe.session.user,
):
for owner in get_ancestors_of(self.name):
if frappe.session.user == frappe.get_value(
"Drive Entity", {"name": owner}, ["owner"]
):
continue
else:
frappe.throw("Not permitted to share", frappe.PermissionError)
break
if user:
share_name = frappe.db.get_value(
"Drive DocShare",
{
"user_name": user,
"user_doctype": user_type,
"share_name": self.name,
"share_doctype": "Drive Entity",
},
)
if cint(public) or cint(everyone):
share_name = frappe.db.get_value(
"Drive DocShare",
{
"share_name": self.name,
"share_doctype": "Drive Entity",
"user_name": None,
"user_doctype": None,
},
)
if share_name:
doc = frappe.get_doc("Drive DocShare", share_name)
else:
doc = frappe.new_doc("Drive DocShare")
doc.update(
{
"user_name": user,
"user_doctype": user_type,
"share_doctype": "Drive Entity",
"share_name": self.name,
"everyone": cint(everyone),
"public": cint(public),
}
)
doc.update(
{
# always add read, since you are adding!
"read": 1,
"write": cint(write),
"share": cint(share),
"everyone": cint(everyone),
"public": cint(public),
"protected": cint(protected),
}
)
if frappe.db.exists(
{
"doctype": "Drive DocShare",
"share_doctype": "Drive Entity",
"share_name": self.parent_drive_entity,
"everyone": cint(everyone),
"public": cint(public),
"user_name": user,
"user_doctype": user_type,
}
):
parent_docshare = frappe.db.get_value(
"Drive DocShare",
{
"share_doctype": "Drive Entity",
"share_name": self.parent_drive_entity,
"everyone": cint(everyone),
"public": cint(public),
"user_name": user,
"user_doctype": user_type,
},
"name",
)
doc.update({"owner_parent": parent_docshare, "share_parent": parent_docshare})
doc.save(ignore_permissions=True)
if self.is_group:
for child in self.get_children():
child.share(
user=user,
user_type=user_type,
read=read,
write=write,
share=share,
everyone=everyone,
public=public,
)
@frappe.whitelist()
def unshare(self, user, user_type="User"):
"""Unshare this file or folder with the specified user
:param user: User or group with whom this is to be shared
:param user_type:
"""
if user:
if user != self.owner and frappe.session.user != self.owner:
shared_parent = frappe.db.exists(
"Drive DocShare",
{
"user_name": user,
"user_doctype": user_type,
"share_name": self.parent_drive_entity,
"share_doctype": "Drive Entity",
},
)
if shared_parent:
return
absolute_path = generate_upward_path(self.name)
for i in absolute_path:
if i.owner == user:
frappe.throw("User owns parent folder", frappe.PermissionError)
share_name = frappe.db.get_value(
"Drive DocShare",
{
"user_name": user,
"user_doctype": user_type,
"share_name": self.name,
"share_doctype": "Drive Entity",
},
)
else:
share_name = frappe.db.get_value(
"Drive DocShare",
{
"share_name": self.name,
"share_doctype": "Drive Entity",
"user_name": None,
"user_doctype": None,
},
)
if share_name:
if frappe.session.user == user or frappe.session.user == self.owner:
frappe.db.delete("Drive DocShare", share_name)
else:
frappe.delete_doc("Drive DocShare", share_name, ignore_permissions=True)
if self.is_group:
for child in self.get_children():
child.unshare(user, user_type)
def on_doctype_update():
frappe.db.add_index("Drive Entity", ["title"])
|
2302_79757062/drive
|
drive/drive/doctype/drive_entity/drive_entity.py
|
Python
|
agpl-3.0
| 20,535
|
import frappe
from drive.api.format import mime_to_human
def execute():
all_entities = frappe.db.get_all(
"Drive Entity", fields=["name", "mime_type", "file_kind", "is_group"]
)
for i in all_entities:
eval = mime_to_human(i.mime_type, i.is_group)
frappe.db.set_value("Drive Entity", i.name, "file_kind", eval, update_modified=False)
|
2302_79757062/drive
|
drive/drive/doctype/drive_entity/patches/set_file_kind.py
|
Python
|
agpl-3.0
| 371
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Drive Entity Log", {
// refresh(frm) {
// },
// });
|
2302_79757062/drive
|
drive/drive/doctype/drive_entity_log/drive_entity_log.js
|
JavaScript
|
agpl-3.0
| 199
|
# 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 DriveEntityLog(Document):
pass
|
2302_79757062/drive
|
drive/drive/doctype/drive_entity_log/drive_entity_log.py
|
Python
|
agpl-3.0
| 222
|
# 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 DriveEntityTag(Document):
pass
|
2302_79757062/drive
|
drive/drive/doctype/drive_entity_tag/drive_entity_tag.py
|
Python
|
agpl-3.0
| 222
|
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Drive Favourite", {
// refresh(frm) {
// },
// });
|
2302_79757062/drive
|
drive/drive/doctype/drive_favourite/drive_favourite.js
|
JavaScript
|
agpl-3.0
| 198
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class DriveFavourite(Document):
pass
|
2302_79757062/drive
|
drive/drive/doctype/drive_favourite/drive_favourite.py
|
Python
|
agpl-3.0
| 222
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Drive Instance Settings", {
// refresh(frm) {
// },
// });
|
2302_79757062/drive
|
drive/drive/doctype/drive_instance_settings/drive_instance_settings.js
|
JavaScript
|
agpl-3.0
| 206
|
# 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 DriveInstanceSettings(Document):
pass
|
2302_79757062/drive
|
drive/drive/doctype/drive_instance_settings/drive_instance_settings.py
|
Python
|
agpl-3.0
| 229
|
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Drive Notification", {
// refresh(frm) {
// },
// });
|
2302_79757062/drive
|
drive/drive/doctype/drive_notification/drive_notification.js
|
JavaScript
|
agpl-3.0
| 201
|
# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
class DriveNotification(Document):
def before_save(self):
if frappe.db.exists(
{
"doctype": "Drive Notification",
"from_user": self.from_user,
"to_user": self.to_user,
"type": self.type,
"notif_doctype_name": self.notif_doctype_name,
}
):
frappe.throw("Duplicate Notification")
|
2302_79757062/drive
|
drive/drive/doctype/drive_notification/drive_notification.py
|
Python
|
agpl-3.0
| 593
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Drive Tag", {
// refresh(frm) {
// },
// });
|
2302_79757062/drive
|
drive/drive/doctype/drive_tag/drive_tag.js
|
JavaScript
|
agpl-3.0
| 192
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
from drive.api.tags import remove_tag
class DriveTag(Document):
def on_trash(self):
drive_entities = frappe.db.get_list(
"Drive Entity", filters={"owner": self.owner}, pluck="name"
)
for entity in drive_entities:
remove_tag(entity, self.name)
|
2302_79757062/drive
|
drive/drive/doctype/drive_tag/drive_tag.py
|
Python
|
agpl-3.0
| 475
|
from . import __version__ as app_version
app_name = "drive"
app_title = "Frappe Drive"
app_publisher = "Frappe Technologies Pvt. Ltd."
app_description = "An easy to use, document sharing and management solution."
app_icon = "octicon octicon-file-directory"
app_color = "grey"
app_email = "developers@frappe.io"
app_license = "GNU Affero General Public License v3.0"
website_route_rules = [
{"from_route": "/drive/<path:app_path>", "to_route": "drive"},
]
add_to_apps_screen = [
{
"name": "drive",
"logo": "assets/drive/frontend/favicon-310x310.png",
"title": "Drive",
"route": "/drive",
"has_permission": "drive.api.permissions.has_app_permission",
}
]
# Includes in <head>
# ------------------
# include js, css files in header of desk.html
# app_include_css = "/assets/drive/css/drive.css"
# app_include_js = "/assets/drive/js/drive.js"
# include js, css files in header of web template
# web_include_css = "/assets/drive/css/drive.css"
# web_include_js = "/assets/drive/js/drive.js"
# include custom scss in every website theme (without file extension ".scss")
# website_theme_scss = "drive/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 = "drive"
# website user home page (by Role)
# role_home_page = {
# "Role": "home_page"
# }
# Generators
# ----------
# automatically create page for each record of this doctype
# website_generators = ["Web Page"]
# Jinja
# ----------
# add methods and filters to jinja environment
# jinja = {
# "methods": "drive.utils.jinja_methods",
# "filters": "drive.utils.jinja_filters"
# }
# Installation
# ------------
# before_install = "drive.install.before_install"
after_install = "drive.install.after_install"
# Uninstallation
# ------------
# before_uninstall = "drive.uninstall.before_uninstall"
# after_uninstall = "drive.uninstall.after_uninstall"
# Desk Notifications
# ------------------
# See frappe.core.notifications.get_notification_config
# notification_config = "drive.notifications.get_notification_config"
# Permissions
# -----------
# Permissions evaluated in scripted ways
# permission_query_conditions = {
# "Event": "frappe.desk.doctype.event.event.get_permission_query_conditions",
# }
#
permission_query_conditions = {
"Drive Entity": "drive.overrides.filter_drive_entity",
"Drive Document": "drive.overrides.filter_drive_document",
"Drive Favourite": "drive.overrides.filter_drive_favourite",
"Drive Entity Log": "drive.overrides.filter_drive_recent",
"Drive Notification": "drive.overrides.filter_drive_notif",
}
has_permission = {
"Drive Entity": "drive.overrides.user_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"
# }
# }
fixtures = [{"dt": "Role", "filters": [["role_name", "like", "Drive %"]]}]
# Scheduled Tasks
# ---------------
scheduler_events = {
"daily": ["drive.api.files.auto_delete_from_trash"],
"daily": ["drive.api.files.delete_expired_docshares"],
}
# Testing
# -------
# before_tests = "drive.install.before_tests"
# Overriding Methods
# ------------------------------
#
# override_whitelisted_methods = {
# "frappe.desk.doctype.event.event.get_events": "drive.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": "drive.task.get_dashboard_data"
# }
# exempt linked doctypes from being automatically cancelled
#
# auto_cancel_exempted_doctypes = ["Auto Repeat"]
# 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 = [
# "drive.auth.validate"
# ]
|
2302_79757062/drive
|
drive/hooks.py
|
Python
|
agpl-3.0
| 4,965
|
import frappe
def after_install():
frappe.db.sql(
"""ALTER TABLE `tabDrive Entity` ADD FULLTEXT INDEX drive_entity_title_fts_idx (title)"""
)
|
2302_79757062/drive
|
drive/install.py
|
Python
|
agpl-3.0
| 160
|
import frappe
import redis
class FileLockedError(Exception):
pass
class DistributedLock(object):
def __init__(self, path, exclusive, ttl=60):
self.path = path
self.exclusive = exclusive
self.ttl = ttl
self.key = frappe.cache().make_key(path)
self.lock_id = f"{frappe.session.user}{frappe.utils.now_datetime().timestamp()}"
self.acquired = False
def acquire_write_lock(self):
if not self._add(self.key, self.lock_id, self.ttl):
raise FileLockedError()
self.acquired = True
def release_write_lock(self):
self._check_and_delete(self.key, self.lock_id)
self.acquired = False
def acquire_read_lock(self):
if not self._increment(self.key, self.ttl):
raise FileLockedError()
self.acquired = True
def release_read_lock(self):
if not self._check_and_delete(self.key, "1"):
self._decrement(self.key)
self.acquired = False
def __enter__(self):
if not self.acquired:
self.acquire_write_lock() if self.exclusive else self.acquire_read_lock()
return self
def __exit__(self, exc_type, exc_value, traceback):
if self.acquired:
self.release_write_lock() if self.exclusive else self.release_read_lock()
def _add(self, key, value, ttl):
"""Returns true if key does not already exist and value is set"""
return frappe.cache().set(key, value, ex=ttl, nx=True)
def _increment(self, key, ttl):
"""Atomic transaction to incremnet value. Returns False if current value cannot be incremented.
If the key does not exist, value is set to 1"""
with frappe.cache().pipeline() as pipe:
try:
res = pipe.incr(key).expire(key, ttl).execute()
return True
except redis.ResponseError:
return False
def _decrement(self, key):
"""Atomic transaction to decrement value. Returns False if current value cannot be decremented
or if the key does not exist"""
try:
if not frappe.cache().exists(key):
return False
frappe.cache().decr(key)
return True
except redis.ResponseError:
return False
def _check_and_set(self, key, expected_val, new_val, ttl):
"""Atomic transaction to set value if current value matches the expected value"""
with frappe.cache().pipeline() as pipe:
while True:
try:
pipe.watch(key)
current_val = pipe.get(key)
if current_val and current_val.decode() != expected_val:
return False
pipe.multi()
pipe.set(key, new_val, ex=ttl)
return pipe.execute()[0]
except redis.WatchError:
continue
def _check_and_delete(self, key, expected_val):
"""Atomic transaction to delete the key if current value matches the expected value"""
with frappe.cache().pipeline() as pipe:
while True:
try:
pipe.watch(key)
current_val = pipe.get(key)
if current_val and current_val.decode() != expected_val:
return False
pipe.multi()
pipe.delete(key)
return pipe.execute()[0]
except redis.WatchError:
continue
|
2302_79757062/drive
|
drive/locks/distributed_lock.py
|
Python
|
agpl-3.0
| 3,575
|
import frappe
from drive.api.permissions import user_group_entity_access
def user_has_permission(doc, ptype, user):
if not user:
user = frappe.session.user
if doc.owner == user:
return True
if user != "Guest":
user_access = frappe.db.get_value(
"Drive DocShare",
{
"share_doctype": "Drive Entity",
"share_name": doc.name,
"user_doctype": "User",
"user_name": frappe.session.user,
},
["read", "write", "share"],
as_dict=1,
)
if user_access:
if ptype == "share" and user_access["share"]:
return True
if ptype == "write" and user_access["write"]:
return True
if ptype == "read" and user_access["read"]:
return True
group_access = user_group_entity_access(doc.name)
if group_access:
if ptype == "share" and group_access["read"]:
return True
if ptype == "write" and group_access["write"]:
return True
if ptype == "read" and group_access["read"]:
return True
general_access = frappe.db.get_value(
"Drive DocShare",
{"share_name": doc.name, "everyone": 1},
["read", "write"],
as_dict=1,
)
if general_access:
if ptype == "write" and general_access["write"]:
return True
if ptype == "read" and general_access["read"]:
return True
public_access = frappe.db.get_value(
"Drive DocShare",
{"share_name": doc.name, "public": 1},
["read", "write"],
as_dict=1,
)
if public_access:
if ptype == "write" and public_access["write"]:
return True
if ptype == "read" and public_access["read"]:
return True
return False
public_access = frappe.db.get_value(
"Drive DocShare",
{"share_name": doc.name, "public": 1},
["read", "write"],
as_dict=1,
)
if public_access:
if ptype == "write" and public_access["write"]:
return True
if ptype == "read" and public_access["read"]:
return True
return False
def filter_drive_entity(user):
user = user or frappe.session.user
if user == "Administrator":
return ""
return f"""(`tabDrive Entity`.`owner` = {frappe.db.escape(user)})"""
def filter_drive_document(user):
user = user or frappe.session.user
if user == "Administrator":
return ""
return f"""(`tabDrive Document`.`owner` = {frappe.db.escape(user)})"""
def filter_drive_favourite(user):
user = user or frappe.session.user
if user == "Administrator":
return ""
return f"""(`tabDrive Favourite`.`user` = {frappe.db.escape(user)})"""
def filter_drive_recent(user):
user = user or frappe.session.user
if user == "Administrator":
return ""
return f"""(`tabDrive Entity Log`.`user` = {frappe.db.escape(user)})"""
def filter_drive_notif(user):
user = user or frappe.session.user
if user == "Administrator":
return ""
return """(`tabDrive Notification`.to_user = {user} or `tabDrive Notification`.from_user = {user})""".format(
user=frappe.db.escape(user)
)
|
2302_79757062/drive
|
drive/overrides.py
|
Python
|
agpl-3.0
| 3,461
|
import frappe
import os
import mimetypes
from pathlib import Path
import hashlib
from PIL import Image, ImageOps
from drive.locks.distributed_lock import DistributedLock
import cv2
def create_user_directory():
"""
Create user directory on disk, and insert corresponding DriveEntity doc
:raises FileExistsError: If user directory already exists
:return: Dictionary containing the document-name and path
:rtype: frappe._dict
"""
if frappe.session.user == "Guest":
return
user_directory_name = _get_user_directory_name()
user_directory_path = Path(frappe.get_site_path("private/files"), user_directory_name)
user_directory_path.mkdir(exist_ok=True)
full_name = frappe.get_value("User", frappe.session.user, "full_name")
user_directory = frappe.get_doc(
{
"doctype": "Drive Entity",
"name": user_directory_name,
"title": f"{full_name}'s Drive",
"is_group": 1,
"path": user_directory_path,
}
)
user_directory.flags.file_created = True
# frappe.local.rollback_observers.append(user_directory)
# (Placeholder) till we make login and onboarding
# user_directory breaks if its not created by a `drive_user`
user = frappe.get_doc("User", frappe.session.user)
user.flags.ignore_permlevel_for_fields = ["roles"]
user.add_roles("Drive User")
user.save(ignore_permissions=True)
user_directory.insert()
return frappe._dict({"name": user_directory.name, "path": user_directory.path})
def get_user_directory(user=None):
"""
Return the document-name, and path of the specified user's user directory
:param user: User whose directory details should be returned. Defaults to the current user
:raises FileNotFoundError: If user directory does not exist
:return: Dictionary containing the document-name and path
:rtype: frappe._dict
"""
user_directory_name = _get_user_directory_name(user)
user_directory = frappe.db.get_value(
"Drive Entity", user_directory_name, ["name", "path"], as_dict=1
)
if user_directory is None:
user_directory = create_user_directory()
return user_directory
def _get_user_directory_name(user=None):
"""Returns user directory name from user's unique id"""
if not user:
user = frappe.session.user
return hashlib.md5(user.encode("utf-8")).hexdigest()
@frappe.whitelist()
def get_new_title(title, parent_name, document=False, folder=False):
"""
Returns new title for an entity if same title exists for another entity at the same level
:param entity_title: Title of entity to be renamed (if at all)
:param parent_entity: Parent entity of entity to be renamed (if at all)
:return: String with new title
"""
entity_title, entity_ext = os.path.splitext(title)
filters = {
"is_active": 1,
"parent_drive_entity": parent_name,
"title": ["like", f"{entity_title}%{entity_ext}"],
}
if entity_ext:
mime_type = mimetypes.guess_type(title)
filters["mime_type"] = mime_type[0]
if document:
mime_type = "frappe_doc"
if folder:
filters["is_group"] = 1
sibling_entity_titles = frappe.db.get_list(
"Drive Entity",
filters=filters,
pluck="title",
)
if not sibling_entity_titles:
return title
return f"{entity_title} ({len(sibling_entity_titles)}){entity_ext}"
def create_user_thumbnails_directory():
user_directory_name = _get_user_directory_name()
user_directory_thumnails_path = Path(
frappe.get_site_path("private/files"), user_directory_name, "thumbnails"
)
user_directory_thumnails_path.mkdir(exist_ok=True)
return user_directory_thumnails_path
def get_user_thumbnails_directory(user=None):
user_directory_name = _get_user_directory_name(user)
user_directory_thumnails_path = Path(
frappe.get_site_path("private/files"), user_directory_name, "thumbnails"
)
if not os.path.exists(user_directory_thumnails_path):
try:
user_directory_thumnails_path = create_user_thumbnails_directory()
except FileNotFoundError:
user_directory_thumnails_path = create_user_thumbnails_directory()
return user_directory_thumnails_path
def create_thumbnail(entity_name, path, mime_type):
user_thumbnails_directory = None
try:
user_thumbnails_directory = get_user_thumbnails_directory()
except FileNotFoundError:
user_thumbnails_directory = create_user_thumbnails_directory()
thumbnail_savepath = Path(user_thumbnails_directory, entity_name)
with DistributedLock(path, exclusive=False):
if mime_type.startswith("image"):
max_retries = 3
retry_count = 0
while retry_count < max_retries:
try:
image_path = path
with Image.open(image_path).convert("RGB") as image:
image = ImageOps.exif_transpose(image)
image.thumbnail((512, 512))
image.save(str(thumbnail_savepath) + ".thumbnail", format="webp")
break
except Exception as e:
print(f"Failed to create thumbnail. Retry {retry_count+1}/{max_retries}")
retry_count += 1
else:
print("Failed to create thumbnail after maximum retries.")
if mime_type.startswith("video"):
max_retries = 3
retry_count = 0
while retry_count < max_retries:
try:
video_path = str(path)
cap = cv2.VideoCapture(video_path)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
target_frame = int(frame_count / 2)
cap.set(cv2.CAP_PROP_POS_FRAMES, target_frame)
ret, frame = cap.read()
cap.release()
_, thumbnail_encoded = cv2.imencode(
# ".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 30]
".webp",
frame,
[int(cv2.IMWRITE_WEBP_QUALITY), 50],
)
with open(str(thumbnail_savepath) + ".thumbnail", "wb") as f:
f.write(thumbnail_encoded)
break
except Exception as e:
print(f"Failed to create thumbnail. Retry {retry_count+1}/{max_retries}")
retry_count += 1
else:
print("Failed to create thumbnail after maximum retries.")
|
2302_79757062/drive
|
drive/utils/files.py
|
Python
|
agpl-3.0
| 6,730
|
import frappe
from drive.utils.users import is_drive_admin
@frappe.whitelist()
def get_name_of_all_user_groups():
try:
user_groups = frappe.get_all("User Group")
return user_groups
except Exception as e:
return {"message": "Failed to fetch user groups.", "error": str(e)}
@frappe.whitelist()
def get_users_in_group(group_name):
try:
user_group = frappe.get_doc("User Group", group_name)
users = [member.user for member in user_group.user_group_members]
for index, value in enumerate(users):
user_info = frappe.db.get_value(
"User", value, ["user_image", "full_name", "email"], as_dict=True
)
users[index] = user_info
return users
except Exception as e:
return {"message": "Failed to fetch users in the group.", "error": str(e)}
@frappe.whitelist()
def create_user_group(group_name, members=[]):
if not is_drive_admin():
return []
group_name = group_name.title()
# Create a new User Group
new_group = frappe.get_doc(
{
"doctype": "User Group",
"name": group_name,
"user_group_members": [{"user": member} for member in members],
}
)
new_group.insert(ignore_permissions=True)
return {
"message": ("User Group created successfully."),
"user_group": new_group.name,
}
@frappe.whitelist()
def delete_user_group(group_name):
if not is_drive_admin():
return []
try:
frappe.db.delete("User Group", group_name)
frappe.db.delete("User Group Member", {"parent": group_name})
frappe.db.delete("Drive DocShare", {"user_name": group_name, "user_doctype": "User Group"})
return {
"message": ("User Group deleted successfully."),
}
except Exception as e:
return {"message": ("User Group deletion failed."), "error": str(e)}
@frappe.whitelist()
def add_user_to_group(group_name, user_email):
try:
# Get the User Group document
user_group = frappe.get_doc("User Group", group_name)
# Check if the user is already in the group
existing_members = [member.user for member in user_group.user_group_members]
if user_email in existing_members:
return {"message": ("User already exists in the group.")}
# Add the user to the group
user_group.append("user_group_members", {"user": user_email})
user_group.save(ignore_permissions=True)
return {
"message": ("User added to the group successfully."),
"user_group": user_group.name,
}
except Exception as e:
return {"message": ("Failed to add user to the group."), "error": str(e)}
@frappe.whitelist()
def add_users_to_group(group_name, user_emails=[]):
# Get the User Group document
user_group = frappe.get_doc("User Group", group_name)
# Add each user to the group
added_users = []
already_existing_users = []
existing_members = [member.user for member in user_group.user_group_members]
for user_email in user_emails:
if user_email not in existing_members:
user_group.append("user_group_members", {"user": user_email})
added_users.append(user_email)
else:
already_existing_users.append(user_email)
if already_existing_users:
return {
"message": ("Some users are already a part of the User Group"),
"existing_users": already_existing_users,
}
if added_users:
user_group.save(ignore_permissions=True)
return {
"message": ("Users added to the group successfully."),
"added_users": added_users,
"user_group": user_group.name,
}
else:
return {
"message": ("All users are already in the group."),
"user_group": user_group.name,
}
@frappe.whitelist()
def remove_users_from_group(group_name, user_emails=[]):
# Get the User Group document
user_group = frappe.get_doc("User Group", group_name)
# Remove specified users from the group
removed_users = []
existing_members = [member.user for member in user_group.user_group_members]
for user_email in user_emails:
if user_email in existing_members:
user_group.user_group_members = [
member for member in user_group.user_group_members if member.user != user_email
]
removed_users.append(user_email)
if removed_users:
user_group.save(ignore_permissions=True)
return {
"message": ("Users removed from the group successfully."),
"removed_users": removed_users,
"user_group": user_group.name,
}
else:
return {
"message": ("No specified users were found in the group."),
"user_group": user_group.name,
}
@frappe.whitelist()
def get_entity_shared_with_user_groups(entity_name):
try:
user_group_list = frappe.db.get_list(
"Drive DocShare",
filters={"entity_name": ["like", f"%{entity_name}%"]},
fields=["user_group", "read", "write"],
)
return user_group_list
except Exception as e:
return {
"message": ("Failed to fetch entity shared with user group."),
"error": str(e),
}
def add_new_user_group_docshare(entity_name, user_group):
try:
new_doc = frappe.new_doc("Drive DocShare")
new_doc.entity_name = entity_name
new_doc.user_group = user_group
new_doc.insert()
return new_doc
except Exception as e:
frappe.throw("Error while adding new record: {0}").format(str(e))
def does_exist_user_group_docshare(entity_name, user_group):
exists = frappe.db.exists(
"Drive DocShare", {"entity_name": entity_name, "user_group": user_group}
)
if exists:
frappe.throw("User Group already added ")
else:
return False
|
2302_79757062/drive
|
drive/utils/user_group.py
|
Python
|
agpl-3.0
| 6,071
|
import frappe
import os
from pathlib import Path
import hashlib
from drive.locks.distributed_lock import DistributedLock
import json
from frappe.utils import now
@frappe.whitelist()
def get_users_with_drive_user_role_and_groups(txt=""):
try:
drive_groups = frappe.get_all("User Group")
drive_users = frappe.get_all(
doctype="User",
filters=[
["Has Role", "role", "=", "Drive User"],
["full_name", "not like", "Administrator"],
["full_name", "not like", "Guest"],
],
fields=[
"email",
"full_name",
"user_image",
],
)
return drive_users + drive_groups
except Exception as e:
frappe.log_error("Error in fetching Drive Users: {0}".format(e))
return {
"status": "error",
"message": "An error occurred while fetching Drive Users",
}
@frappe.whitelist()
def get_users_with_drive_user_role(txt="", get_roles=False):
try:
drive_users = frappe.get_all(
doctype="User",
order_by="full_name",
filters=[
["Has Role", "role", "=", "Drive User"],
["full_name", "not like", "Administrator"],
["full_name", "not like", "Guest"],
["full_name", "like", f"%{txt}%"],
],
fields=[
"email",
"full_name",
"user_image",
],
)
if get_roles == "true":
for user in drive_users:
if frappe.db.exists("Has Role", {"parent": user.email, "role": "Drive Admin"}):
user["role"] = "Admin"
else:
user["role"] = "User"
return drive_users
except Exception as e:
frappe.log_error("Error in fetching Drive Users: {0}".format(e))
return {
"status": "error",
"message": "An error occurred while fetching Drive Users",
}
@frappe.whitelist()
def get_all_users_on_site():
try:
has_rw_access = has_read_write_access_to_doctype(frappe.session.user, "User")
if not has_rw_access:
return {
"status": "error",
"message": "You do not have permission to access this resource",
}
site_users = frappe.get_list(
doctype="User",
fields=[
"username",
"email",
"full_name",
"user_image",
],
filters={
"username": ["not like", "%administrator%"],
"username": ["not like", "%guest%"],
},
)
return site_users
except Exception as e:
frappe.log_error("Error in fetching Drive Users: {0}".format(e))
return {
"status": "error",
"message": "An error occurred while fetching Drive Users",
}
@frappe.whitelist()
def add_drive_user_role(user_id):
has_rw_access = has_read_write_access_to_doctype(frappe.session.user, "User")
if not has_rw_access:
return {
"status": "error",
"message": "You do not have permission to access this resource",
}
drive_user = frappe.db.exists("User", {"name": ("like", f"%{user_id}%")})
if not drive_user:
return {"status": "error", "message": "User with given email does not exist"}
user_role_exists = frappe.db.exists("Has Role", {"parent": user_id, "role": "Drive User"})
if user_role_exists is not None:
return {
"status": "error",
"message": "User already has the said Role permissions ",
}
usr = frappe.get_doc("User", user_id)
usr.add_roles("Drive User")
return {"status": "sucess", "message": "Drive User role has been sucessfully added"}
@frappe.whitelist()
def remove_drive_user_role(user_id):
has_rw_access = has_read_write_access_to_doctype(frappe.session.user, "User")
if not has_rw_access:
return {
"status": "error",
"message": "You do not have permission to access this resource",
}
drive_user = frappe.db.exists("User", {"name": ("like", f"%{user_id}%")})
if not drive_user:
return {"status": "error", "message": "User with given email does not exist"}
user_role_exists = frappe.db.exists("Has Role", {"parent": user_id, "role": "Drive User"})
if user_role_exists is None:
return {
"status": "error",
"message": "User does not have Drive User as a role applied ",
}
usr = frappe.get_doc("User", user_id)
usr.remove_roles("Drive User")
return {
"status": "sucess",
"message": "Drive User role has been sucessfully removed",
}
def has_read_write_access_to_doctype(user_id, doctype_name):
"""
Check if a user has both read and write access to a DocType.
Args:
user_id (str): The name of the user to check.
doctype_name (str): The name of the DocType to check access for.
Returns:
bool: True if the user has both read and write access to the DocType, False otherwise.
"""
try:
if frappe.has_permission(doctype_name, user=user_id, ptype="read"):
if frappe.has_permission(doctype_name, user=user_id, ptype="write"):
return True
except frappe.PermissionError:
pass
return False
def mark_as_viewed(entity):
if frappe.session.user == "Guest":
return
if entity.is_group:
return
entity_name = entity.name
entity_log = frappe.db.get_value(
"Drive Entity Log", {"entity_name": entity_name, "user": frappe.session.user}
)
if entity_log:
frappe.db.set_value(
"Drive Entity Log", entity_log, "last_interaction", now(), update_modified=False
)
return
doc = frappe.new_doc("Drive Entity Log")
doc.entity_name = entity_name
doc.user = frappe.session.user
doc.last_interaction = now()
doc.insert()
return doc
@frappe.whitelist()
def is_drive_admin():
user = frappe.session.user
if user != "Guest":
if user == "Administrator" or frappe.db.exists(
"Has Role", {"parent": user, "role": "Drive Admin"}
):
return True
return False
|
2302_79757062/drive
|
drive/utils/users.py
|
Python
|
agpl-3.0
| 6,460
|
from __future__ import unicode_literals
import frappe
from frappe.utils.telemetry import capture
no_cache = 1
def get_context():
csrf_token = frappe.sessions.get_csrf_token()
frappe.db.commit()
context = frappe._dict()
context.boot = get_boot()
context.boot.csrf_token = csrf_token
context.csrf_token = csrf_token
context.site_name = frappe.local.site
if frappe.session.user != "Guest":
capture("active_site", "drive")
return context
@frappe.whitelist(methods=["POST"], allow_guest=True)
def get_context_for_dev():
if not frappe.conf.developer_mode:
frappe.throw("This method is only meant for developer mode")
return get_boot()
def get_boot():
return frappe._dict(
{
"frappe_version": frappe.__version__,
"default_route": get_default_route(),
"site_name": frappe.local.site,
"read_only_mode": frappe.flags.read_only,
}
)
def get_default_route():
return "/drive"
|
2302_79757062/drive
|
drive/www/drive.py
|
Python
|
agpl-3.0
| 1,008
|
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
black drive/
cd frontend/
npm run precommit
|
2302_79757062/drive
|
frontend/.husky/pre-commit
|
Shell
|
agpl-3.0
| 88
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<!-- HTML Meta Tags -->
<title>Frappe Drive</title>
<meta
name="description"
content="An easy to use, document sharing and management solution."
/>
<!-- OG Meta Tags -->
<meta property="og:type" content="website" />
<meta property="og:title" content="Frappe Drive" />
<meta
property="og:description"
content="An easy to use, document sharing and management solution."
/>
<meta
property="og:image"
content="https://raw.githubusercontent.com/frappe/drive/main/.github/og_1200.png"
/>
<!-- Twitter Meta Tags -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Frappe Drive" />
<meta
name="twitter:description"
content="An easy to use, document sharing and management solution."
/>
<meta
name="twitter:image"
content="https://raw.githubusercontent.com/frappe/drive/main/.github/og_1200.png"
/>
<link rel="apple-touch-icon" sizes="57x57" href="/favicon-57x57.png" />
<link rel="apple-touch-icon" sizes="60x60" href="/favicon-60x60.png" />
<link rel="apple-touch-icon" sizes="72x72" href="/favicon-72x72.png" />
<link rel="apple-touch-icon" sizes="76x76" href="/favicon-76x76.png" />
<link rel="apple-touch-icon" sizes="114x114" href="/favicon-114x114.png" />
<link rel="apple-touch-icon" sizes="120x120" href="/favicon-120x120.png" />
<link rel="apple-touch-icon" sizes="144x144" href="/favicon-144x144.png" />
<link rel="apple-touch-icon" sizes="152x152" href="/favicon-152x152.png" />
<link rel="apple-touch-icon" sizes="180x180" href="/favicon-180x180.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png" />
<link
rel="icon"
type="image/png"
sizes="192x192"
href="/favicon-192x192.png"
/>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<meta name="msapplication-TileColor" content="#ffffff" />
<meta name="msapplication-TileImage" content="/favicon-144x144.png" />
<meta name="msapplication-config" content="/browserconfig.xml" />
<link rel="manifest" href="/manifest.json" />
<meta name="theme-color" content="#ffffff" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no"
/>
</head>
<body>
<div id="app"></div>
<div id="modals"></div>
<div id="popovers"></div>
<script>
window.csrf_token = "{{ csrf_token }}"
</script>
<script type="module" src="/src/main.js"></script>
</body>
</html>
|
2302_79757062/drive
|
frontend/index.html
|
HTML
|
agpl-3.0
| 2,906
|
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
|
2302_79757062/drive
|
frontend/postcss.config.js
|
JavaScript
|
agpl-3.0
| 82
|
<template>
<!-- Main container no scroll -->
<div
class="flex w-screen h-screen antialiased overflow-hidden"
@contextmenu="handleDefaultContext($event)"
>
<!-- Main container with scroll -->
<div class="h-full w-full flex flex-col">
<SearchPopup
v-if="isLoggedIn && showSearchPopup"
v-model="showSearchPopup"
/>
<div
v-if="isLoggedIn || $route.meta.isHybridRoute"
class="flex flex-col h-full overflow-hidden sm:flex-row"
>
<Sidebar v-if="isLoggedIn" class="hidden sm:block" />
<div id="dropTarget" class="h-full w-full overflow-hidden">
<Navbar
:mobile-sidebar-is-open="showMobileSidebar"
@toggle-mobile-sidebar="showMobileSidebar = !showMobileSidebar"
/>
<div class="flex w-full h-full overflow-hidden">
<!-- Find a better way to handle the height overflow here (52px is the Navbar) -->
<div
class="flex w-full h-[calc(100dvh-105px)] sm:h-[calc(100dvh-52px)] overflow-hidden"
>
<router-view :key="$route.fullPath" v-slot="{ Component }">
<component :is="Component" id="currentPage" ref="currentPage" />
</router-view>
</div>
<InfoSidebar v-if="hideInfoSideBar" />
</div>
</div>
<BottomBar v-if="isLoggedIn" class="fixed bottom-0 w-full sm:hidden" />
</div>
<!-- Auth -->
<router-view v-else />
</div>
</div>
<FileUploader v-if="isLoggedIn" />
<Transition
enter-active-class="transition duration-[150ms] ease-[cubic-bezier(.21,1.02,.73,1)]"
enter-from-class="translate-y-1 opacity-0"
enter-to-class="translate-y-0 opacity-100"
leave-active-class="transition duration-[150ms] ease-[cubic-bezier(.21,1.02,.73,1)]"
leave-from-class="translate-y-0 opacity-100"
leave-to-class="translate-y-1 opacity-0"
>
<UploadTracker v-if="showUploadTracker" />
</Transition>
<Toasts />
</template>
<script>
import Navbar from "@/components/Navbar.vue"
import Sidebar from "@/components/Sidebar.vue"
import InfoSidebar from "@/components/InfoSidebar.vue"
import MobileSidebar from "@/components/MobileSidebar.vue"
import UploadTracker from "@/components/UploadTracker.vue"
import { Button, FeatherIcon } from "frappe-ui"
import { Toasts } from "@/utils/toasts.js"
import FilePicker from "./components/FilePicker.vue"
import MoveDialog from "./components/MoveDialog.vue"
import SearchPopup from "./components/SearchPopup.vue"
import FileUploader from "./components/FileUploader.vue"
import BottomBar from "./components/BottomBar.vue"
import { init as initTelemetry } from "@/telemetry"
export default {
name: "App",
components: {
Navbar,
Sidebar,
InfoSidebar,
MobileSidebar,
UploadTracker,
Button,
FeatherIcon,
Toasts,
FilePicker,
MoveDialog,
SearchPopup,
FileUploader,
BottomBar,
},
data() {
return {
isOpen: false,
showMobileSidebar: false,
showSearchPopup: false,
}
},
computed: {
isExpanded() {
return this.$store.state.IsSidebarExpanded
},
isLoggedIn() {
return this.$store.getters.isLoggedIn
},
isHybridRoute() {
return this.$route.meta.isHybridRoute
},
showUploadTracker() {
return this.isLoggedIn && this.$store.state.uploads.length > 0
},
hideInfoSideBar() {
if (this.$route.meta.documentPage) {
return false
}
if (this.$route.name === "Notifications") {
return false
}
return true
},
},
async mounted() {
this.$store.dispatch.getServerTZ
this.addKeyboardShortcut()
this.emitter.on("showSearchPopup", (data) => {
this.showSearchPopup = data
})
await initTelemetry()
},
methods: {
handleDefaultContext(event) {
if (this.$route.meta.documentPage) {
return
} else if (
this.$store.state.entityInfo[0]?.mime_type ===
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" &&
this.$route.name === "File"
) {
return
} else {
return event.preventDefault()
}
},
async currentPageEmitTrigger() {
this.emitter.emit("fetchFolderContents")
},
addKeyboardShortcut() {
window.addEventListener("keydown", (e) => {
if (
e.key === "k" &&
(e.ctrlKey || e.metaKey) &&
!e.target.classList.contains("ProseMirror")
) {
this.showSearchPopup = true
e.preventDefault()
}
})
},
},
resources: {
getServerTZ: {
url: "drive.api.api.get_server_timezone",
auto: true,
method: "GET",
onSuccess(data) {
this.$store.state.serverTZ = data
},
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/App.vue
|
Vue
|
agpl-3.0
| 4,870
|
<script setup>
import { ref, onMounted, onBeforeUnmount, inject } from "vue"
import { v4 as uuidv4 } from "uuid"
import Uppy from "@uppy/core"
import Tus from "@uppy/tus"
import { useStore } from "vuex"
import DropTarget from "@uppy/drop-target"
const fileInput = ref(null)
const store = useStore()
const emitter = inject("emitter")
emitter.on("uploadFile", () => {
fileInput.value.removeAttribute("webkitdirectory")
fileInput.value.click()
})
emitter.on("uploadFolder", () => {
fileInput.value.setAttribute("webkitdirectory", true)
fileInput.value.click()
})
function fileInputPayload() {
const files = Array.from(event.target.files)
files.forEach((file) => {
try {
uppy.addFile({
source: "file input",
name: file.name,
type: file.type,
data: file,
})
} catch (err) {
if (err.isRestriction) {
// handle restrictions
console.log("Restriction error:", err)
} else {
// handle other errors
console.error(err)
}
}
})
}
const uppy = new Uppy({
autoProceed: true,
showProgressDetails: true,
debug: true,
})
uppy.use(Tus, {
// read site config and use that size if its bigger
chunkSize: 20 * 1024 * 1024, //20 MB
addRequestId: true,
endpoint: "/api/method/drive.api.upload.handle_tus_request",
withCredentials: true,
limit: 1,
parallelUploads: 1,
removeFingerprintOnSuccess: true,
onBeforeRequest: function (req) {
if (req._method === "HEAD") {
}
},
headers: {
"X-Frappe-CSRF-Token": window.csrf_token,
"X-Request-ID": uuidv4(),
"Content-Type": "application/offset+octet-stream",
},
})
uppy.use(DropTarget, {
target: document.body,
})
uppy.on("file-added", (file) => {
console.log(uppy.getFile(file.id))
console.log(uuidv4())
uppy.setFileMeta(file.id, {
fileId: file.id,
fileParent: store.state.currentFolderID,
lastModified: file.data.lastModified,
})
store.commit("pushToUploads", {
uuid: file.id,
name: file.name,
progress: 0,
})
})
uppy.on("restriction-failed", (file, error) => {
// do some customized logic like showing system notice to users
})
uppy.on("upload-error", (file, error, response) => {
console.log(error)
})
uppy.on("upload-retry", (fileID) => {
console.log("upload retried:", fileID)
})
uppy.on("retry-all", (fileID) => {
console.log("upload retried:", fileID)
})
uppy.on("upload-progress", (file, progress) => {
store.commit("updateUpload", {
uuid: file.id,
progress: file.progress.percentage,
})
})
uppy.on("upload-success", (file, response) => {
store.commit("updateUpload", {
uuid: file.id,
completed: true,
})
})
/* Complete batch events */
uppy.on("progress", (progress) => {
// progress: integer (total progress percentage)
//console.log(progress);
})
uppy.on("error", (error) => {
console.error(error)
})
uppy.on("complete", (result) => {
emitter.emit("fetchFolderContents")
uppy.cancelAll()
})
onBeforeUnmount(() => {
uppy.close()
})
</script>
|
2302_79757062/drive
|
frontend/src/TusFileUploader.vue
|
Vue
|
agpl-3.0
| 3,034
|
<template>
<Popover placement="right-start" class="flex w-full">
<template #target="{ togglePopover }">
<button
:class="[
active ? 'bg-gray-100' : 'text-gray-800',
'group w-full flex h-7 items-center justify-between rounded px-2 text-base hover:bg-gray-100',
]"
@click.prevent="togglePopover()"
>
<div class="flex gap-2">
<AppsIcon class="size-4" />
<span class="whitespace-nowrap"> Apps </span>
</div>
<FeatherIcon name="chevron-right" class="size-4 text-gray-600" />
</button>
</template>
<template #body>
<div
class="grid grid-cols-3 justify-between mx-3 p-2 rounded-lg border border-gray-100 bg-white shadow-xl"
>
<div v-for="app in apps.data" :key="app.name">
<a
:href="app.route"
class="flex flex-col gap-1.5 rounded justify-center items-center py-2 px-1 hover:bg-gray-100"
>
<img class="size-8" :src="app.logo" />
<div class="text-sm text-gray-700" @click="app.onClick">
{{ app.title }}
</div>
</a>
</div>
</div>
</template>
</Popover>
</template>
<script setup>
import AppsIcon from "@/components/EspressoIcons/Apps.vue"
import { Popover, createResource } from "frappe-ui"
import { FeatherIcon } from "frappe-ui"
const props = defineProps({
active: Boolean,
})
const apps = createResource({
url: "frappe.apps.get_apps",
cache: "apps",
auto: true,
transform: (data) => {
let apps = [
{
name: "frappe",
logo: "/assets/frappe/images/framework.png",
title: "Desk",
route: "/app",
},
]
data.map((app) => {
if (app.name === "drive") return
apps.push({
name: app.name,
logo: app.logo,
title: app.title,
route: app.route,
})
})
return apps
},
})
</script>
|
2302_79757062/drive
|
frontend/src/components/AppSwitcher.vue
|
Vue
|
agpl-3.0
| 1,957
|
<template>
<div class="border-r bg-gray-50 transition-all">
<div
ondragstart="return false;"
ondrop="return false;"
class="grid grid-cols-5 h-14 items-center border-y border-gray-300 standalone:pb-4 px-1"
>
<router-link
v-for="item in sidebarItems"
:key="item.label"
v-slot="{ href, navigate }"
:to="item.route"
>
<a
class="flex flex-col items-center justify-center py-3 transition active:scale-95 rounded"
:class="[
item.highlight()
? 'bg-white shadow-sm border-[0.5px] border-gray-300'
: ' hover:bg-gray-100',
]"
:href="href"
@click="navigate && $emit('toggleMobileSidebar')"
>
<FeatherIcon
:name="item.icon"
class="stroke-1.5 self-center w-auto h-5.5 text-gray-800"
/>
</a>
</router-link>
<!-- <span
class="mt-auto w-[256px] h-7 px-3 py-4 gap-3 rounded-lg focus:outline-none flex items-center">
<FeatherIcon name="cloud" class="stroke-1.5 w-4 h-4" />
Used :
{{ $resources.getRootFolderSize.data + "B" }}
</span> -->
</div>
</div>
</template>
<script>
import { FeatherIcon } from "frappe-ui"
export default {
name: "Sidebar",
components: { FeatherIcon },
emits: ["toggleMobileSidebar"],
data() {
return {
sidebarResizing: false,
}
},
computed: {
isExpanded() {
return this.$store.state.IsSidebarExpanded
},
/* currentSideBarWidth: {
get() {
return this.currentSideBarWidth = this.$store.state.IsSidebarExpanded ? 280 : 60
},
set(val) {
console.log(val)
return this.currentSideBarWidth = val
}
}, */
sidebarItems() {
return [
/* {
label: "Search",
route: () => {},
icon: "search",
highlight: () => {},
}, */
{
label: "Home",
route: "/home",
icon: "home",
highlight: () => {
return this.$store.state.currentBreadcrumbs[0].label === "Home"
},
},
{
label: "Recents",
route: "/recents",
icon: "clock",
highlight: () => {
return this.$store.state.currentBreadcrumbs[0].label === "Recents"
},
},
{
label: "Favourites",
route: "/favourites",
icon: "star",
highlight: () => {
return (
this.$store.state.currentBreadcrumbs[0].label === "Favourites"
)
},
},
{
label: "Shared",
route: "/shared",
icon: "users",
highlight: () => {
return this.$store.state.currentBreadcrumbs[0].label === "Shared"
},
},
{
label: "Trash",
route: "/trash",
icon: "trash-2",
highlight: () => {
return this.$store.state.currentBreadcrumbs[0].label === "Trash"
},
},
]
},
},
methods: {
toggleExpanded() {
console.log("test")
return this.$store.commit(
"setIsSidebarExpanded",
this.isExpanded ? false : true
)
},
startResize() {
document.addEventListener("mousemove", this.resize)
document.addEventListener("mouseup", () => {
document.body.classList.remove("select-none")
document.body.classList.remove("cursor-col-resize")
this.sidebarResizing = false
document.removeEventListener("mousemove", this.resize)
})
},
resize(e) {
this.sidebarResizing = true
document.body.classList.add("select-none")
document.body.classList.add("cursor-col-resize")
let sidebarWidth = e.clientX
let range = [60, 180]
if (sidebarWidth > range[0] && sidebarWidth < range[1]) {
sidebarWidth = 60
this.$store.commit("setIsSidebarExpanded", false)
}
if (sidebarWidth > 180) {
this.$store.commit("setIsSidebarExpanded", true)
}
/* if (sidebarWidth < 100) {
this.$store.commit("setIsSidebarExpanded", false )
}
if (sidebarWidth > 100) {
this.$store.commit("setIsSidebarExpanded", true )
} */
},
},
resources: {
getRootFolderSize() {
return {
url: "drive.api.files.get_user_directory_size",
onError(error) {
console.log(error)
},
auto: false,
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/BottomBar.vue
|
Vue
|
agpl-3.0
| 4,612
|
<template>
<div ref="container" class="flex justify-items-center items-center text-base">
<template v-if="dropDownItems.length">
<Dropdown class="h-7" :options="dropDownItems">
<Button variant="ghost">
<template #icon>
<svg
class="w-4 text-gray-600"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="1" />
<circle cx="19" cy="12" r="1" />
<circle cx="5" cy="12" r="1" />
</svg>
</template>
</Button>
</Dropdown>
<span class="ml-1 mr-0.5 text-base text-gray-500" aria-hidden="true">
/
</span>
</template>
<div class="flex">
<router-link
v-for="(item, index) in crumbs"
:key="item.label"
class="text-md line-clamp-1 sm:text-lg font-medium cursor-pointer"
:class="[
$store.state.currentBreadcrumbs.length === 1
? 'text-black'
: ' hover:text-gray-800 text-gray-600',
]"
:to="item.route"
>
<span> {{ item.label }}</span>
<span v-show="index < crumbs.length - 1" class="mx-1">/</span>
</router-link>
</div>
<span
v-if="$store.state.currentBreadcrumbs.length > 1"
class="text-black text-md line-clamp-1 sm:text-lg font-medium cursor-pointer"
@click="canShowRenameDialog"
>
<span class="ml-1">/</span>
{{ currentTitle }}
</span>
</div>
<RenameDialog
v-if="showRenameDialog"
v-model="showRenameDialog"
:entity="entity"
@success="
(data) => {
showRenameDialog = false
currentTitle = data.title
}
"
/>
</template>
<script>
import RenameDialog from "@/components/RenameDialog.vue"
import { Dropdown } from "frappe-ui"
export default {
name: "Breadcrumbs",
components: { RenameDialog, Dropdown },
data() {
return {
title: "",
showRenameDialog: false,
}
},
computed: {
entity() {
if (this.$route.name === "Folder") {
this.$store.commit("setEntityInfo", this.$store.state.currentFolder)
}
return this.$store.state.entityInfo[0]
},
breadcrumbLinks() {
let arr = this.$store.state.currentBreadcrumbs
if (arr.length > 1) {
return arr.slice(0, -1)
}
return arr
},
currentTitle: {
get() {
const { breadcrumbLinks, $route, $store } = this
const { name } = $route
const lastBreadcrumb = breadcrumbLinks[breadcrumbLinks.length - 1]
const storeTitle = $store.state.entityInfo[0]?.title
const folderTitle = $store.state.currentFolder[0]?.title
let result
switch (name) {
case "Folder":
result = folderTitle
break
case "Document":
case "File":
result =
lastBreadcrumb.label !== storeTitle
? storeTitle
: lastBreadcrumb.label
break
default:
result = lastBreadcrumb.label
}
document.title = result
return result
},
set(newValue) {
return newValue
},
},
currentRoute() {
return this.breadcrumbLinks[this.breadcrumbLinks.length - 1].route
},
currentEntityName() {
return this.currentRoute.split("/")[2]
},
dropDownItems() {
if (window.innerWidth > 640) return []
let allExceptLastTwo = this.breadcrumbLinks.slice(0, -1)
return allExceptLastTwo.map((item) => {
let onClick = item.onClick
? item.onClick
: () => this.$router.push(item.route)
return {
...item,
icon: null,
label: item.label,
onClick,
}
})
},
crumbs() {
if (window.innerWidth > 640) return this.breadcrumbLinks
return this.breadcrumbLinks.slice(-1)
},
},
methods: {
isLastItem(index) {
return this.breadcrumbLinks.length > 1
? index === this.breadcrumbLinks.length - 1
: false
},
canShowRenameDialog() {
if (this.$route.name === "Folder") {
if (
(this.$store.state.currentFolder[0]?.owner === "You") |
this.$store.state.currentFolder[0]?.write
) {
return (this.showRenameDialog = true)
}
} else if (
(this.$store.state.entityInfo[0]?.owner === "You") |
(this.$store.state.entityInfo[0]?.write === 1)
) {
return (this.showRenameDialog = true)
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/Breadcrumbs.vue
|
Vue
|
agpl-3.0
| 4,850
|
<template>
<Dialog v-model="open" :options="{ title: title, size: 'sm' }">
<template #body-content>
<p class="text-gray-600">
{{ message }}
</p>
<div class="flex mt-5">
<Button
:variant="buttonVariant"
theme="red"
icon-left="trash-2"
class="w-full"
:loading="$resources.action.loading"
@click="$resources.action.submit()"
>
{{ buttonText }}
</Button>
</div>
</template>
</Dialog>
</template>
<script>
import { Dialog } from "frappe-ui"
export default {
name: "CTADeleteDialog",
components: {
Dialog,
},
props: {
modelValue: {
type: Boolean,
required: true,
},
entities: {
type: Array,
required: false,
default: null,
},
clearAll: {
type: Boolean,
required: false,
default: false,
},
},
emits: ["update:modelValue", "success"],
data: () => ({
title: "",
message: "",
buttonText: "",
buttonVariant: "subtle",
url: null,
}),
computed: {
open: {
get() {
return this.modelValue
},
set(value) {
this.$emit("update:modelValue", value)
},
},
},
mounted() {
this.evalDialog()
},
methods: {
evalDialog() {
if (this.$route.name === "Recents") {
this.title = "Clear Recents?"
this.message = "All your recently viewed files will be cleared"
this.buttonText = "Clear"
this.url = "drive.api.files.remove_recents"
}
if (this.$route.name === "Favourites") {
this.title = "Clear Favourites?"
this.message =
"All your favourited items will be marked as unfavourite."
this.buttonText = "Unfavourite"
this.url = "drive.api.files.add_or_remove_favourites"
}
if (this.$route.name === "Trash") {
this.title = "Delete Forever?"
this.message =
"All items in your Trash will be deleted forever. This is an irreversible process."
this.buttonVariant = "solid"
this.buttonText = "Delete"
this.url = "drive.api.files.delete_entities"
}
},
},
resources: {
action() {
return {
url: this.url,
params: {
clear_all: true,
},
onSuccess(data) {
this.$emit("success", data)
},
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/CTADeleteDialog.vue
|
Vue
|
agpl-3.0
| 2,545
|
<template>
<Popover
trigger="hover"
placement="right-start"
popover-class="border-x-[8px] border-transparent"
:hover-delay="0.25"
:leave-delay="0.5"
>
<template #target="{ togglePopover, isOpen }">
<div
:active="isOpen"
class="h-6 px-2 hover:bg-gray-100 text-sm cursor-pointer rounded-[5px] flex justify-start items-center w-full"
@click="togglePopover()"
>
<Palette class="h-4 w-auto mr-2 text-gray-800" />
<div class="text-gray-800">Color</div>
<FeatherIcon
:name="'chevron-right'"
class="h-3.5 text-gray-900 ml-auto"
/>
</div>
</template>
<template #body-main>
<div class="grid grid-cols-5 gap-2 p-3">
<button
v-for="color in colors"
:key="color"
class="h-5 w-5 rounded-full justify-self-center"
:style="{ backgroundColor: color }"
@click="
$resources.updateColor.submit({
method: 'change_color',
entity_name: entityName,
new_color: color,
})
"
/>
</div>
</template>
</Popover>
</template>
<script>
import { Popover, FeatherIcon } from "frappe-ui"
import Palette from "./EspressoIcons/Palette.vue"
export default {
name: "ColorPopover",
components: { Popover, FeatherIcon, Palette },
props: {
entityName: {
type: String,
default: null,
},
},
emits: ["success"],
data() {
return {
colors: [
"#525252",
"#775225",
"#e11d48",
"#20C1F4",
"#2374D2",
"#fbbf24",
"#E39B4C",
"#16a34a",
"#EF7323",
"#9333ea",
],
}
},
resources: {
updateColor() {
return {
url: "drive.api.files.call_controller_method",
params: {
method: "change_color",
entity_name: this.entityName,
},
validate(params) {
if (!params?.new_color) {
return "New name is required"
}
},
onSuccess() {
this.emitter.emit("fetchFolderContents")
},
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/ColorPopover.vue
|
Vue
|
agpl-3.0
| 2,189
|
<template>
<Dialog v-model="open" :options="{ title: 'Delete Forever?', size: 'sm' }">
<template #body-content>
<p class="text-gray-600">
{{
entities.length === 1
? `${entities.length} item`
: `${entities.length} items`
}}
will be deleted forever. This is an irreversible process.
</p>
<div class="flex mt-5">
<Button
variant="solid"
theme="red"
icon-left="trash-2"
class="w-full"
:loading="$resources.delete.loading"
@click="$resources.delete.submit()"
>
Delete Forever
</Button>
</div>
</template>
</Dialog>
</template>
<script>
import { Dialog } from "frappe-ui"
import { del } from "idb-keyval"
export default {
name: "DeleteDialog",
components: {
Dialog,
},
props: {
modelValue: {
type: Boolean,
required: true,
},
entities: {
type: Array,
required: false,
default: null,
},
},
emits: ["update:modelValue", "success"],
computed: {
open: {
get() {
return this.modelValue
},
set(value) {
this.$emit("update:modelValue", value)
},
},
},
resources: {
delete() {
return {
url: "drive.api.files.delete_entities",
params: {
entity_names: JSON.stringify(
this.entities?.map((entity) => entity.name)
),
},
onSuccess(data) {
this.entities.map((entity) => del(entity.name))
this.$emit("success", data)
},
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/DeleteDialog.vue
|
Vue
|
agpl-3.0
| 1,758
|
<template>
<editor-content v-if="editor" :editor="editor" />
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, normalizeClass } from "vue"
import Link from "@tiptap/extension-link"
import TaskItem from "@tiptap/extension-task-item"
import TaskList from "@tiptap/extension-task-list"
import Typography from "@tiptap/extension-typography"
import StarterKit from "@tiptap/starter-kit"
import { Editor, EditorContent } from "@tiptap/vue-3"
import { IndexeddbPersistence } from "y-indexeddb"
import * as Y from "yjs"
import { Table } from "./extensions/table"
import { PageBreak } from "./extensions/Pagebreak"
import { Highlight } from "./extensions/backgroundColor"
import { CharacterCount } from "./extensions/character-count"
import { Collaboration } from "./extensions/collaboration"
import { Color } from "./extensions/color"
import { FontFamily } from "./extensions/font-family"
import { FontSize } from "./extensions/font-size"
import { Indent } from "./extensions/indent"
import { LineHeight } from "./extensions/lineHeight"
import { Placeholder } from "./extensions/placeholder"
import { TextAlign } from "./extensions/text-align"
import { TextStyle } from "./extensions/text-style"
import { Underline } from "./extensions/underline"
import { ResizableMedia } from "./extensions/resizenode"
const editor = ref(null)
const document = ref(null)
const provider = ref(null)
const props = defineProps({
yjsUpdate: {
type: Uint8Array,
required: true,
},
})
onMounted(() => {
const doc = new Y.Doc()
Y.applyUpdate(doc, props.yjsUpdate)
const indexeddbProvider = new IndexeddbPersistence("version-proxy-doc", doc)
provider.value = indexeddbProvider
document.value = doc
provider.value.on("synced", () => {
editor.value = new Editor({
editable: false,
// eslint-disable-next-line no-sparse-arrays
extensions: [
StarterKit.configure({
history: false,
heading: {
levels: [1, 2, 3, 4, 5],
},
listItem: {
HTMLAttributes: {
class: "prose-list-item",
},
},
codeBlock: {
HTMLAttributes: {
spellcheck: false,
class:
"not-prose my-5 px-4 py-2 text-[0.9em] font-mono text-black bg-gray-50 rounded border border-gray-300 overflow-x-auto",
},
},
blockquote: {
HTMLAttributes: {
class:
"prose-quoteless text-black border-l-2 pl-2 border-gray-400 text-[0.9em]",
},
},
code: {
HTMLAttributes: {
class:
"not-prose px-px font-mono bg-gray-50 text-[0.85em] rounded-sm border border-gray-300",
},
},
bulletList: {
keepMarks: true,
keepAttributes: false,
HTMLAttributes: {
class: "",
},
},
orderedList: {
keepMarks: true,
keepAttributes: false,
HTMLAttributes: {
class: "",
},
},
}),
Table,
FontFamily.configure({
types: ["textStyle"],
}),
TextAlign.configure({
types: ["heading", "paragraph"],
defaultAlignment: "left",
}),
,
PageBreak,
Collaboration.configure({
document: doc,
}),
LineHeight,
Indent,
Link.configure({
openOnClick: false,
}),
Placeholder.configure({
placeholder: "Press / for commands",
}),
Highlight.configure({
multicolor: true,
}),
TaskList.configure({
HTMLAttributes: {
class: "not-prose",
},
}),
TaskItem.configure({
HTMLAttributes: {
class: "my-task-item",
},
}),
CharacterCount,
Underline,
Typography,
TextStyle,
FontSize.configure({
types: ["textStyle"],
}),
Color.configure({
types: ["textStyle"],
}),
ResizableMedia.configure({
uploadFn: () => {},
}),
],
editorProps: {
attributes: {
/* !p-0 to offset .Prosemirror */
class: normalizeClass([
`text-[14px] !p-0 mx-2 my-4 prose prose-sm prose-table:table-fixed prose-td:p-2 prose-th:p-2 prose-td:border prose-th:border prose-td:border-gray-300 prose-th:border-gray-300 prose-td:relative prose-th:relative prose-th:bg-gray-100 rounded-b-lg max-w-[unset] pb-[50vh] md:px-[70px]`,
]),
},
},
})
})
})
onBeforeUnmount(() => {
editor.value.destroy()
provider.value.clearData()
document.value.destroy()
})
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/PreviewEditor.vue
|
Vue
|
agpl-3.0
| 4,849
|
<template>
<div v-if="editor && initComplete" class="flex-col w-full overflow-y-auto">
<div
:class="[
settings.docFont,
settings.docSize ? 'text-[15px]' : 'text-[17px]',
settings.docWidth
? 'sm:min-w-[75vw] sm:max-w-[75vw]'
: 'sm:min-w-[21cm] sm:max-w-[21cm]',
]"
class="flex sm:w-full items-start justify-start lg:justify-center mx-auto"
>
<editor-content
id="editor-capture"
class="min-w-full"
autocomplete="true"
autocorrect="true"
autocapitalize="true"
:spellcheck="settings.docSpellcheck ? true : false"
:editor="editor"
@keydown.enter.passive="handleEnterKey"
/>
</div>
<TableBubbleMenu v-if="isWritable" :editor="editor" />
<BubbleMenu
v-if="editor"
v-show="!forceHideBubbleMenu"
plugin-key="main"
:should-show="shouldShow"
:editor="editor"
>
<Menu :buttons="bubbleMenuButtons" />
</BubbleMenu>
</div>
<DocMenuAndInfoBar
v-if="editor && initComplete"
ref="MenuBar"
v-model:allAnnotations="allAnnotations"
v-model:activeAnnotation="activeAnnotation"
:editor="editor"
:versions="versions"
:settings="settings"
/>
<FilePicker
v-if="showFilePicker"
v-model="showFilePicker"
:suggested-tab-index="0"
@success="
(val) => {
pickedFile = val
showFilePicker = false
if (editor) {
if (editable) {
wordToHTML()
}
}
}
"
/>
<SnapshotPreviewDialog
v-if="snapShotDialog"
v-model="snapShotDialog"
:snapshot-data="selectedSnapshot"
@success="
() => {
selectedSnapshot = null
}
"
/>
</template>
<script>
import FilePicker from "@/components/FilePicker.vue"
import { toast } from "@/utils/toasts.js"
import Link from "@tiptap/extension-link"
import TaskItem from "@tiptap/extension-task-item"
import TaskList from "@tiptap/extension-task-list"
import Typography from "@tiptap/extension-typography"
import StarterKit from "@tiptap/starter-kit"
import { BubbleMenu, Editor, EditorContent } from "@tiptap/vue-3"
import { onOutsideClickDirective } from "frappe-ui"
import { DOMParser } from "prosemirror-model"
import { v4 as uuidv4 } from "uuid"
import { computed, normalizeClass } from "vue"
import { IndexeddbPersistence } from "y-indexeddb"
import { WebrtcProvider } from "y-webrtc"
import * as Y from "yjs"
import { uploadDriveEntity } from "../../utils/chunkFileUpload"
import { detectMarkdown, markdownToHTML } from "../../utils/markdown"
import DocMenuAndInfoBar from "./components/DocMenuAndInfoBar.vue"
import configureMention from "./extensions/mention/mention"
import Menu from "./components/Menu.vue"
import { Table } from "./extensions/table"
import TableBubbleMenu from "./components/TableBubbleMenu.vue"
import { Comment } from "./extensions/comment"
import { PageBreak } from "./extensions/Pagebreak"
import { Highlight } from "./extensions/backgroundColor"
import { CharacterCount } from "./extensions/character-count"
import { Collaboration } from "./extensions/collaboration"
import { CollaborationCursor } from "./extensions/collaborationCursor"
import { Color } from "./extensions/color"
import { FontFamily } from "./extensions/font-family"
import { FontSize } from "./extensions/font-size"
import { Indent } from "./extensions/indent"
import { LineHeight } from "./extensions/lineHeight"
import { Placeholder } from "./extensions/placeholder"
import { TextAlign } from "./extensions/text-align"
import { TextStyle } from "./extensions/text-style"
import { Underline } from "./extensions/underline"
import { ResizableMedia } from "./extensions/resizenode"
import { createEditorButton } from "./utils"
import { Annotation } from "./extensions/AnnotationExtension/annotation"
import suggestion from "./extensions/suggestion/suggestion"
import Commands from "./extensions/suggestion/suggestionExtension"
import SnapshotPreviewDialog from "./components/SnapshotPreviewDialog.vue"
import { formatDate } from "../../utils/format"
import { Paragraph } from "./extensions/paragraph"
export default {
name: "TextEditor",
components: {
EditorContent,
BubbleMenu,
Menu,
DocMenuAndInfoBar,
FilePicker,
TableBubbleMenu,
SnapshotPreviewDialog,
},
directives: {
onOutsideClick: onOutsideClickDirective,
},
provide() {
return {
editor: computed(() => this.editor),
document: computed(() => this.document),
versions: computed(() => this.versions),
}
},
inheritAttrs: false,
//expose: ["editor", "versions"],
props: {
settings: {
type: Object,
default: null,
},
entityName: {
default: "",
type: String,
required: false,
},
entity: {
default: null,
type: Object,
required: false,
},
documentName: {
default: "",
type: String,
required: false,
},
yjsContent: {
type: Uint8Array,
required: true,
default: null,
},
lastSaved: {
type: Number,
required: true,
},
rawContent: {
type: String,
required: true,
default: null,
},
isWritable: {
type: Boolean,
default: false,
},
userList: {
type: Object,
required: true,
default: null,
},
},
emits: [
"update:yjsContent",
"updateTitle",
"saveDocument",
"mentionedUsers",
"update:rawContent",
"update:lastSaved",
],
data() {
return {
docWidth: this.settings.docWidth,
docSize: this.settings.docSize,
docFont: this.settings.docFont,
editor: null,
defaultFont: "font-sans",
buttons: [],
forceHideBubbleMenu: false,
synced: false,
peercount: 0,
initComplete: true,
provider: null,
document: null,
awareness: null,
connectedUsers: null,
localStore: null,
tempEditable: true,
isTextSelected: false,
currentMode: "",
showCommentMenu: false,
commentText: "",
isCommentModeOn: true,
isReadOnly: false,
showFilePicker: false,
pickedFile: null,
activeCommentsInstance: {
uuid: "",
comments: [],
},
implicitTitle: "",
allAnnotations: [],
allComments: [],
activeAnnotation: "",
activeAnchorAnnotations: null,
isNewDocument: this.entity.title.includes("Untitled Document"),
versions: [],
selectedSnapshot: null,
snapShotDialog: false,
}
},
computed: {
editable() {
return this.isWritable && this.tempEditable
},
bubbleMenuButtons() {
if (this.entity.owner === "You" || this.entity.write) {
let buttons = [
"Bold",
"Italic",
"Underline",
"Strikethrough",
"Code",
"Separator",
"Link",
"Separator",
"NewAnnotation",
//"Comment",
]
return buttons.map(createEditorButton)
} else if (this.entity.allow_comments) {
let buttons = ["Comment"]
return buttons.map(createEditorButton)
}
return []
},
currentUserName() {
return this.$store.state.user.fullName
},
currentUserImage() {
return this.$store.state.user.imageURL
},
},
watch: {
activeAnchorAnnotations: {
handler(newVal) {
if (newVal) {
// unexpected case??
let yArray = this.document.getArray("docAnnotations")
// Toggle visibility if it's not visible in the document anymore
yArray.forEach((item) => {
if (newVal.has(item.get("id"))) {
item.set("anchor", 1)
} else {
item.set("anchor", 0)
}
})
}
},
},
isNewDocument: {
handler(val) {
if (val) {
this.$store.state.passiveRename = true
} else {
this.$store.state.passiveRename = false
}
},
immediate: true,
},
lastSaved(newVal) {
const ymap = this.document.getMap("docinfo")
const lastSaved = ymap.get("lastsaved")
if (newVal > lastSaved) {
ymap.set("lastsaved", newVal)
}
},
settings(newVal) {
switch (newVal.toLowerCase()) {
case "sans":
this.defaultFont = "font-['Nunito']"
break
case "serif":
this.defaultFont = "font-['Lora']"
break
case "round":
this.defaultFont = "font-['Nunito']"
break
case "mono":
this.defaultFont = "font-['Geist-Mono']"
break
default:
this.defaultFont = "font-['InterVar']"
}
},
activeCommentsInstance: {
handler(newVal) {
if (newVal) {
// check if userid is available
this.$store.commit(
"setActiveCommentsInstance",
JSON.stringify(newVal)
)
}
},
immediate: true,
},
allComments: {
handler(newVal) {
if (newVal) {
this.$store.commit("setAllComments", JSON.stringify(newVal))
}
},
immediate: true, // make this watch function is called when component created
},
editable(value) {
this.editor.setEditable(value)
},
},
mounted() {
if (window.matchMedia("(max-width: 1500px)").matches) {
this.$store.commit("setIsSidebarExpanded", false)
}
this.emitter.on("exportDocToPDF", () => {
if (this.editor) {
this.printEditorContent()
}
})
this.emitter.on("forceHideBubbleMenu", (val) => {
if (this.editor) {
this.forceHideBubbleMenu = val
}
})
this.emitter.on("importDocFromWord", () => {
this.showFilePicker = true
})
const doc = new Y.Doc({ gc: false })
const ymap = doc.getMap("docinfo")
ymap.set("lastsaved", this.lastSaved)
this.document = doc
const indexeddbProvider = new IndexeddbPersistence(
"fdoc-" + JSON.stringify(this.entityName),
doc
)
Y.applyUpdate(doc, this.yjsContent)
const webrtcProvider = new WebrtcProvider(
"fdoc-" + JSON.stringify(this.entityName),
doc,
{ signaling: ["wss://network.arjunchoudhary.com"] }
)
ymap.observe(() => {
this.$emit("update:lastSaved", ymap.get("lastsaved"))
})
this.provider = webrtcProvider
this.awareness = this.provider.awareness
this.localStore = indexeddbProvider
let componentContext = this
document.addEventListener("keydown", this.saveDoc)
this.editor = new Editor({
editable: this.editable,
autofocus: "start",
editorProps: {
attributes: {
class: normalizeClass([
`ProseMirror prose prose-sm prose-table:table-fixed prose-td:p-2 prose-th:p-2 prose-td:border prose-th:border prose-td:border-gray-300 prose-th:border-gray-300 prose-td:relative prose-th:relative prose-th:bg-gray-100 rounded-b-lg max-w-[unset] pb-[50vh] md:px-[70px]`,
]),
},
clipboardTextParser: (text, $context) => {
if (!detectMarkdown(text)) return
if (
!confirm(
"Do you want to convert markdown content to HTML before pasting?"
)
)
return
let dom = document.createElement("div")
dom.innerHTML = markdownToHTML(text)
let parser =
this.editor.view.someProp("clipboardParser") ||
this.editor.view.someProp("domParser") ||
DOMParser.fromSchema(this.editor.schema)
return parser.parseSlice(dom, {
preserveWhitespace: true,
context: $context,
})
},
},
onCreate() {
//componentContext.findCommentsAndStoreValues()
//componentContext.updateConnectedUsers(componentContext.editor)
},
// evaluate document version
onUpdate() {
//componentContext.updateConnectedUsers(componentContext.editor)
//componentContext.findCommentsAndStoreValues()
componentContext.setCurrentComment()
componentContext.$emit(
"update:rawContent",
componentContext.editor.getHTML()
)
componentContext.$emit(
"mentionedUsers",
componentContext.parseMentions(componentContext.editor.getJSON())
)
componentContext.$emit(
"update:yjsContent",
Y.encodeStateAsUpdate(componentContext.document)
)
componentContext.updateAnnotationStatus()
},
onSelectionUpdate() {
//componentContext.updateConnectedUsers(componentContext.editor)
//componentContext.setCurrentComment()
//componentContext.isTextSelected =
// !!componentContext.editor.state.selection.content().size
},
// eslint-disable-next-line no-sparse-arrays
extensions: [
StarterKit.configure({
history: false,
paragraph: {
HTMLAttributes: {
class: this.entity.version > 0 ? "not-prose" : "",
},
},
heading: {
levels: [1, 2, 3, 4, 5],
},
listItem: {
HTMLAttributes: {
class: "prose-list-item",
},
},
codeBlock: {
HTMLAttributes: {
spellcheck: false,
class:
"not-prose my-5 px-4 py-2 text-[0.9em] font-mono text-black bg-gray-50 rounded border border-gray-300 overflow-x-auto",
},
},
blockquote: {
HTMLAttributes: {
class:
"prose-quoteless text-black border-l-2 pl-2 border-gray-400 text-[0.9em]",
},
},
code: {
HTMLAttributes: {
class:
"not-prose px-px font-mono bg-gray-50 text-[0.85em] rounded-sm border border-gray-300",
},
},
bulletList: {
keepMarks: true,
keepAttributes: false,
HTMLAttributes: {
class: "",
},
},
orderedList: {
keepMarks: true,
keepAttributes: false,
HTMLAttributes: {
class: "",
},
},
}),
Commands.configure({
suggestion,
}),
Table,
FontFamily.configure({
types: ["textStyle"],
}),
TextAlign.configure({
types: ["heading", "paragraph"],
defaultAlignment: "left",
}),
,
PageBreak,
Annotation.configure({
onAnnotationClicked: (ID) => {
componentContext.setAndFocusCurrentAnnotation(ID)
},
onAnnotationActivated: (ID) => {
//this.activeAnnotation = ID
if (ID) setTimeout(() => componentContext.setCurrentAnnotation(ID))
},
HTMLAttributes: {
//class: 'cursor-pointer annotation annotation-number'
//class: 'cursor-pointer bg-amber-300 bg-opacity-20 border-b-2 border-yellow-300 pb-[1px]'
class: "cursor-pointer annotation",
},
}),
Collaboration.configure({
document: doc,
}),
CollaborationCursor.configure({
provider: webrtcProvider,
user: {
name: this.currentUserName,
avatar: this.currentUserImage,
color: this.RndColor(),
},
}),
LineHeight,
Indent,
Link.configure({
openOnClick: false,
}),
Comment.configure({
isCommentModeOn: this.isCommentModeOn,
}),
Placeholder.configure({
placeholder: "Press / for commands",
}),
Highlight.configure({
multicolor: true,
}),
configureMention(this.userList),
TaskList.configure({
HTMLAttributes: {
class: "not-prose",
},
}),
TaskItem.configure({
HTMLAttributes: {
class: "my-task-item",
},
}),
CharacterCount,
Underline,
Typography,
TextStyle,
FontSize.configure({
types: ["textStyle"],
}),
Color.configure({
types: ["textStyle"],
}),
ResizableMedia.configure({
uploadFn: (file) => uploadDriveEntity(file, this.entityName),
}),
],
})
this.emitter.on("emitToggleCommentMenu", () => {
if (this.editor?.isActive("comment") !== true) {
this.showCommentMenu = !this.showCommentMenu
} else {
this.$store.state.showInfo = true
this.$refs.MenuBar.tab = 5
}
})
window.addEventListener("offline", () => {
this.provider.disconnect()
this.synced = false
this.connected = false
this.peercount = 0
})
window.addEventListener("online", () => {
this.provider.connect()
})
this.localStore.on("synced", () => {
this.initComplete = true
})
this.provider.on("status", (e) => {
this.connected = e.connected
})
this.provider.on("peers", (e) => {
this.peercount = e.webrtcPeers.length
})
this.awareness.on("update", () => {
this.$store.commit(
"setConnectedUsers",
this.editor?.storage.collaborationCursor.users
)
})
this.provider.on("synced", (e) => {
this.synced = e.synced
})
this.$realtime.doc_subscribe("Drive Entity", this.entityName)
this.$realtime.doc_open("Drive Entity", this.entityName)
this.$realtime.on("document_version_change_recv", (data) => {
const { doctype, document, author, author_image, author_id } = data
if (author_id === this.$realtime.socket.id) {
toast({
title: "You changed the document version",
position: "bottom-right",
timeout: 2,
})
return
}
toast({
title: `Document version changed`,
position: "bottom-right",
avatarURL: author_image,
avatarLabel: author,
timeout: 2,
})
})
},
updated() {
if (this.isNewDocument) {
this.evalImplicitTitle()
}
},
beforeUnmount() {
this.$realtime.off("document_version_change_recv")
this.$realtime.doc_close("Drive Entity", this.entityName)
this.$realtime.doc_unsubscribe("Drive Entity", this.entityName)
this.updateConnectedUsers(this.editor)
this.$store.state.passiveRename = false
document.removeEventListener("keydown", this.saveDoc)
this.editor.destroy()
this.document.destroy()
this.provider.disconnect()
this.provider.destroy()
this.provider = null
this.editor = null
},
methods: {
updateAnnotationStatus() {
const temp = new Set()
this.editor.state.doc.descendants((node, pos) => {
const { marks } = node
marks.forEach((mark) => {
if (mark.type.name === "annotation") {
const annotationMark = mark.attrs.annotationID
temp.add(annotationMark)
}
})
})
this.activeAnchorAnnotations = temp
},
handleEnterKey() {
if (this.$store.state.passiveRename) {
if (!this.implicitTitle.length) return
this.isNewDocument = false
}
},
updateConnectedUsers(editor) {
this.$store.commit(
"setConnectedUsers",
editor.storage.collaborationCursor.users
)
},
async wordToHTML() {
let ctx = this
if (
ctx.pickedFile?.mime_type ===
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
ctx.pickedFile?.file_ext == ".docx"
) {
const headers = {
Accept: "application/json",
"Content-Type": "application/json; charset=utf-8",
"X-Frappe-Site-Name": window.location.hostname,
Range: "bytes=0-10000000",
}
const res = await fetch(
`/api/method/drive.api.files.get_file_content?entity_name=${ctx.pickedFile.name}`,
{
method: "GET",
headers,
}
)
if (res.ok) {
let blob = await res.arrayBuffer()
const { convertToHtml } = await import("mammoth")
convertToHtml({ arrayBuffer: blob })
.then(function (result) {
ctx.editor.commands.insertContent(result.value)
})
.catch(function (error) {
console.error(error)
})
//.then((x) => console.log("docx: finished"));
}
} else {
toast({
title: "Not a valid DOCX file!",
position: "bottom-right",
icon: "alert-triangle",
iconClasses: "text-red-500",
timeout: 2,
})
}
},
saveDoc(e) {
if (!(e.keyCode === 83 && (e.ctrlKey || e.metaKey))) {
return
}
e.preventDefault()
this.$emit("update:rawContent", this.editor.getHTML())
this.$emit("update:yjsContent", Y.encodeStateAsUpdate(this.document))
this.$emit("mentionedUsers", this.parseMentions(this.editor.getJSON()))
if (this.synced || this.peercount === 0) {
this.$emit("saveDocument")
}
toast({
title: "Document saved",
position: "bottom-right",
timeout: 2,
})
},
printHtml(dom) {
const style = Array.from(document.querySelectorAll("style, link")).reduce(
(str, style) => str + style.outerHTML,
""
)
const content = style + dom.outerHTML
const iframe = document.createElement("iframe")
iframe.id = "el-tiptap-iframe"
iframe.setAttribute(
"style",
"position: absolute; width: 0; height: 0; top: -10px; left: -10px;"
)
document.body.appendChild(iframe)
const frameWindow = iframe.contentWindow
const doc =
iframe.contentDocument ||
(iframe.contentWindow && iframe.contentWindow.document)
if (doc) {
doc.open()
doc.write(content)
doc.close()
}
if (frameWindow) {
iframe.onload = function () {
try {
setTimeout(() => {
frameWindow.focus()
try {
if (!frameWindow.document.execCommand("print", false)) {
frameWindow.print()
}
} catch (e) {
frameWindow.print()
}
frameWindow.close()
}, 10)
} catch (err) {
console.error(err)
}
setTimeout(function () {
document.body.removeChild(iframe)
}, 100)
}
}
},
printEditorContent() {
const editorContent = document.getElementById("editor-capture")
if (editorContent) {
this.printHtml(editorContent)
return true
}
return false
},
shouldShow: ({ state }) => {
const { from, to } = state.selection
// Check if the selection is within a text node
const node = state.doc.nodeAt(from)
if (node && node.type.name === "text") {
// Ensure the selection is not empty
return from !== to
}
return false // Hide the menu if the selection is outside a text node
},
RndColor() {
const max = 255
const min = 100
const range = max - min
const red = Math.floor(Math.random() * range) + min
const green = Math.floor(Math.random() * range) + min
const blue = Math.floor(Math.random() * range) + min
const redToHex = red.toString(16)
const greenToHex = green.toString(16)
const blueToHex = blue.toString(16)
return "#" + redToHex + greenToHex + blueToHex
},
discardComment() {
this.commentText = ""
this.isCommentModeOn = false
},
getIsCommentModeOn() {
return this.isCommentModeOn
},
focusContent({ from, to }) {
this.editor.chain().setTextSelection({ from, to }).run()
},
findCommentsAndStoreValues() {
const tempComments = []
this.editor.state.doc.descendants((node, pos) => {
const { marks } = node
marks.forEach((mark) => {
if (mark.type.name === "comment") {
const markComments = mark.attrs.comment
const jsonComments = markComments ? JSON.parse(markComments) : null
if (
jsonComments !== null &&
!tempComments.find(
(el) => el.jsonComments.uuid === jsonComments.uuid
)
) {
tempComments.push({
node,
jsonComments,
from: pos,
to: pos + (node.text?.length || 0),
text: node.text,
})
}
}
})
})
return (this.allComments = tempComments)
},
setCurrentAnnotation() {
let newVal = this.editor.isActive("annotation")
const sideBarState =
this.$store.state.showInfo && this.$refs.MenuBar.tab == 5
if (newVal && sideBarState) {
this.activeAnnotation =
this.editor.getAttributes("annotation").annotationID
}
},
//Click
setAndFocusCurrentAnnotation() {
let newVal = this.editor.isActive("annotation")
if (newVal) {
this.$store.state.showInfo = true
this.$refs.MenuBar.tab = 5
this.activeAnnotation =
this.editor.getAttributes("annotation").annotationID
}
},
setCurrentComment() {
let newVal = this.editor.isActive("comment")
if (newVal) {
this.$store.state.showInfo = true
this.$refs.MenuBar.tab = 5
const parsedComment = JSON.parse(
this.editor.getAttributes("comment").comment
)
parsedComment.comments =
typeof parsedComment.comments === "string"
? JSON.parse(parsedComment.comments)
: parsedComment.comments
this.activeCommentsInstance = parsedComment
} else {
this.activeCommentsInstance = {}
}
},
setComment(val) {
const localVal = val || this.commentText
if (!localVal.trim().length) return
const currentSelectedComment = JSON.parse(
JSON.stringify(this.activeCommentsInstance)
)
const commentsArray =
typeof currentSelectedComment.comments === "string"
? JSON.parse(currentSelectedComment.comments)
: currentSelectedComment.comments
if (commentsArray) {
commentsArray.push({
userName: this.currentUserName,
userImage: this.currentUserImage,
time: Date.now(),
content: localVal,
})
const commentWithUuid = JSON.stringify({
uuid: this.activeCommentsInstance.uuid || uuidv4(),
comments: commentsArray,
})
this.editor.chain().setComment(commentWithUuid).run()
this.commentText = ""
} else {
const commentWithUuid = JSON.stringify({
uuid: uuidv4(),
comments: [
{
userName: this.currentUserName,
userImage: this.currentUserImage,
time: Date.now(),
content: localVal,
},
],
})
this.editor.chain().setComment(commentWithUuid).run()
this.commentText = ""
}
},
parseMentions(data) {
const tempMentions = (data.content || []).flatMap(this.parseMentions)
if (data.type === "mention") {
tempMentions.push({
id: data.attrs.id,
author: data.attrs.author,
type: data.attrs.type,
})
}
const uniqueMentions = [
...new Set(tempMentions.map((item) => item.id)),
].map((id) => tempMentions.find((item) => item.id === id))
return uniqueMentions
},
evalImplicitTitle() {
this.implicitTitle = this.editor.state.doc.textContent.trim().slice(0, 35)
this.implicitTitle = this.implicitTitle.trim()
if (this.implicitTitle.charAt(0) === "@") {
return
}
if (this.implicitTitle.length && this.$store.state.passiveRename) {
this.$store.state.entityInfo[0].title = this.implicitTitle
this.$resources.rename.submit({
entity_name: this.entityName,
new_title: this.implicitTitle,
})
}
},
},
resources: {
rename() {
return {
url: "drive.api.files.passive_rename",
debounce: 500,
}
},
},
}
</script>
<style>
.ProseMirror {
outline: none;
caret-color: theme("colors.blue.600");
word-break: break-word;
-webkit-user-select: none;
-ms-user-select: none;
user-select: text;
padding: 4em 1em;
background: white;
}
/* 640 is sm from espresso design */
@media only screen and (max-width: 640px) {
.ProseMirror {
display: block;
max-width: 100%;
min-width: 100%;
}
}
.ProseMirror a {
text-decoration: underline;
}
/* Firefox */
.ProseMirror-focused:focus-visible {
outline: none;
}
@page {
size: a4;
margin: 4em;
}
/*
Omit the page break div from printing added from `PageBreak.ts`
*/
@media print {
#page-break-div {
border: none !important;
margin: none !important;
}
}
/*
span[data-comment] {
background: rgba(255, 215, 0, 0.15);
border-bottom: 2px solid rgb(255, 210, 0);
user-select: text;
padding: 2px;
}
*/
span[data-annotation-id] {
background: rgba(255, 215, 0, 0.15);
border-bottom: 2px solid rgb(255, 210, 0);
user-select: text;
padding: 2px;
}
.collaboration-cursor__caret {
border-left: 0px solid currentColor;
border-right: 2px solid currentColor;
margin-left: 0px;
margin-right: -2px;
pointer-events: none;
position: relative;
word-break: normal;
}
/* Render the username above the caret */
.collaboration-cursor__label {
border-radius: 60px;
border: 2px solid #0000001a;
color: #ffffffdf;
font-size: 0.65rem;
font-style: normal;
font-family: "Inter";
font-weight: 500;
line-height: normal;
padding: 0.1rem 0.25rem;
position: absolute;
top: -1.5em;
left: 0.25em;
user-select: none;
white-space: nowrap;
}
/* Check list */
.my-task-item {
display: flex;
}
.my-task-item input {
border-radius: 4px;
outline: 0;
margin-right: 10px;
}
.my-task-item input[type="checkbox"]:hover {
outline: 0;
background-color: #d6d6d6;
cursor: pointer;
transition: background 0.2s ease, border 0.2s ease;
}
.my-task-item input[type="checkbox"]:focus {
outline: 0;
background-color: #5b5b5b;
}
.my-task-item input[type="checkbox"]:active {
outline: 0;
background-color: #5b5b5b;
}
.my-task-item input[type="checkbox"]:checked {
outline: 0;
background-color: #000000;
}
summary {
display: flex;
width: 100%;
padding: 0 2.5rem;
box-sizing: border-box;
pointer-events: none;
outline: none;
}
summary p {
margin-top: 0.15rem !important;
margin-bottom: 0.15rem !important;
}
.grip-row.selected {
background-color: #e3f0fce2;
content: "✓";
}
.grip-column.selected {
background-color: #e3f0fce2;
}
.grip-column.selected::before {
content: "✓";
position: absolute;
color: white;
top: -25%;
left: 0%;
font-weight: 600;
}
.grip-row.selected::before {
content: "✓";
position: absolute;
color: white;
top: -25%;
left: 0%;
font-weight: 600;
}
</style>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/TextEditor.vue
|
Vue
|
agpl-3.0
| 31,542
|
import { defineAsyncComponent } from "vue"
import { Code } from "lucide-vue-next"
import Bold from "./icons/Bold.vue"
import Italic from "./icons/Italic.vue"
import Strikethrough from "./icons/StrikeThrough.vue"
import Underline from "./icons/Underline.vue"
import { default as NewCommentIcon } from "../EspressoIcons/Comment.vue"
import { default as NewLink } from "../EspressoIcons/Link.vue"
import { TableCellsSplit, TableCellsMerge } from "lucide-vue-next"
import ToggleHeaderCell from "./icons/ToggleHeaderCell.vue"
export default {
Bold: {
label: "Bold",
icon: Bold,
action: (editor) => editor.chain().focus().toggleBold().run(),
isActive: (editor) => editor.isActive("bold"),
},
Italic: {
label: "Italic",
icon: Italic,
action: (editor) => editor.chain().focus().toggleItalic().run(),
isActive: (editor) => editor.isActive("italic"),
},
Underline: {
label: "Underline",
icon: Underline,
action: (editor) => editor.chain().focus().toggleUnderline().run(),
isActive: (editor) => editor.isActive("underline"),
},
Strikethrough: {
label: "Strikethrough",
icon: Strikethrough,
action: (editor) => editor.chain().focus().toggleStrike().run(),
isActive: (editor) => editor.isActive("strike"),
},
Code: {
label: "Code",
icon: Code,
action: (editor) => editor.chain().focus().toggleCode().run(),
isActive: (editor) => editor.isActive("code"),
},
Link: {
label: "New Link",
icon: NewLink,
isActive: (editor) => editor.isActive("link"),
component: defineAsyncComponent(() =>
import("./components/InsertLink.vue")
),
},
Separator: {
type: "separator",
},
NewAnnotation: {
label: "New Annotation",
icon: NewCommentIcon,
isActive: (editor) => editor.isActive("comment"),
component: defineAsyncComponent(() =>
import("./components/NewAnnotation.vue")
),
},
Comment: {
label: "New Comment",
icon: NewLink,
isActive: (editor) => editor.isActive("comment"),
component: defineAsyncComponent(() =>
import("./components/NewComment.vue")
),
},
MergeCells: {
label: "Merge Cells",
icon: TableCellsMerge,
isActive: () => false,
action: (editor) => editor.chain().focus().mergeCells().run(),
},
SplitCells: {
label: "Split Cells",
icon: TableCellsSplit,
isActive: () => false,
action: (editor) => editor.chain().focus().splitCell().run(),
},
ToggleHeaderCell: {
label: "Toggle Header",
icon: ToggleHeaderCell,
isActive: () => false,
action: (editor) => editor.chain().focus().toggleHeaderCell().run(),
},
}
|
2302_79757062/drive
|
frontend/src/components/DocEditor/commands.js
|
JavaScript
|
agpl-3.0
| 2,648
|
<template>
<div class="select-text">
<div class="flex items-center justify-start mb-6">
<span
class="inline-flex items-center gap-2.5 text-gray-800 font-medium text-lg w-full"
>
Annotations
</span>
<Dropdown :options="filterItems" placement="left">
<Button>
<template #prefix>
<Filter />
</template>
{{ currentFilterLabel }}
</Button>
</Dropdown>
</div>
<div class="divide-y space-y-4">
<!-- root annotations -->
<div
v-if="currentFilter.length"
class="current-comment my-4"
@click="
emit('setActiveAnnotation', comment),
(currentActiveAnnotation = comment)
"
:class="
comment.get('id') === activeAnnotation ? 'active' : 'cursor-pointer'
"
v-for="(comment, i) in currentFilter"
>
<div class="mt-4 flex py-0.5 mb-2 gap-x-2 text-sm items-center">
<Avatar
size="md"
:label="comment.get('owner')"
:image="comment.get('ownerImage')"
class="mr-1"
/>
<div class="flex flex-col gap-y-0.5 mb-1">
<div class="flex items-center gap-x-0.5">
<span class="text-gray-800 text-sm font-medium">
{{ comment.get("owner") }}
</span>
<span class="text-gray-700 text-sm">{{ " ∙ " }}</span>
<span class="text-gray-700 text-sm">
{{ useTimeAgo(comment.get("createdAt")) }}
</span>
</div>
<span class="text-sm text-gray-700">
{{ comment.get("replies").length }}
{{ comment.get("replies").length === 1 ? " reply" : "replies" }}
</span>
</div>
<Dropdown
v-if="
comment.get('id') === activeAnnotation &&
(entity.write === 1 ||
comment.get('ownerEmail') === currentUserEmail)
"
:options="commentOptions"
placement="right"
class="ml-auto mb-auto"
>
<Button size="sm" variant="ghost" icon="more-horizontal" />
</Dropdown>
</div>
<div class="pl-10 text-sm leading-5">
<span
id="injected"
v-html="comment.get('content')"
class="max-w-full break-word text-sm text-gray-700"
>
</span>
</div>
<!-- replies for current annotation -->
<div v-if="comment.get('id') === activeAnnotation">
<div class="mt-6" v-for="(reply, j) in comment.get('replies')">
<div
class="flex py-0.5 gap-x-0.5 text-sm justify-start items-center mb-1.5"
>
<Avatar
size="md"
:label="reply.get('owner')"
:image="reply.get('ownerImage')"
class="mr-2"
/>
<span class="text-gray-800 text-sm font-medium">
{{ reply.get("owner") }}
</span>
<span class="text-gray-700 text-sm">{{ " ∙ " }}</span>
<span class="text-gray-700 text-sm">
{{ useTimeAgo(reply.get("createdAt")) }}
</span>
<Dropdown
v-if="
entity.owner === 'You' ||
reply.get('ownerEmail') === currentUserEmail
"
:options="replyOptions"
placement="right"
class="ml-auto"
>
<Button
size="sm"
variant="ghost"
icon="more-horizontal"
@click="currentActiveReplyAnnotation = reply"
/>
</Dropdown>
</div>
<div class="pl-9 -mt-1.5 text-sm leading-5">
<span
id="injected"
v-html="reply.get('content')"
class="max-w-full break-word text-gray-700"
>
</span>
</div>
</div>
<section
v-if="comment.get('id') === activeAnnotation"
class="flex flex-col gap-2"
>
<div class="flex items-center justify-start gap-2 mt-6 mb-2">
<Avatar size="md" :label="fullName" :image="imageURL" class="" />
<TiptapInput
v-model="commentText"
@success="addReply(comment.get('id'))"
@keyup.ctrl.enter="addReply(comment.get('id'))"
/>
</div>
</section>
</div>
</div>
<div v-else class="text-gray-600 text-sm my-5">
There are annotations for the current document or category
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { useStore } from "vuex"
import {
ref,
watch,
computed,
nextTick,
onUpdated,
onMounted,
h,
inject,
} from "vue"
import { Avatar, Button, Dropdown, createResource } from "frappe-ui"
import { v4 as uuidv4, v4 } from "uuid"
import { useTimeAgo } from "@vueuse/core"
import * as Y from "yjs"
import Filter from "@/components/EspressoIcons/Filter.vue"
import TiptapInput from "@/components/TiptapInput.vue"
const store = useStore()
const emit = defineEmits([
"setActiveAnnotation",
/* "update:allAnnotations", */
"update:activeAnnotation",
])
interface Props {
activeAnnotation: string
showAnnotations: boolean
}
const doc = inject("document")
const editor = inject("editor")
const props = defineProps<Props>()
const allAnnotations = doc.value.getArray("docAnnotations")
const currentActiveAnnotation = ref()
const currentActiveReplyAnnotation = ref()
const currentFilterLabel = ref("Open")
const currentFilterState = ref(0)
const commentText = ref<string>("")
const fullName = computed(() => store.state.user.fullName)
const email = computed(() => store.state.auth.user_id)
const imageURL = computed(() => store.state.user.imageURL)
const currentUserEmail = computed(() => store.state.auth.user_id)
const entity = computed(() => store.state.entityInfo[0])
const openAndAnchoredAnnotations = computed(() => {
let arr = allAnnotations.toArray()
return arr.filter(
(item) => item.get("anchor") === 1 && item.get("resolved") === 0
)
})
const openAnnotations = computed(() => {
let arr = allAnnotations.toArray()
return arr.filter(
(item) => item.get("anchor") === 0 && item.get("resolved") === 0
)
})
const allResolvedAnnotations = computed(() => {
let arr = allAnnotations.toArray()
return arr.filter((item) => item.get("resolved") === 1)
})
const currentFilter = computed(() => {
switch (currentFilterState.value) {
case 0:
currentFilterLabel.value = "Open"
return openAndAnchoredAnnotations.value
case 1:
currentFilterLabel.value = "Unanchored"
return openAnnotations.value
case 2:
currentFilterLabel.value = "Resolved"
return allResolvedAnnotations.value
default:
return openAndAnchoredAnnotations.value
}
})
const filterItems = computed(() => {
return [
{
label: "Open",
onClick: () => {
currentFilterState.value = 0
},
},
{
label: "Unanchored",
onClick: () => {
currentFilterState.value = 1
},
},
{
label: "Resolved",
onClick: () => {
currentFilterState.value = 2
},
},
].filter((item, index) => index !== currentFilterState.value)
})
const addReply = (parentID) => {
const newID = uuidv4()
const newReplyYmap = new Y.Map()
let parent
for (const value of allAnnotations) {
if (value.get("id") === parentID) {
parent = value
break
}
}
commentText.value = commentText.value.replace(/<p>(\s| )*<\/p>$/, "") // trim trailing p tags
let replies_arr = parent.get("replies")
newReplyYmap.set("id", newID)
newReplyYmap.set("content", commentText.value)
newReplyYmap.set("owner", fullName.value)
newReplyYmap.set("owner", fullName.value)
newReplyYmap.set("ownerEmail", email.value)
newReplyYmap.set("ownerImage", imageURL.value)
newReplyYmap.set("createdAt", Date.now())
replies_arr.push([newReplyYmap])
/* let newReply = {
id: uuidv4(),
enabled: 1,
parentID: parentID,
content: commentText.value,
owner: fullName.value,
ownerEmail: email.value,
createdAt: Date.now(),
};
let pval
for (const value of allAnnotations) {
if (value.id === parentID){
pval = value
break
}
}
*/
/* console.log(pval)
pval.replies.push(newReply) */
/* let parentComment = props.allAnnotations.find((item) => item.id === parentID);
if (parentComment && Array.isArray(parentComment.replies)) {
parentComment.replies.push(newReply);
} */
commentText.value = ""
}
const commentOptions = computed(() =>
[
/* {
label: "Edit",
onClick: () => {},
//icon: () => h(FeatherIcon, { name: "edit-2" }),
isEnabled: () => {
return true
},
}, */
{
label: "Mark as Resolved",
onClick: () => {
allAnnotations.forEach((yMap) => {
if (yMap.get("id") === currentActiveAnnotation.value.get("id")) {
yMap.set("resolved", 1)
editor.value
.chain()
.unsetAnnotation(currentActiveAnnotation.value.get("id"))
.run()
}
})
},
isEnabled: () => {
return (
!currentActiveAnnotation?.value?.get("resolved") &&
(currentActiveAnnotation?.value?.get("ownerEmail") ===
currentUserEmail ||
entity.value.write)
)
},
},
{
label: "Mark as Open",
onClick: () => {
allAnnotations.forEach((yMap) => {
if (yMap.get("id") === currentActiveAnnotation.value.get("id")) {
yMap.set("resolved", 0)
editor.value
.chain()
.setAnnotation(currentActiveAnnotation.value.get("id"))
.run()
}
})
},
isEnabled: () => {
return (
currentActiveAnnotation?.value?.get("resolved") &&
(currentActiveAnnotation?.value?.get("ownerEmail") ===
currentUserEmail ||
entity.value.write)
)
},
},
{
label: "Delete",
onClick: () => {
editor.value
.chain()
.unsetAnnotation(currentActiveAnnotation.value.get("id"))
.run()
wipeEntryById(allAnnotations, currentActiveAnnotation.value.get("id"))
},
isEnabled: () => {
return true
},
},
].filter((item) => item.isEnabled())
)
const replyOptions = computed(() =>
[
/* {
label: "Edit",
onClick: () => {},
isEnabled: () => {
return (
currentActiveReplyAnnotation?.value?.get("ownerEmail") ===
currentUserEmail.value
)
},
}, */
{
label: "Delete",
onClick: () => {
let yarray = allAnnotations
let targetId = currentActiveAnnotation.value.get("id")
parentLoop: for (let i = 0; i < yarray.length; i++) {
const ymap = yarray.get(i)
if (ymap.get("id") === targetId) {
let replies = ymap.get("replies")
for (let j = 0; j < replies.length; j++) {
const replyMap = replies.get(j)
if (
replyMap.get("id") ===
currentActiveReplyAnnotation.value.get("id")
) {
replies.delete(j)
break parentLoop
return
}
}
}
}
},
isEnabled: () => {
return (
currentActiveReplyAnnotation?.value?.get("ownerEmail") ===
currentUserEmail.value || entity.value.owner === "You"
)
},
},
].filter((item) => item.isEnabled())
)
// Move 'resolve' operations to a similar for loop
// exit early instead of forEach
function wipeEntryById(yarray, targetId) {
for (let index = 0; index < yarray.length; index++) {
const ymap = yarray.get(index)
if (ymap.get("id") === targetId) {
yarray.delete(index)
break
return
}
}
}
</script>
<style>
.current-comment {
/* transition: all 0.1s cubic-bezier(0.165, 0.84, 0.44, 1); */
transition: all 0.1s ease-in-out;
}
#injected p:empty::after {
content: "\A"; /* Inserts a line break */
white-space: pre; /* Preserves white space */
}
.current-comment.active {
padding: 15px 0px;
}
.slide-fade-enter-active {
transition: all 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
}
.slide-fade-leave-active {
transition: all 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
}
.slide-fade-enter-from,
.slide-fade-leave-to {
transform: translateY(10px);
opacity: 0;
}
</style>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/AnnotationList.vue
|
Vue
|
agpl-3.0
| 12,974
|
<template>
<ColorPicker
:model-value="value"
@update:model-value="(color) => emit('change', color)"
>
<template #target="{ togglePopover }">
<div class="flex items-stretch">
<span class="font-medium uppercase text-gray-600">
{{ label }}
</span>
<div class="relative w-full">
<div
:style="{
background: value
? value
: `url(/color-circle.png) center / contain`,
}"
class="absolute left-2 top-[6px] z-10 h-4 w-4 rounded shadow-sm cursor-pointer"
@click="togglePopover"
></div>
<Input
type="text"
class="rounded-md text-sm text-gray-700 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-300 dark:focus:bg-zinc-700"
placeholder="Set Color"
input-class="pl-8 pr-6"
:value="value"
@change="
(value) => {
value = getRGB(value)
emit('change', value)
}
"
></Input>
<div
v-show="value"
class="absolute right-1 top-[3px] cursor-pointer p-1 text-gray-700 dark:text-zinc-300"
@click="clearValue"
>
<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>
</div>
</div>
</div>
</template>
</ColorPicker>
</template>
<script setup lang="ts">
import { Input } from "frappe-ui"
import { getRGB } from "@/utils/helpers"
import ColorPicker from "./ColorPicker.vue"
defineProps({
value: {
type: String,
default: null,
},
label: {
type: String,
default: "",
},
})
const emit = defineEmits(["change"])
const clearValue = () => emit("change", null)
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/ColorInput.vue
|
Vue
|
agpl-3.0
| 2,211
|
<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>
<div
ref="colorPicker"
class="rounded-lg bg-white p-3 shadow-lg dark:bg-zinc-900"
>
<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,
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>
<svg
v-if="isSupported"
class="text-gray-700 dark:text-zinc-300"
@click="() => open()"
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>
</div>
</div>
</div>
</template>
</Popover>
</template>
<script setup lang="ts">
import { HSVToHex, HexToHSV, RGBToHex, getRGB } from "@/utils/helpers"
import { clamp, useEyeDropper } from "@vueuse/core"
import { Popover } from "frappe-ui"
import { PropType, Ref, StyleValue, computed, nextTick, ref, watch } from "vue"
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)
const mouseMove = (mouseMoveEvent: MouseEvent) => {
mouseMoveEvent.preventDefault()
setHue(mouseMoveEvent)
}
document.addEventListener("mousemove", mouseMove)
document.addEventListener(
"mouseup",
(mouseUpEvent) => {
document.removeEventListener("mousemove", mouseMove)
mouseUpEvent.preventDefault()
},
{ 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) 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/drive
|
frontend/src/components/DocEditor/components/ColorPicker.vue
|
Vue
|
agpl-3.0
| 9,355
|
<template>
<div
class="transition-all duration-200 ease-in-out h-full border-l overflow-y-auto"
:class="
showInfoSidebar
? 'sm:min-w-[352px] sm:max-w-[352px] min-w-full opacity-100'
: 'w-0 min-w-0 max-w-0 overflow-hidden opacity-0'
"
>
<div v-if="entity" class="w-full border-b pl-3 py-4">
<div class="flex items-center">
<div class="font-medium truncate text-lg">
{{ entity.title }}
</div>
</div>
</div>
<div v-if="entity && editor">
<!-- Info -->
<div v-if="tab === 4" class="px-5 py-4 border-b">
<span
class="inline-flex items-center gap-2.5 mb-5 text-gray-800 font-medium text-lg w-full"
>
Information
</span>
<div class="space-y-6.5 h-full flex-auto flex flex-col z-0">
<div v-if="entity.owner === 'You'">
<div class="text-base font-medium mb-4">Access</div>
<div class="flex items-center justify-start">
<Avatar
size="lg"
:label="entity.owner"
:image="entity.user_image"
></Avatar>
<div class="border-l h-6 mx-1.5"></div>
<GeneralAccess
v-if="
!$resources.generalAccess.loading &&
(!!$resources.generalAccess.data?.length ||
!sharedWithList?.length)
"
size="lg"
class="-mr-[3px] outline outline-white"
:general-access="$resources.generalAccess?.data?.[0]"
/>
<div
v-if="sharedWithList?.length"
class="flex items-center justify-start"
>
<Avatar
v-for="user in sharedWithList.slice(0, 3)"
:key="user?.user_name"
size="lg"
:label="user?.full_name ? user?.full_name : user?.user_name"
:image="user?.user_image"
class="-mr-[3px] outline outline-white"
/>
<Avatar
v-if="sharedWithList.slice(3).length"
size="lg"
:label="sharedWithList.slice(3).length.toString()"
class="-mr-[3px] outline outline-white"
/>
</div>
</div>
</div>
<!-- <div
v-if="
$resources.entityTags.data?.length || entity.owner === 'You'
"
>
<div class="text-base font-medium mb-4">Tags</div>
<div class="flex items-center justify-start flex-wrap gap-y-4">
<div
v-if="$resources.entityTags.data?.length"
class="flex flex-wrap gap-2 max-w-full"
>
<Tag
v-for="tag in $resources.entityTags?.data"
:key="tag"
:tag="tag"
:entity="entity"
@success="
() => {
userTags.fetch()
$resources.entityTags.fetch()
}
"
/>
</div>
<span v-else class="text-gray-700 text-sm">
This file has no tags
</span>
<Button
v-if="!addTag && entity.owner === 'You'"
class="ml-auto"
@click="addTag = true"
>
Add tag
</Button>
<TagInput
v-if="addTag"
:class="{ 'w-full': $resources.entityTags.data?.length }"
:entity="entity"
:unadded-tags="unaddedTags"
@success="
() => {
userTags.fetch()
$resources.entityTags.fetch()
addTag = false
}
"
@close="addTag = false"
/>
</div>
</div> -->
<div>
<div class="text-base font-medium mb-4">Properties</div>
<div class="text-base grid grid-flow-row grid-cols-2 gap-y-3">
<span class="col-span-1 text-gray-600">Type</span>
<span class="col-span-1">{{ formattedMimeType }}</span>
<span class="col-span-1 text-gray-600">Size</span>
<span class="col-span-1">{{ entity.file_size }}</span>
<span class="col-span-1 text-gray-600">Modified</span>
<span class="col-span-1">{{ entity.modified }}</span>
<span class="col-span-1 text-gray-600">Created</span>
<span class="col-span-1">{{ entity.creation }}</span>
<span class="col-span-1 text-gray-600">Owner</span>
<span class="col-span-1">{{ entity.full_name }}</span>
</div>
</div>
<div>
<div class="text-base font-medium mb-4">Stats</div>
<div class="text-base grid grid-flow-row grid-cols-2 gap-y-3">
<span class="col-span-1 text-gray-600">Words</span>
<span class="col-span-1">
{{ editor.storage.characterCount.words() }}
</span>
<span class="col-span-1 text-gray-600">Characters</span>
<span class="col-span-1">
{{ editor.storage.characterCount.characters() }}
</span>
<span class="col-span-1 text-gray-600">Reading Time</span>
<span class="col-span-1">
{{ Math.ceil(editor.storage.characterCount.words() / 200) }}
{{
Math.ceil(editor.storage.characterCount.words() / 200) > 1
? "mins"
: "min"
}}
</span>
</div>
</div>
</div>
</div>
<!-- Comments -->
<div v-if="tab === 5" class="px-5 py-4 border-b">
<AnnotationList
v-if="allAnnotations"
:active-annotation="activeAnnotation"
:all-annotations="allAnnotations"
:show-annotations="showComments"
@set-active-annotation="setActiveAnnotation"
/>
</div>
<!-- Versions -->
<div v-if="tab === 6" class="px-2 py-4 border-b">
<span
class="px-3 inline-flex items-center gap-2.5 text-gray-800 font-medium text-lg w-full"
>
Versions
<Button class="ml-auto" @click="generateSnapshot">New</Button>
</span>
<div
v-if="
!$resources.getversionList.loading &&
$resources.getversionList.data.length
"
>
<div
v-for="(version, i) in $resources.getversionList.data"
:key="version.name"
class="flex flex-col gap-y-1.5 p-2 m-2 hover:bg-gray-100 cursor-pointer rounded"
@click.stop="previewSnapshot(i)"
>
<span
:title="version.creation"
class="font-medium text-base text-gray-800"
>
{{ version.relativeTime }}
</span>
<span class="text-sm text-gray-700">
{{ version.snapshot_message }}
</span>
</div>
</div>
<div v-else class="text-gray-600 text-sm my-5 px-3">
No previous versions available for the current document
</div>
</div>
<!-- Typography -->
<div v-if="tab === 0" class="flex flex-col px-5 py-4 border-b">
<span
class="inline-flex items-center gap-2.5 mb-5 text-gray-800 font-medium text-lg w-full"
>
Style
</span>
<span class="font-medium text-gray-600 text-xs my-2">TITLE</span>
<div class="w-full flex justify-between gap-x-1.5 mb-6">
<Button
class="w-1/3 font-semibold"
@click="
editor
.chain()
.focus()
.clearNodes()
.unsetAllMarks()
.setHeading({ level: 1 })
.run()
"
>
Title
</Button>
<Button
class="w-1/3 font-medium"
@click="
editor
.chain()
.focus()
.clearNodes()
.unsetAllMarks()
.setHeading({ level: 2 })
.run()
"
>
Subtitle
</Button>
<Button
class="w-1/3"
@click="
editor
.chain()
.focus()
.clearNodes()
.unsetAllMarks()
.setHeading({ level: 3 })
.run()
"
>
Heading
</Button>
</div>
<span class="font-semibold text-gray-600 text-xs my-2">CONTENT</span>
<div class="w-full flex justify-between gap-x-1.5 mb-6">
<Button
class="w-1/3 font-bold"
@click="
editor
.chain()
.focus()
.clearNodes()
.unsetAllMarks()
.setBold()
.setHeading({ level: 4 })
.run()
"
>
Strong
</Button>
<Button
class="w-1/3"
@click="
editor
.chain()
.focus()
.clearNodes()
.unsetAllMarks()
.setParagraph()
.run()
"
>
Body
</Button>
<Button
class="w-1/3"
@click="
editor
.chain()
.focus()
.clearNodes()
.unsetAllMarks()
.setHeading({ level: 5 })
.setFontSize('0.9rem')
.setColor('#7c7c7c')
.run()
"
>
Caption
</Button>
</div>
<span class="font-medium text-gray-600 text-xs my-2">GROUPS</span>
<div
class="flex flex-row w-full bg-gray-100 justify-stretch items-stretch rounded p-0.5 space-x-0.5 h-8 mb-2"
>
<Button
class="w-full"
:class="
editor.isActive('bold') ? 'bg-white border' : 'bg-transparent'
"
@click="editor.chain().focus().toggleBold().run()"
>
<Bold class="w-4 stroke-2" />
</Button>
<Button
class="w-full"
:class="
editor.isActive('italic')
? 'bg-white shadow-sm'
: 'bg-transparent'
"
@click="editor.chain().focus().toggleItalic().run()"
>
<FeatherIcon name="italic" class="w-4 stroke-2" />
</Button>
<Button
class="w-full"
:class="
editor.isActive('underline')
? 'bg-white shadow-sm'
: 'bg-transparent'
"
@click="editor.chain().focus().toggleUnderline().run()"
>
<Underline class="w-4 stroke-2" />
</Button>
<Button
class="w-full"
:class="
editor.isActive('strike')
? 'bg-white shadow-sm'
: 'bg-transparent'
"
@click="editor.chain().focus().toggleStrike().run()"
>
<Strikethrough class="w-4 stroke-2" />
</Button>
<Button
class="w-full"
:class="
editor.isActive('code') ? 'bg-white shadow-sm' : 'bg-transparent'
"
@click="editor.chain().focus().toggleCode().run()"
>
<Code class="w-4 stroke-2" />
</Button>
</div>
<div
class="flex flex-row w-full bg-gray-100 justify-stretch items-stretch rounded p-0.5 space-x-0.5 h-8 mb-2"
>
<Button
class="w-full"
:class="
editor.isActive('bulletList')
? 'bg-white shadow-sm'
: 'bg-transparent'
"
@click="editor.chain().focus().toggleBulletList().run()"
>
<template #icon>
<List class="w-4 stroke-2" />
</template>
</Button>
<!-- <Button
class="w-full"
:class="
editor.isActive('details')
? 'bg-white shadow-sm'
: 'bg-transparent'
"
@click="
editor.isActive('details')
? editor.chain().focus().removeDetails().run()
: editor.chain().focus().setDetails().run()
"
>
<template #icon>
<Details class="w-4" />
</template>
</Button> -->
<Button
class="w-full"
:class="
editor.isActive('orderedList')
? 'bg-white shadow-sm'
: 'bg-transparent'
"
@click="editor.chain().focus().toggleOrderedList().run()"
>
<template #icon>
<OrderList class="w-4" />
</template>
</Button>
<Button
class="w-full"
:class="
editor.isActive('taskList')
? 'bg-white shadow-sm'
: 'bg-transparent'
"
@click="editor.chain().focus().toggleTaskList().run()"
>
<template #icon>
<Check class="w-4" />
</template>
</Button>
</div>
<div class="flex gap-x-1.5 mb-6">
<div
class="flex flex-row bg-gray-100 justify-stretch items-stretch rounded p-0.5 space-x-0.5 h-8"
>
<Button
:variant="'subtle'"
@click="editor.chain().focus().indent().run()"
>
<Indent class="h-4" />
</Button>
<Button
:variant="'subtle'"
@click="editor.chain().focus().outdent().run()"
>
<Outdent class="h-4" />
</Button>
</div>
<div
class="flex flex-row w-full bg-gray-100 justify-stretch items-stretch rounded p-0.5 space-x-0.5 h-8"
>
<Button
class="w-full"
:class="
editor.isActive({ textAlign: 'left' })
? 'bg-white shadow-sm'
: 'bg-transparent'
"
@click="editor.chain().focus().setTextAlign('left').run()"
>
<alignLeft class="w-4" />
</Button>
<Button
class="w-full"
:class="
editor.isActive({ textAlign: 'center' })
? 'bg-white shadow-sm'
: 'bg-transparent'
"
@click="editor.chain().focus().setTextAlign('center').run()"
>
<alignCenter class="w-4" />
</Button>
<Button
class="w-full"
:class="
editor.isActive({ textAlign: 'right' })
? 'bg-white shadow-sm'
: 'bg-transparent'
"
@click="editor.chain().focus().setTextAlign('right').run()"
>
<alignRight class="w-4" />
</Button>
<Button
class="w-full"
:class="
editor.isActive({ textAlign: 'justify' })
? 'bg-white shadow-sm'
: 'bg-transparent'
"
@click="editor.chain().focus().setTextAlign('justify').run()"
>
<alignJustify class="w-4" />
</Button>
</div>
</div>
<span class="font-medium text-gray-600 text-xs my-2">
DECORATIONS
</span>
<div class="w-full flex justify-between gap-x-1.5 mb-6">
<Button
class="w-full"
@click="editor.chain().focus().toggleCodeBlock().run()"
>
<template #prefix>
<Codeblock name="code" class="w-4" />
</template>
Block
</Button>
<Button
class="w-full"
@click="editor.chain().focus().toggleBlockquote().run()"
>
<template #prefix>
<BlockQuote name="quote" class="w-4" />
</template>
Focus
</Button>
</div>
<span class="font-medium text-gray-600 text-xs mt-2 mb-1">
TEXT COLOR
</span>
<ColorInput
class="mt-0.5 mb-1"
:value="editor.getAttributes('textStyle').color"
@change="(value) => editor.chain().focus().setColor(value).run()"
/>
<span class="font-medium text-gray-600 text-xs mt-2 mb-1">
BACKGROUND COLOR
</span>
<ColorInput
class="mt-0.5 mb-6"
:value="editor.getAttributes('textStyle').backgroundColor"
@change="
(value) => editor.chain().focus().toggleHighlight(value).run()
"
/>
<span class="font-medium text-gray-600 text-xs my-2">FONT</span>
<div class="w-full flex justify-between gap-x-1.5">
<Button
class="w-1/3"
:class="[
editor.isActive('textStyle', { fontFamily: 'InterVar' })
? 'outline outline-gray-400'
: '',
]"
@click="editor.chain().focus().setFontFamily('InterVar').run()"
>
Sans
</Button>
<Button
class="w-1/3 font-['Lora']"
:class="[
editor.isActive('textStyle', { fontFamily: 'Lora' })
? 'outline outline-gray-400'
: '',
]"
@click="editor.chain().focus().setFontFamily('Lora').run()"
>
Serif
</Button>
<Button
class="w-1/3"
:style="{ fontFamily: 'Geist Mono' }"
:class="[
editor.isActive('textStyle', { fontFamily: 'Geist Mono' })
? 'outline outline-gray-400'
: '',
]"
@click="editor.chain().focus().setFontFamily('Geist Mono').run()"
>
Mono
</Button>
<Button
class="w-1/3 font-['Nunito']"
:class="[
editor.isActive('textStyle', { fontFamily: 'Nunito' })
? 'outline outline-gray-400'
: '',
]"
@click="editor.chain().focus().setFontFamily('Nunito').run()"
>
Round
</Button>
</div>
</div>
<!-- Insert -->
<div v-if="tab === 1" class="flex flex-col px-5 py-4 border-b">
<span
class="inline-flex items-center gap-2.5 mb-5 text-gray-800 font-medium text-lg w-full"
>
Insert
</span>
<div>
<span class="font-medium text-gray-600 text-base mb-1">Media</span>
<div class="w-full flex justify-between gap-x-1.5 mb-6">
<Button class="w-full justify-start" @click="addImageDialog = true">
<template #prefix>
<Image class="text-gray-700 w-4" />
Image
</template>
</Button>
<Button class="w-full justify-start" @click="addVideoDialog = true">
<template #prefix>
<Video class="text-gray-700 w-4" />
Video
</template>
</Button>
</div>
</div>
<span class="font-medium text-gray-600 text-base mb-1">Break</span>
<div class="w-full flex justify-between gap-x-1.5 mb-6">
<Button
class="w-full px-2"
@click="editor.chain().focus().setHorizontalRule().run()"
>
<template #prefix>
<Minus class="stroke-[1] text-gray-700" />
</template>
Rule
</Button>
<Button
class="px-2 w-full"
@click="editor.chain().focus().setPageBreak().run()"
>
<template #prefix>
<svg
class="w-3.5"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M12 22H17.5C18.0304 22 19.0391 21.7893 19.4142 21.4142C19.7893 21.0391 20 20.5304 20 20V18M4 8V4C4 3.46957 4.21071 2.96086 4.58579 2.58579C4.96086 2.21071 5.46957 2 6 2H14.5L20 7.5V10.5"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M4 4C4 3.46957 4.21071 2.96086 4.58579 2.58579C4.96086 2.21071 5.46957 2 6 2H14.5L20 7.5M4 20C4 20.5304 4.21071 21.0391 4.58579 21.4142C4.96086 21.7893 5.46957 22 6 22H18C18.5304 22 19.0391 21.7893 19.4142 21.4142C19.7893 21.0391 20 20.5304 20 20"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M14 2V8H20"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M3 15H21"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</template>
Page Break
</Button>
</div>
<span class="font-medium text-gray-600 text-base">Table</span>
<div class="flex space-x-2 my-2">
<Button
:disabled="editor.isActive('table')"
class="w-full"
@click="
editor
.chain()
.focus()
.insertTable({ rows: 3, cols: 3, withHeaderRow: false })
.run()
"
>
<template #prefix>
<svg
xmlns="http://www.w3.org/2000/svg"
class="w-4"
width="24"
height="24"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
fill="none"
stroke-linecap="round"
stroke-linejoin="round"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
<path
d="M12.5 21h-7.5a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v7.5"
></path>
<path d="M3 10h18"></path>
<path d="M10 3v18"></path>
<path d="M16 19h6"></path>
<path d="M19 16v6"></path>
</svg>
New Table
</template>
</Button>
</div>
</div>
<!-- Document Settings -->
<div v-if="tab === 2" class="flex flex-col px-3 py-4 border-b">
<span
class="inline-flex items-center gap-2.5 mb-5 text-gray-800 font-medium text-lg w-full px-2"
>
Settings
</span>
<Switch v-model="settings.docSize" label="Small Text" />
<Switch v-model="settings.docSpellcheck" label="Spellcheck" />
<!-- <Switch v-model="settings.docSize" label="Highlight Check" /> -->
<Switch v-model="settings.docWidth" label="Full Width" />
<span class="font-medium text-gray-700 text-base my-2.5 px-2.5">
Default Font
</span>
<div class="w-full flex justify-between gap-1 px-3">
<Button
class="w-1/3"
:class="[
editor.isActive('textStyle', { fontFamily: 'InterVar' })
? 'outline outline-gray-400'
: '',
]"
@click="settings.docFont = 'font-fd-sans'"
>
Sans
</Button>
<Button
class="w-1/3 font-['Lora']"
:class="[
editor.isActive('textStyle', { fontFamily: 'Lora' })
? 'outline outline-gray-400'
: '',
]"
@click="settings.docFont = 'font-fd-serif'"
>
Serif
</Button>
<Button
class="w-1/3"
:style="{ fontFamily: 'Geist Mono' }"
:class="[
editor.isActive('textStyle', { fontFamily: 'Geist Mono' })
? 'outline outline-gray-400'
: '',
]"
@click="settings.docFont = 'font-fd-mono'"
>
Mono
</Button>
<Button
class="w-1/3 font-['Nunito']"
:class="[
editor.isActive('textStyle', { fontFamily: 'Nunito' })
? 'outline outline-gray-400'
: '',
]"
@click="settings.docFont = 'font-fd-round'"
>
Round
</Button>
</div>
</div>
<!-- Transform -->
<div v-if="tab === 3" class="px-5 py-4 border-b">
<span
class="inline-flex items-center gap-2.5 mb-5 text-gray-800 font-medium text-lg w-full"
>
Transform
</span>
<div>
<span
v-if="$route.meta.documentPage && $store.state.hasWriteAccess"
class="font-medium text-gray-700 text-base"
>
Import
</span>
<Button
v-if="$route.meta.documentPage && $store.state.hasWriteAccess"
class="w-full justify-start mb-2"
@click="() => emitter.emit('importDocFromWord')"
>
<template #prefix>
<FileUp class="text-gray-700 w-4 stroke-[1.5]" />
Import DOCX
</template>
</Button>
<span class="font-medium text-gray-700 text-base">Export</span>
<Button
class="w-full justify-start"
@click="() => emitter.emit('exportDocToPDF')"
>
<template #prefix>
<FileDown class="text-gray-700 w-4 stroke-[1.5]" />
Export PDF
</template>
</Button>
<!-- <Button class="w-full justify-start">
<template #prefix>
<FileDown class="text-gray-700 w-4" />
Export to DOCX
</template>
</Button> -->
</div>
</div>
</div>
</div>
<div
class="hidden sm:flex flex-col items-center overflow-hidden h-full min-w-[48px] gap-1 pt-3 px-0 border-l z-0 bg-white"
>
<template v-for="(item, index) in tabs" :key="item.label">
<button
v-if="item.write === $store.state.hasWriteAccess || !item.write"
variant="'ghost'"
:class="[
tab === index && showInfoSidebar
? 'text-black bg-gray-200'
: ' hover:bg-gray-50',
]"
class="h-7 w-7 text-gray-600 rounded"
@click="switchTab(index)"
>
<component
:is="item.icon"
:class="[
tab === 1 && showInfoSidebar ? 'text-gray-700' : 'text-gray-600',
]"
class="mx-auto stroke-[1.5] text-gray-600 w-4 h-4"
/>
</button>
</template>
<!--
Might spawn from emits
so they fall outside of tabs scope
-->
<InsertImage v-model="addImageDialog" :editor="editor" />
<InsertVideo v-model="addVideoDialog" :editor="editor" />
<NewManualSnapshotDialog
v-if="newSnapshotDialog"
v-model="newSnapshotDialog"
@success="
(data) => {
storeSnapshot(data)
}
"
/>
<SnapshotPreviewDialog
v-if="snapShotDialog"
v-model="snapShotDialog"
:snapshot-data="selectedSnapshot"
@success="
(data) => {
applySnapshot(selectedSnapshot)
}
"
/>
</div>
</template>
<script>
import {
FeatherIcon,
Avatar,
Input,
Popover,
Badge,
Dropdown,
Switch,
} from "frappe-ui"
import TagInput from "@/components/TagInput.vue"
import Tag from "@/components/Tag.vue"
import { formatMimeType } from "@/utils/format"
import { getIconUrl } from "@/utils/getIconUrl"
import { v4 as uuidv4 } from "uuid"
import { defineAsyncComponent, markRaw } from "vue"
import OuterCommentVue from "@/components/DocEditor/components/OuterComment.vue"
import LineHeight from "../icons/line-height.vue"
import Info from "@/components/EspressoIcons/Info.vue"
import Comment from "@/components/EspressoIcons/Comment.vue"
import {
Plus,
Minus,
Heading1,
Heading2,
Heading3,
FileUp,
FileDown,
ArrowDownUp,
TextQuote,
MessageCircle,
FileText,
FileClock,
} from "lucide-vue-next"
import { Code } from "lucide-vue-next"
import { Code2 } from "lucide-vue-next"
import { Table2Icon } from "lucide-vue-next"
import "@fontsource/lora"
import "@fontsource/geist-mono"
import "@fontsource/nunito"
import ColorInput from "../components/ColorInput.vue"
import Bold from "../icons/Bold.vue"
import Strikethrough from "../icons/StrikeThrough.vue"
import Underline from "../icons/Underline.vue"
import GeneralAccess from "@/components/GeneralAccess.vue"
import Indent from "../icons/Indent.vue"
import Outdent from "../icons/Outdent.vue"
import Codeblock from "../icons/Codeblock.vue"
import List from "../icons/List.vue"
import OrderList from "../icons/OrderList.vue"
import Check from "../icons/Check.vue"
import Details from "../icons/Details.vue"
import alignRight from "../icons/AlignRight.vue"
import alignLeft from "../icons/AlignLeft.vue"
import alignCenter from "../icons/AlignCenter.vue"
import alignJustify from "../icons/AlignJustify.vue"
import BlockQuote from "../icons/BlockQuote.vue"
import Style from "../icons/Style.vue"
import Image from "../icons/Image.vue"
import Video from "../icons/Video.vue"
import { useTimeAgo } from "@vueuse/core"
import * as Y from "yjs"
import { TiptapTransformer } from "@hocuspocus/transformer"
import { fromUint8Array, toUint8Array } from "js-base64"
import { formatDate } from "../../../utils/format"
import AnnotationList from "../components/AnnotationList.vue"
export default {
name: "DocMenuAndInfoBar",
components: {
Switch,
Input,
FeatherIcon,
Avatar,
TagInput,
Tag,
OuterCommentVue,
Info,
Comment,
Popover,
InsertImage: defineAsyncComponent(() => import("./InsertImage.vue")),
InsertVideo: defineAsyncComponent(() => import("./InsertVideo.vue")),
SnapshotPreviewDialog: defineAsyncComponent(() =>
import("./SnapshotPreviewDialog.vue")
),
NewManualSnapshotDialog: defineAsyncComponent(() =>
import("./NewManualSnapshotDialog.vue")
),
LineHeight,
Plus,
Minus,
Bold,
Strikethrough,
Underline,
List,
Indent,
Outdent,
Code,
Code2,
Codeblock,
Check,
OrderList,
alignLeft,
alignRight,
alignCenter,
alignJustify,
BlockQuote,
Style,
Image,
Video,
Table2Icon,
Badge,
Dropdown,
ColorInput,
Heading1,
Heading2,
Heading3,
FileUp,
FileDown,
ArrowDownUp,
TextQuote,
MessageCircle,
FileText,
Details,
GeneralAccess,
AnnotationList,
},
inject: ["editor", "document"],
emits: ["update:allComments", "update:activeAnnotation"],
inheritAttrs: false,
props: {
settings: {
type: Object,
required: true,
},
allAnnotations: {
type: Object,
required: true,
},
activeAnnotation: {
type: String,
required: false,
},
},
setup() {
return { formatMimeType, getIconUrl }
},
data() {
return {
tab: this.entity?.write ? 0 : 4,
docFont: this.settings.docFont,
tabs: [
{
name: "Typography",
icon: markRaw(Style),
write: true,
},
{
name: "Insert",
icon: markRaw(Plus),
write: true,
},
{
name: "Document Settings",
icon: markRaw(FileText),
write: true,
},
{
name: "Transforms",
icon: markRaw(ArrowDownUp),
write: false,
},
{
name: "Information",
icon: markRaw(Info),
write: false,
},
{
name: "Comments",
icon: markRaw(Comment),
write: false,
},
{
name: "Versions",
icon: markRaw(FileClock),
write: false,
},
],
newComment: "",
showShareDialog: false,
addImageDialog: false,
addVideoDialog: false,
addTag: false,
snapShotDialog: false,
selectedSnapshot: null,
stagedSnapshot: null,
newSnapshotDialog: false,
}
},
computed: {
userId() {
return this.$store.state.auth.user_id
},
fullName() {
return this.$store.state.user.fullName
},
currentUserName() {
return this.$store.state.user.fullName
},
currentUserImage() {
return this.$store.state.user.imageURL
},
entity() {
return this.$store.state.entityInfo[0]
},
unaddedTags() {
return this.$resources.userTags.data.filter(
({ name: id1 }) =>
!this.$resources.entityTags.data.some(({ name: id2 }) => id2 === id1)
)
},
allComments() {
return JSON.parse(this.$store.state.allComments)
},
activeCommentsInstance() {
return JSON.parse(this.$store.state.activeCommentsInstance)
},
showInfoSidebar() {
return this.$store.state.showInfo
},
foregroundColors() {
// tailwind css colors, scale 600
return [
{ name: "Default", hex: "#1F272E" },
{ name: "Yellow", hex: "#ca8a04" },
{ name: "Orange", hex: "#ea580c" },
{ name: "Red", hex: "#dc2626" },
{ name: "Green", hex: "#16a34a" },
{ name: "Blue", hex: "#1579D0" },
{ name: "Purple", hex: "#9333ea" },
{ name: "Pink", hex: "#db2777" },
]
},
backgroundColors() {
// tailwind css colors, scale 100
return [
{ name: "Default", hex: null },
{ name: "Yellow", hex: "#fef9c3" },
{ name: "Orange", hex: "#ffedd5" },
{ name: "Red", hex: "#fee2e2" },
{ name: "Green", hex: "#dcfce7" },
{ name: "Blue", hex: "#D3E9FC" },
{ name: "Purple", hex: "#f3e8ff" },
{ name: "Pink", hex: "#fce7f3" },
]
},
showComments() {
if (this.entity?.owner === "You") {
return true
} else if (this.entity.write) {
return true
} else if (this.entity.allow_comments) {
return true
} else {
return false
}
},
sharedWithList() {
return this.$resources.userList.data?.users.concat(
this.$resources.groupList.data
)
},
formattedMimeType() {
if (this.entity.is_group) return "Folder"
const file = this.entity.file_kind
return file?.charAt(0).toUpperCase() + file?.slice(1)
},
},
mounted() {
this.emitter.on("addImage", () => {
this.addImageDialog = true
})
this.emitter.on("addVideo", () => {
this.addVideoDialog = true
})
// document.vue debouncedWatch
this.emitter.on("triggerAutoSnapshot", () => {
this.autoSnapshot()
})
},
beforeUnmount() {
this.emitter.off("triggerAutoSnapshot")
},
methods: {
setActiveAnnotation(val) {
this.$emit("update:activeAnnotation", val.get("id"))
// focus the comment inside the editor. needs further testing
/* let from = val.rangeStart
let to = val.rangeEnd
//const { node } = this.editor.view.domAtPos(this.editor.state.selection.anchor);
//if (node) {
// Use node.parentElement if domAtPos returns text node instead of a DOM element
// (node.parentElement || node).scrollIntoView({ behavior: 'smooth'})
// scrollIntoView(false); false == dont focus ediotr
//}
//focusCommentWithActiveId(activeCommentId)
//focusContentWithActiveId(activeCommentId) */
},
switchTab(val) {
if (this.$store.state.showInfo == false) {
this.$store.commit("setShowInfo", !this.$store.state.showInfo)
this.tab = val
} else if (this.tab == val) {
this.$store.commit("setShowInfo", !this.$store.state.showInfo)
} else {
this.tab = val
}
},
setComment(val) {
const localVal = val || this.commentText
if (!localVal.trim().length) return
const currentSelectedComment = JSON.parse(
JSON.stringify(this.activeCommentsInstance)
)
const commentsArray =
typeof currentSelectedComment.comments === "string"
? JSON.parse(currentSelectedComment.comments)
: currentSelectedComment.comments
if (commentsArray) {
commentsArray.push({
userName: this.currentUserName,
userImage: this.currentUserImage,
time: Date.now(),
content: localVal,
})
const commentWithUuid = JSON.stringify({
uuid: this.activeCommentsInstance.uuid || uuidv4(),
comments: commentsArray,
})
this.editor.chain().setComment(commentWithUuid).run()
this.commentText = ""
} else {
const commentWithUuid = JSON.stringify({
uuid: uuidv4(),
comments: [
{
userName: this.currentUserName,
userImage: this.currentUserImage,
time: Date.now(),
content: localVal,
},
],
})
this.editor.chain().setComment(commentWithUuid).run()
this.commentText = ""
}
},
focusContent({ from, to }) {
this.editor.chain().setTextSelection({ from, to }).run()
},
toggleSideBar() {
if (this.entity) {
this.$store.commit("setShowInfo", !this.$store.state.showInfo)
}
},
setBackgroundColor(color) {
if (color.name != "Default") {
this.editor.chain().focus().toggleHighlight(color.hex).run()
} else {
this.editor.chain().focus().unsetHighlight().run()
}
},
setForegroundColor(color) {
if (color.name != "Default") {
this.editor.chain().focus().setColor(color.hex).run()
} else {
this.editor.chain().focus().unsetColor().run()
}
},
onButtonClick(button) {
if (typeof button.action === "string") {
this.emitter.emit(button.action)
} else {
button.action(this.editor)
}
},
/*
Imperative that we take the snapshot EXACTLY when the user clicks `New`
document state can change, so the sooner the better
*/
autoSnapshot() {
this.stagedSnapshot = Y.snapshot(this.document)
this.$resources.storeVersion.submit({
entity_name: this.entity.name,
doc_name: this.entity.document,
snapshot_message: `Auto generated version by ${this.currentUserName}`,
snapshot_data: fromUint8Array(Y.encodeSnapshot(this.stagedSnapshot)),
})
},
generateSnapshot() {
this.newSnapshotDialog = true
this.stagedSnapshot = Y.snapshot(this.document)
},
storeSnapshot(message) {
this.$resources.storeVersion.submit({
entity_name: this.entity.name,
doc_name: this.entity.document,
snapshot_message: message,
snapshot_data: fromUint8Array(Y.encodeSnapshot(this.stagedSnapshot)),
})
},
previewSnapshot(index) {
let tempSnapshot = Y.decodeSnapshot(
this.$resources.getversionList.data[index].snapshot_data
)
let tempDoc = Y.createDocFromSnapshot(
this.document,
tempSnapshot,
new Y.Doc({ gc: false })
)
this.selectedSnapshot = Object.assign(
{},
this.$resources.getversionList.data[index]
)
this.selectedSnapshot.snapshot_data = tempDoc
this.snapShotDialog = true
},
applySnapshot(data) {
/* Simply generate the old snapshot state and write the new content */
const snapshotDoc = data.snapshot_data
const prosemirrorJSON = TiptapTransformer.fromYdoc(snapshotDoc).default // default pm fragment
// setContent is a transactional dispatch
// wipes `lastSaved` maybe
this.editor.commands.setContent(prosemirrorJSON, true)
this.$realtime.emit(
"document_version_change_emit",
"Drive Entity",
this.entity.name,
this.currentUserName,
this.currentUserImage,
this.$realtime.socket.id
)
},
revertState(data) {
// DO NOT USE
// find a way to reset the cursor position of all connected clients
const snapshotDoc = new Y.Doc({ gc: false })
Y.applyUpdate(snapshotDoc, Y.encodeStateAsUpdate(data.snapshot_data))
// state vectors
const currentStateVector = Y.encodeStateVector(this.document)
const snapshotStateVector = Y.encodeStateVector(snapshotDoc)
// pack all changes from snapshot till now
const changesSinceSnapshotUpdate = Y.encodeStateAsUpdate(
this.document,
snapshotStateVector
)
// apply them
const um = new Y.UndoManager(snapshotDoc.getXmlFragment("default")) // prosemirror default fragment
Y.applyUpdate(snapshotDoc, changesSinceSnapshotUpdate)
// revert them
um.undo()
// apply the revert operation
const revertChangesSinceSnapshotUpdate = Y.encodeStateAsUpdate(
snapshotDoc,
currentStateVector
)
// propagate changes
Y.applyUpdate(this.document, revertChangesSinceSnapshotUpdate)
},
},
resources: {
storeVersion() {
return {
url: "drive.api.files.create_doc_version",
method: "POST",
debounce: 1000,
auto: false,
onSuccess() {
this.stagedSnapshot = null
this.$resources.getversionList.fetch()
},
}
},
getversionList() {
return {
url: "drive.api.files.get_doc_version_list",
method: "GET",
params: {
entity_name: this.entity.name,
},
auto: this.entity.write === 1 && this.tab === 6,
onSuccess(data) {
data.forEach((element) => {
element.relativeTime = useTimeAgo(element.creation)
element.creation = formatDate(element.creation)
element.snapshot_data = toUint8Array(element.snapshot_data)
})
},
}
},
userList() {
return {
url: "drive.api.permissions.get_shared_with_list",
params: { entity_name: this.entity.name },
auto: this.entity.owner === "You",
}
},
groupList() {
return {
url: "drive.api.permissions.get_shared_user_group_list",
params: { entity_name: this.entity.name },
auto: this.entity.owner === "You",
}
},
generalAccess() {
return {
url: "drive.api.permissions.get_general_access",
params: { entity_name: this.entity.name },
auto: this.entity.owner === "You",
}
},
userTags() {
return {
url: "drive.api.tags.get_user_tags",
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
auto: false,
}
},
entityTags() {
return {
url: "drive.api.tags.get_entity_tags",
params: { entity: this.entity.name },
onError(error) {
if (error.messages) {
console.log(error.messages)
}
},
auto: false,
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/DocMenuAndInfoBar.vue
|
Vue
|
agpl-3.0
| 44,595
|
<template>
<Popover transition="default">
<template #target="{ togglePopover, isOpen }">
<slot
v-bind="{ onClick: () => togglePopover(), isActive: isOpen }"
></slot>
</template>
<template #body-main>
<div class="p-2">
<div class="text-sm text-gray-700">Text Color</div>
<div class="mt-1 grid grid-cols-8 gap-1">
<Tooltip
v-for="color in foregroundColors"
:key="color.name"
class="flex"
:text="color.name"
>
<button
:aria-label="color.name"
class="flex h-5 w-5 items-center justify-center rounded border text-base"
:style="{
color: color.hex,
}"
@click="setForegroundColor(color)"
>
A
</button>
</Tooltip>
</div>
<div class="mt-2 text-sm text-gray-700">Background Color</div>
<div class="mt-1 grid grid-cols-8 gap-1">
<Tooltip
v-for="color in backgroundColors"
:key="color.name"
class="flex"
:text="color.name"
>
<button
:aria-label="color.name"
class="flex h-5 w-5 items-center justify-center rounded border text-base text-gray-900"
:class="!color.hex ? 'border-gray-200' : 'border-transparent'"
:style="{
backgroundColor: color.hex,
}"
@click="setBackgroundColor(color)"
>
A
</button>
</Tooltip>
</div>
</div>
</template>
</Popover>
</template>
<script>
import { Popover, Tooltip } from "frappe-ui"
export default {
name: "FontColor",
components: { Popover, Tooltip },
props: ["editor"],
computed: {
foregroundColors() {
// tailwind css colors, scale 600
return [
{ name: "Default", hex: "#1F272E" },
{ name: "Yellow", hex: "#ca8a04" },
{ name: "Orange", hex: "#ea580c" },
{ name: "Red", hex: "#dc2626" },
{ name: "Green", hex: "#16a34a" },
{ name: "Blue", hex: "#1579D0" },
{ name: "Purple", hex: "#9333ea" },
{ name: "Pink", hex: "#db2777" },
]
},
backgroundColors() {
// tailwind css colors, scale 100
return [
{ name: "Default", hex: null },
{ name: "Yellow", hex: "#fef9c3" },
{ name: "Orange", hex: "#ffedd5" },
{ name: "Red", hex: "#fee2e2" },
{ name: "Green", hex: "#dcfce7" },
{ name: "Blue", hex: "#D3E9FC" },
{ name: "Purple", hex: "#f3e8ff" },
{ name: "Pink", hex: "#fce7f3" },
]
},
},
methods: {
setBackgroundColor(color) {
if (color.name != "Default") {
this.editor.chain().focus().toggleHighlight({ color: color.hex }).run()
} else {
this.editor.chain().focus().unsetHighlight().run()
}
},
setForegroundColor(color) {
if (color.name != "Default") {
this.editor.chain().focus().setColor(color.hex).run()
} else {
this.editor.chain().focus().unsetColor().run()
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/FontColor.vue
|
Vue
|
agpl-3.0
| 3,216
|
<template>
<Dialog v-model="open" :options="{ title: 'Add Image' }" @after-leave="reset">
<template #body-content>
<FileUploader
file-types="image/*"
@success="(file) => (addImageDialog.url = file.file_url)"
>
<template #default="{ file, progress, uploading, openFileSelector }">
<div class="flex items-center space-x-2">
<Button @click="openFileSelector">
{{
uploading
? `Uploading ${progress}%`
: addImageDialog.url
? "Change Image"
: "Upload Image"
}}
</Button>
<Button
v-if="addImageDialog.url"
@click="
() => {
addImageDialog.url = null
addImageDialog.file = null
}
"
>
Remove
</Button>
</div>
</template>
</FileUploader>
<img
v-if="addImageDialog.url"
:src="addImageDialog.url"
class="mt-2 w-full rounded-lg space-x-2"
/>
</template>
<template #actions>
<Button
class="mr-2"
variant="solid"
@click="addImage(addImageDialog.url)"
>
Insert Image
</Button>
<Button @click="reset">Cancel</Button>
</template>
</Dialog>
</template>
<script>
import { Button, Dialog, FileUploader } from "frappe-ui"
export default {
name: "InsertImage",
components: { Button, Dialog, FileUploader },
props: {
modelValue: {
type: Boolean,
required: false,
},
editor: {
type: Object,
required: true,
},
},
data() {
return {
addImageDialog: { url: "", file: null },
}
},
computed: {
open: {
get() {
return this.modelValue
},
set(value) {
this.$emit("update:modelValue", value)
if (!value) {
this.errorMessage = ""
}
},
},
},
methods: {
onImageSelect(e) {
let file = e.target.files[0]
if (!file) {
return
}
this.addImageDialog.file = file
},
addImage(src) {
this.editor
.chain()
.focus()
.setMedia({
src: src,
"media-type": "img",
width: "100%",
height: "auto",
})
.run()
this.reset()
},
reset() {
this.open = false
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/InsertImage.vue
|
Vue
|
agpl-3.0
| 2,499
|
<template>
<slot v-bind="{ onClick: openDialog }"></slot>
<Dialog
v-model="setLinkDialog.show"
:options="{ title: 'Set Link', size: 'sm' }"
@after-leave="reset"
>
<template #body-content>
<!-- <span class="text-sm italic font-medium leading-relaxed text-gray-700">{{ `"${commentRootContent}"` }}</span> -->
<!-- <span class="mt-4 mb-0.5 block text-sm leading-4 text-gray-700">URL</span> -->
<Input
ref="input"
v-model="setLinkDialog.url"
type="text"
class="mt-1"
placeholder="Link"
@keydown.enter="(e) => setLink(e.target.value)"
/>
<Button
variant="solid"
class="w-full mt-6"
@click="setLink(setLinkDialog.url)"
>
Save
</Button>
</template>
</Dialog>
</template>
<script>
import { Dialog, Button, Input } from "frappe-ui"
import { ref } from "vue"
import { useFocus } from "@vueuse/core"
export default {
name: "InsertLink",
components: { Button, Input, Dialog },
props: ["editor"],
setup() {
const input = ref()
const { focused } = useFocus(input, { initialValue: true })
return {
input,
focused,
}
},
data() {
return {
setLinkDialog: { url: "", show: false },
}
},
computed: {
commentRootContent() {
const { view, state } = this.editor
const { from, to } = view.state.selection
return state.doc.textBetween(from, to, "")
},
},
methods: {
openDialog() {
this.emitter.emit("forceHideBubbleMenu", true)
let existingURL = this.editor.getAttributes("link").href
if (existingURL) {
this.setLinkDialog.url = existingURL
}
this.setLinkDialog.show = true
},
setLink(url) {
// empty
if (url === "") {
this.editor.chain().focus().extendMarkRange("link").unsetLink().run()
} else {
// update link
this.editor
.chain()
.focus()
.extendMarkRange("link")
.setLink({ href: url })
.run()
}
this.setLinkDialog.show = false
this.setLinkDialog.url = ""
},
reset() {
this.emitter.emit("forceHideBubbleMenu", false)
this.setLinkDialog = this.$options.data().setLinkDialog
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/InsertLink.vue
|
Vue
|
agpl-3.0
| 2,297
|
<template>
<Dialog v-model="open" :options="{ title: 'Add Video' }" @after-leave="reset">
<template #body-content>
<FileUploader
file-types="video/*"
@success="(file) => (addVideoDialog.url = file.file_url)"
>
<template #default="{ file, progress, uploading, openFileSelector }">
<div class="flex items-center space-x-2">
<Button @click="openFileSelector">
{{
uploading
? `Uploading ${progress}%`
: addVideoDialog.url
? "Change Video"
: "Upload Video"
}}
</Button>
<Button
v-if="addVideoDialog.url"
@click="
() => {
addVideoDialog.url = null
addVideoDialog.file = null
}
"
>
Remove
</Button>
</div>
</template>
</FileUploader>
<video
v-if="addVideoDialog.url"
:src="addVideoDialog.url"
class="mt-2 w-full rounded-lg"
type="video/mp4"
/>
</template>
<template #actions>
<Button
variant="solid"
class="mr-2"
@click="addVideo(addVideoDialog.url)"
>
Insert Video
</Button>
<Button @click="reset">Cancel</Button>
</template>
</Dialog>
</template>
<script>
import { Button, Dialog, FileUploader } from "frappe-ui"
export default {
name: "InsertImage",
components: { Button, Dialog, FileUploader },
props: {
modelValue: {
type: Boolean,
required: false,
},
editor: {
type: Object,
required: true,
},
},
data() {
return {
addVideoDialog: { url: "", file: null },
}
},
computed: {
open: {
get() {
return this.modelValue
},
set(value) {
this.$emit("update:modelValue", value)
if (!value) {
this.errorMessage = ""
}
},
},
},
methods: {
onVideoSelect(e) {
let file = e.target.files[0]
if (!file) {
return
}
this.addVideoDialog.file = file
},
addVideo(src) {
this.editor
.chain()
.focus()
.setMedia({
src: src,
"media-type": "video",
width: "100%",
height: "auto",
})
.run()
this.reset()
},
reset() {
this.open = false
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/InsertVideo.vue
|
Vue
|
agpl-3.0
| 2,517
|
<template>
<div>
<div
v-if="items.length"
class="min-w-40 rounded-lg border bg-white p-1.5 text-base shadow-lg"
>
<button
v-for="(item, index) in items"
:key="index"
:class="[
index === selectedIndex ? 'bg-gray-100' : 'text-gray-900',
'flex w-full items-center whitespace-nowrap rounded p-1 text-sm',
]"
@click="selectItem(index)"
@mouseover="selectedIndex = index"
>
<Avatar
size="sm"
class="mr-1"
:label="item.label"
:image="item.user_image"
/>
{{ item.label }}
</button>
</div>
</div>
</template>
<script>
import { Avatar } from "frappe-ui"
export default {
props: {
items: {
type: Array,
required: true,
},
command: {
type: Function,
required: true,
},
},
components: {
Avatar,
},
data() {
return {
selectedIndex: 0,
}
},
computed: {
currentUserName() {
return this.$store.state.auth.user_id
},
},
watch: {
items() {
this.selectedIndex = 0
},
},
methods: {
onKeyDown({ event }) {
if (event.key === "ArrowUp") {
this.upHandler()
return true
}
if (event.key === "ArrowDown") {
this.downHandler()
return true
}
if (event.key === "Enter") {
this.enterHandler()
return true
}
return false
},
upHandler() {
this.selectedIndex =
(this.selectedIndex + this.items.length - 1) % this.items.length
},
downHandler() {
this.selectedIndex = (this.selectedIndex + 1) % this.items.length
},
enterHandler() {
this.selectItem(this.selectedIndex)
},
selectItem(index) {
const item = this.items[index]
if (item) {
this.command({
id: item.value,
label: item.label,
author: this.currentUserName,
type: item.type,
})
}
},
},
}
</script>
<style>
.item {
display: block;
margin: 0;
width: 100%;
text-align: left;
background: transparent;
border-radius: 0.4rem;
border: 1px solid transparent;
padding: 0.2rem 0.4rem;
}
.item.is-selected {
border-color: #000;
}
</style>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/MentionList.vue
|
Vue
|
agpl-3.0
| 2,286
|
<template>
<div
class="flex items-center justify-center bg-white w-full shadow-lg rounded-[0.45rem] gap-1 px-0.5 py-0.5"
>
<template v-for="button in buttons" :key="button.label">
<div v-if="button.type === 'separator'" class="h-5 border-l"></div>
<div v-else-if="button.map" class="shrink-0">
<Popover>
<template #target="{ togglePopover }">
<button
class="rounded text-base font-medium text-gray-800 transition-colors hover:bg-gray-100"
:set="
(activeBtn =
button.find((b) => b.isActive(editor)) || button[0])
"
@click="togglePopover"
>
<component
:is="activeBtn.icon"
v-if="activeBtn.icon"
class="h-4 w-4"
/>
<span v-else>
{{ activeBtn.label }}
</span>
</button>
</template>
<template #body="{ close }">
<ul class="rounded border bg-white p-1 shadow-md">
<li
v-for="option in button"
v-show="option.isDisabled ? !option.isDisabled(editor) : true"
:key="option.label"
class="w-full"
>
<button
class="w-full rounded px-2 py-1 text-left text-base hover:bg-gray-50"
@click="
() => {
onButtonClick(option)
close()
}
"
>
{{ option.label }}
</button>
</li>
</ul>
</template>
</Popover>
</div>
<component :is="button.component || 'div'" v-else v-bind="{ editor }">
<template #default="componentSlotProps">
<button
class="flex items-center rounded-[0.35rem] p-1 text-gray-800 transition-colors gap-1"
:class="
button.isActive(editor) || componentSlotProps?.isActive
? 'bg-gray-200 text-gray-400'
: 'hover:bg-gray-100'
"
:title="button.label"
@click="
componentSlotProps?.onClick
? componentSlotProps.onClick(button)
: onButtonClick(button)
"
>
<component
:is="button.icon"
v-if="button.icon"
class="h-4 w-auto stroke-[1.5]"
/>
<span
v-else
class="inline-block h-4 min-w-[1rem] text-sm leading-4"
>
{{ button.text }}
</span>
</button>
</template>
</component>
</template>
</div>
</template>
<script>
import { Popover, FeatherIcon } from "frappe-ui"
export default {
name: "TipTapMenu",
components: {
Popover,
FeatherIcon,
},
inject: ["editor"],
props: ["buttons"],
emits: ["toggleCommentMode"],
methods: {
onButtonClick(button) {
if (typeof button.action === "string") {
this.emitter.emit(button.action)
} else {
button.action(this.editor)
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/Menu.vue
|
Vue
|
agpl-3.0
| 3,259
|
<template>
<div class="flex px-3 bg-white pb-2 shadow-sm">
<Dropdown :options="fileMenuOptions">
<template #default="{ open }">
<button
:class="[
'rounded-md px-2 py-1 text-base font-medium',
open ? 'bg-slate-100' : 'bg-white-200',
]"
>
File
</button>
</template>
</Dropdown>
<Dropdown
:options="[
{
group: 'New',
hideLabel: true,
items: [
{
label: 'Undo',
handler: () => alert('New File'),
},
{
label: 'Redo',
handler: () => alert('New Window'),
// show/hide option based on condition function
condition: () => true,
},
{
label: 'Cut',
handler: () => alert('New File'),
},
{
label: 'Copy',
handler: () => alert('New Window'),
// show/hide option based on condition function
condition: () => true,
},
{
label: 'Paste',
handler: () => alert('New File'),
},
{
label: 'Paste without Formatting',
handler: () => alert('New Window'),
// show/hide option based on condition function
condition: () => true,
},
{
label: 'Select All',
handler: () => alert('New File'),
},
{
label: 'Find and Replace',
handler: () => alert('New Window'),
// show/hide option based on condition function
condition: () => true,
},
],
},
]"
>
<template #default="{ open }">
<button
:class="[
'rounded-md px-2 py-1 text-base font-medium',
open ? 'bg-slate-100' : 'bg-white-200',
]"
>
Edit
</button>
</template>
</Dropdown>
<Dropdown
:options="[
{
group: 'New',
hideLabel: true,
items: [
{
label: 'Mode',
handler: () => alert('New File'),
},
{
label: 'Text Width',
handler: () => alert('New Window'),
// show/hide option based on condition function
condition: () => true,
},
{
label: 'Focus Mode',
handler: () => alert('New Window'),
// show/hide option based on condition function
condition: () => true,
},
{
label: 'Full screen',
handler: () => alert('New Window'),
// show/hide option based on condition function
condition: () => true,
},
],
},
]"
>
<template #default="{ open }">
<button
:class="[
'rounded-md px-2 py-1 text-base font-medium',
open ? 'bg-slate-100' : 'bg-white-200',
]"
>
View
</button>
</template>
</Dropdown>
<Dropdown
:options="[
{
group: 'Insert',
hideLabel: true,
items: [
{
label: 'Image',
handler: () => alert('New File'),
},
{
label: 'Video',
handler: () => alert('New File'),
},
{
label: 'Table',
handler: () => alert('New File'),
},
{
label: 'Link',
handler: () => alert('New File'),
},
{
label: 'Horizontal Line',
handler: () => alert('New File'),
},
{
label: 'Emoji',
handler: () => alert('New File'),
},
{
label: 'Blockquote',
handler: () => alert('New File'),
},
],
},
]"
>
<template #default="{ open }">
<button
:class="[
'rounded-md px-2 py-1 text-base font-medium',
open ? 'bg-slate-100' : 'bg-white-200',
]"
>
Insert
</button>
</template>
</Dropdown>
<Dropdown
:options="[
{
group: 'New',
hideLabel: true,
items: [
{
label: 'Text',
handler: () => alert('New File'),
},
{
label: 'Style',
handler: () => alert('New File'),
},
{
label: 'Alignment',
handler: () => alert('New File'),
},
{
label: 'Line Height',
handler: () => alert('New File'),
},
{
label: 'Horizontal Line',
handler: () => alert('New File'),
},
{
label: 'List and Numbering',
handler: () => alert('New File'),
},
{
label: 'Table',
handler: () => alert('New File'),
},
],
},
]"
>
<template #default="{ open }">
<button
:class="[
'rounded-md px-2 py-1 text-base font-medium',
open ? 'bg-slate-100' : 'bg-white-200',
]"
>
Format
</button>
</template>
</Dropdown>
<!-- <div class="ml-auto">
<Dropdown :options="modeMenuOptions">
<template v-slot="{ open }">
<Button :icon-left="modeButtonIcon" :label="modeButtonText" />
</template>
</Dropdown>
</div> -->
<ShareDialog
v-if="showShareDialog"
v-model="showShareDialog"
:entity-name="entityName"
/>
<!-- Ideally convert the component to recieve both an array or a single entity -->
<GeneralDialog
v-model="showRemoveDialog"
:entities="entityName"
:for="'remove'"
@success="
() => {
$router.go(-1)
}
"
/>
</div>
</template>
<script>
import { Dropdown } from "frappe-ui"
import ShareDialog from "@/components/ShareDialog.vue"
import GeneralDialog from "@/components/GeneralDialog.vue"
export default {
name: "MenuBar",
components: {
Dropdown,
ShareDialog,
GeneralDialog,
},
props: {
entityName: {
default: "",
type: String,
required: false,
},
editable: {
type: Boolean,
required: false,
},
isCommentModeOn: {
type: Boolean,
required: false,
},
isReadOnly: {
type: Boolean,
required: false,
},
},
emits: ["toggleCommentMode", "toggleEditMode", "toggleReadMode"],
data() {
return {
showShareDialog: false,
showRemoveDialog: false,
modeButtonIcon: "",
fileMenuOptions: [
/* {
group: "New",
hideLabel: true,
items: [
{
icon: "file-plus",
label: "New File",
handler: () => this.emitter.emit("createNewDocument"),
},
],
}, */
{
group: "Current File",
hideLabel: true,
items: [
/* Look into making a modal/dialog/portal for this and opening a file from the current file view*/
/* {
icon: "copy",
label: "Copy File",
handler: () =>
this.$store.commit("setPasteData", {
entities: this.entityName,
action: "copy",
}),
}, */
{
icon: "share-2",
label: "Share File",
handler: () => (this.showShareDialog = true),
},
{
icon: "star",
label: "Add to favourites",
handler: () => alert("Open File"),
},
],
},
{
group: "Delete",
hideLabel: true,
items: [
{
icon: "trash-2",
label: "Delete File",
handler: () => (this.showRemoveDialog = true),
},
],
},
],
modeMenuOptions: [
{
group: "Mode",
hideLabel: true,
items: [
{
icon: "eye",
label: "Reading",
handler: () => {
this.emitter.emit("toggleReadMode")
},
},
{
icon: "edit-3",
label: "Editing",
handler: () => {
this.emitter.emit("toggleEditMode")
},
},
{
icon: "message-square",
label: "Suggesting",
handler: () => {
this.emitter.emit("toggleCommentMode")
},
},
],
},
],
}
},
computed: {
modeButtonText() {
if (this.editable) {
this.modeButtonIcon = "edit-3"
return "Editing"
} else if (this.isReadOnly) {
this.modeButtonIcon = "eye"
return "Reading"
} else if (this.isCommentModeOn) {
this.modeButtonIcon = "message-square"
return "Suggesting"
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/MenuBar.vue
|
Vue
|
agpl-3.0
| 9,565
|
<template>
<div>
<slot v-bind="{ onClick: openDialog }"></slot>
<Dialog
v-model="showNewCommentDialog"
:options="{ title: 'New Annotation', size: 'sm' }"
@after-leave="reset"
>
<template #body-content>
<!-- <span class="text-sm italic font-medium leading-relaxed text-gray-700">{{ `"${commentRootContent}"` }}</span> -->
<!-- <span class="text-sm prose prose-xs overflow-auto" v-html="commentRootContent"></span> -->
<!-- <span class="mt-4 mb-0.5 block text-sm leading-4 text-gray-700">Comment</span> -->
<TiptapInput
v-model="commentText"
class="border border-gray-300"
:show-inline-button="false"
@keyup.ctrl.enter="setComment(commentText)"
/>
<Button
variant="solid"
class="w-full mt-6"
@click="setComment(commentText)"
>
Post
</Button>
</template>
<!-- //https://github.com/ueberdosis/tiptap/issues/369 -->
</Dialog>
</div>
</template>
<script>
import { Dialog, Button } from "frappe-ui"
import { ref } from "vue"
import { useFocus } from "@vueuse/core"
import { v4 as uuidv4 } from "uuid"
import { DOMSerializer } from "prosemirror-model"
import * as Y from "yjs"
import TiptapInput from "@/components/TiptapInput.vue"
export default {
name: "NewComment",
components: { Button, Dialog, TiptapInput },
inject: ["editor", "document"],
setup() {
const input = ref(null)
const { focused } = useFocus(input, { initialValue: true })
return {
input,
focused,
}
},
data() {
return {
commentText: "",
showNewCommentDialog: false,
activeCommentsInstance: {
uuid: "",
comments: [],
},
}
},
computed: {
currentUserName() {
return this.$store.state.user.fullName
},
currentUserImage() {
return this.$store.state.user.imageURL
},
currentUserEmail() {
return this.$store.state.auth.user_id
},
commentRootContent() {
const { view, state } = this.editor
const { from, to } = view.state.selection
return this.getHTMLContentBetween(this.editor, from, to)
return state.doc.textBetween(from, to, "")
},
},
computed: {
currentUserName() {
return this.$store.state.user.fullName
},
currentUserImage() {
return this.$store.state.user.imageURL
},
commentRootContent() {
const { view, state } = this.editor
const { from, to } = view.state.selection
return this.getHTMLContentBetween(this.editor, from, to)
return state.doc.textBetween(from, to, "")
},
},
methods: {
openDialog() {
this.emitter.emit("forceHideBubbleMenu", true)
this.showNewCommentDialog = true
},
getHTMLContentBetween(editor, from, to) {
const { state } = editor
const nodesArray = []
state.doc.nodesBetween(from, to, (node, pos, parent) => {
if (parent === state.doc) {
const serializer = DOMSerializer.fromSchema(editor.schema)
const dom = serializer.serializeNode(node)
const tempDiv = document.createElement("div")
tempDiv.appendChild(dom)
nodesArray.push(tempDiv.innerHTML)
}
})
return nodesArray.join("")
},
setComment(val) {
// Trim trailing whitespace
let { from, to } = this.editor.view.state.selection
const textContent = this.editor.view.state.doc.textBetween(from, to)
const trimmedEnd = textContent.length - textContent.trim().length
to = to - trimmedEnd
this.editor.commands.setTextSelection({ from, to })
const newID = uuidv4()
const newCommentRepliesYarray = new Y.Array()
const newCommentYmap = new Y.Map()
newCommentYmap.set("id", newID)
newCommentYmap.set("content", val)
newCommentYmap.set("anchor", 1)
newCommentYmap.set("resolved", 0)
//newCommentYmap.set('synced', 1)
newCommentYmap.set("owner", this.currentUserName)
newCommentYmap.set("ownerEmail", this.$store.state.auth.user_id)
newCommentYmap.set("ownerImage", this.currentUserImage)
newCommentYmap.set("replies", newCommentRepliesYarray)
newCommentYmap.set("createdAt", Date.now())
newCommentYmap.set("rangeStart", from)
newCommentYmap.set("rangeEnd", to)
const yarray = this.document.getArray("docAnnotations")
yarray.push([newCommentYmap])
this.editor.chain().setAnnotation(newID).run()
/* let newComment = {
id: uuidv4(),
content: val,
anchor: 1,
resolved: 0,
synced: 1,
owner: this.currentUserName,
ownerEmail: this.currentUserEmail,
replies: [],
createdAt: Date.now(),
rangeStart: from,
rangeEnd: to,
} */
this.commentText = ""
this.showNewCommentDialog = false
this.$emit("success")
/* // Get all marks in this selection
let activeCommentsInSelection = []
this.editor.state.doc.nodesBetween(from, to, (node) => {
const mark = node.marks.find((mark) => mark.type.name === 'comment');
if (mark) {
activeCommentsInSelection.push(mark);
}
});
let id1 = activeCommentsInSelection[0].attrs.commentId
let id2 = activeCommentsInSelection[1].attrs.commentId
id1 = activeCommentsInSelection[1].attrs.commentId
console.log(activeCommentsInSelection[0].attrs.commentId) */
/* const isCommentActive = activeMarks.some(mark => mark.type.name === 'comment');
if (isCommentActive) {
// Find the first active 'comment' mark
const firstCommentMark = activeMarks.find(mark => mark.type.name === 'comment');
// Get the attributes of the 'comment' mark
const firstCommentAttrs = firstCommentMark.attrs;
console.log('The first active comment mark here is:', firstCommentMark)
console.log('The first active comment markAttrs here is:', firstCommentAttrs)
} else {
console.log('Not Active.');
} */
},
discardComment() {
this.activeCommentsInstance = {}
this.commentText = ""
},
reset() {
this.emitter.emit("forceHideBubbleMenu", false)
this.showNewCommentDialog = this.$options.data().showNewCommentDialog
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/NewAnnotation.vue
|
Vue
|
agpl-3.0
| 6,466
|
<template>
<slot v-bind="{ onClick: openDialog }"></slot>
<Dialog
v-model="showNewCommentDialog"
:options="{ title: 'New Comment', size: 'sm' }"
@after-leave="reset"
>
<template #body-content>
<!-- <span class="text-sm italic font-medium leading-relaxed text-gray-700">{{ `"${commentRootContent}"` }}</span> -->
<!-- <span class="text-sm prose prose-xs overflow-auto" v-html="commentRootContent"></span> -->
<!-- <span class="mt-4 mb-0.5 block text-sm leading-4 text-gray-700">Comment</span> -->
<textarea
ref="input"
v-model="commentText"
class="resize-none w-full form-input mt-1 min-h-6 max-h-[50vh] text-sm"
type="text"
placeholder="Comment"
@keydown.enter="(e) => setComment(e.target.value)"
/>
<Button
variant="solid"
class="w-full mt-6"
@click="setComment(commentText)"
>
Save
</Button>
</template>
<!-- //https://github.com/ueberdosis/tiptap/issues/369 -->
</Dialog>
</template>
<script>
import { Dialog, Button, Input } from "frappe-ui"
import { ref, inject } from "vue"
import { useFocus, useTextareaAutosize } from "@vueuse/core"
import { v4 as uuidv4 } from "uuid"
import { DOMSerializer } from "prosemirror-model"
export default {
name: "NewComment",
components: { Button, Input, Dialog },
props: ["editor"],
setup() {
const input = ref(null)
const { focused } = useFocus(input, { initialValue: true })
return {
input,
focused,
}
},
data() {
return {
commentText: "",
showNewCommentDialog: false,
activeCommentsInstance: {
uuid: "",
comments: [],
},
}
},
computed: {
currentUserName() {
return this.$store.state.user.fullName
},
currentUserImage() {
return this.$store.state.user.imageURL
},
commentRootContent() {
const { view, state } = this.editor
const { from, to } = view.state.selection
return this.getHTMLContentBetween(this.editor, from, to)
return state.doc.textBetween(from, to, "")
},
},
watch: {
commentText: function () {
this.$refs.input.style.height = "2rem"
this.$nextTick(() => {
this.$refs.input.style.height = this.$refs.input.scrollHeight + "px"
})
},
},
methods: {
openDialog() {
this.emitter.emit("forceHideBubbleMenu", true)
this.showNewCommentDialog = true
},
getHTMLContentBetween(editor, from, to) {
const { state } = editor
const nodesArray = []
state.doc.nodesBetween(from, to, (node, pos, parent) => {
if (parent === state.doc) {
const serializer = DOMSerializer.fromSchema(editor.schema)
const dom = serializer.serializeNode(node)
const tempDiv = document.createElement("div")
tempDiv.appendChild(dom)
nodesArray.push(tempDiv.innerHTML)
}
})
return nodesArray.join("")
},
setComment(val) {
const localVal = val || this.commentText
const commentWithUuid = JSON.stringify({
uuid: uuidv4(),
comments: [
{
userName: this.currentUserName,
userImage: this.currentUserImage,
time: Date.now(),
content: localVal,
},
],
})
this.editor.chain().setComment(commentWithUuid).run()
this.commentText = ""
this.showNewCommentDialog = false
this.$emit("success")
},
discardComment() {
this.activeCommentsInstance = {}
this.commentText = ""
},
reset() {
this.emitter.emit("forceHideBubbleMenu", false)
this.showNewCommentDialog = this.$options.data().showNewCommentDialog
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/NewComment.vue
|
Vue
|
agpl-3.0
| 3,780
|
<template>
<Dialog v-model="open" :options="{ title: 'New Version', size: 'sm' }">
<template #body-content>
<Input v-model="snapshotMessage" label="Message" />
</template>
<template #actions>
<Button :variant="'solid'" class="w-full" @click="save">Create</Button>
</template>
</Dialog>
</template>
<script setup>
import { ref, computed, defineEmits, defineProps, onBeforeUnmount } from "vue"
import { Dialog, Button, Input } from "frappe-ui"
defineOptions({
inheritAttrs: false,
})
const snapshotMessage = ref("")
const props = defineProps({
modelValue: {
type: Boolean,
required: true,
},
})
const emit = defineEmits(["update:modelValue", "success"])
const open = computed({
get: () => props.modelValue,
set: (value) => emit("update:modelValue", value),
})
const save = () => {
emit("success", snapshotMessage.value)
emit("update:modelValue", false)
}
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/NewManualSnapshotDialog.vue
|
Vue
|
agpl-3.0
| 922
|
<template>
<section class="text-sm w-full flex flex-col overflow-x-hidden min-w-full">
<article
v-for="(comment, i) in allComments"
:key="i + ''"
class="current-comment pt-2 bg-white flex flex-col border-b last:border-b-0"
:class="[
`${
comment.jsonComments.uuid === activeCommentsInstance.uuid
? 'active'
: 'cursor-pointer'
}`,
]"
@click.stop.prevent="focusContent({ from: comment.from, to: comment.to })"
>
<div
v-for="(jsonComment, j) in comment.jsonComments.comments"
:key="`${j}_${Math.random()}`"
class="flex items-start justify-start my-5"
>
<Avatar
:label="jsonComment.userName"
:image="jsonComment.userImage"
class="h-7 w-7"
/>
<div class="ml-3">
<div class="flex items-center justify-start text-base gap-x-1">
<span class="font-medium">
{{ jsonComment.userName }}
</span>
<span class="text-gray-500">{{ " ∙ " }}</span>
<span class="text-gray-600">
{{ formatDate(jsonComment.time) }}
</span>
</div>
<span class="my-2 text-base text-gray-700 break-word leading-snug">{{
jsonComment.content
}}</span>
</div>
</div>
<section
v-show="comment.jsonComments.uuid == activeCommentsInstance.uuid"
class="flex flex-col"
:class="[
`${
comment.jsonComments.uuid === activeCommentsInstance.uuid
? ''
: 'max-h-0'
}`,
]"
>
<div class="flex items-center gap-1 mt-2 mb-4">
<Avatar :label="fullName" :image="imageURL" class="h-7 w-7 mr-1" />
<div
class="flex items-center mx-auto border w-full bg-transparent rounded max-w-[87%] focus-within:ring-2 ring-gray-400 hover:bg-gray-100 focus-within:bg-gray-100 group"
>
<textarea
v-model="commentText"
class="w-full form-textarea bg-transparent resize-none border-none hover:bg-transparent focus:ring-0 focus:shadow-none focus:bg-transparent"
placeholder="Add comment"
@input="resize($event)"
@keypress.enter.stop.prevent="setComment"
/>
<Button
class="hover:bg-transparent"
variant="ghost"
icon="arrow-up-circle"
:disabled="!commentText.length"
@click="setComment"
></Button>
</div>
</div>
</section>
</article>
</section>
</template>
<script setup lang="ts">
import { useStore } from "vuex"
import { ref, watch, computed, nextTick, onUpdated } from "vue"
import { Avatar, Button, Input } from "frappe-ui"
import { formatDate } from "@/utils/format"
const store = useStore()
const emit = defineEmits(["setComment"])
interface Props {
allComments: any[]
activeCommentsInstance: {
uuid: ""
comments: []
}
isCommentModeOn: boolean
focusContent: ({ from, to }: { from: number; to: number }) => void
}
const props = defineProps<Props>()
const commentText = ref<string>("")
const textarea = ref<Record<string, any>>({})
const activeCommentInstanceUuid = computed(
() => props.activeCommentsInstance.uuid
)
const fullName = computed(() => store.state.user.fullName)
const imageURL = computed(() => store.state.user.imageURL)
const setComment = () => {
emit("setComment", commentText.value)
commentText.value = ""
}
watch(activeCommentInstanceUuid, (val) => {
setTimeout(() => {
if (!val || !props.isCommentModeOn) return
commentText.value = ""
const activeTextArea: HTMLTextAreaElement = textarea.value[val]
//if (activeTextArea) activeTextArea.focus()
}, 100)
})
function resize(e) {
e.target.style.height = `${e.target.scrollHeight}px`
}
/* watch(commentText, (val) => {
nextTick(() => {
console.log(textarea.value.style)
//textarea.value.style.height = textarea.value.style.scrollHeight + 'px';
})
}) */
</script>
<style lang="scss" scoped>
.current-comment {
transition: all 2s cubic-bezier(0.165, 0.84, 0.44, 1);
&.active {
padding: 10px 0px;
}
}
</style>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/OuterComment.vue
|
Vue
|
agpl-3.0
| 4,292
|
<script setup lang="ts">
import { Editor, Node, NodeViewWrapper } from "@tiptap/vue-3"
import { ref, onMounted, computed, watch } from "vue"
import { Node as ProseMirrorNode } from "prosemirror-model"
import { Decoration } from "prosemirror-view"
import { resizableMediaActions } from "../extensions/resizenode/resizableMediaMenuUtil"
import "tippy.js/animations/shift-away.css"
import AlignItemLeft from "../icons/align-item-left.vue"
import AlignItemRight from "../icons/align-item-right.vue"
import AlignItemCenter from "../icons/align-item-center.vue"
import FloatItemLeft from "../icons/float-item-left.vue"
import FloatItemRight from "../icons/float-item-right.vue"
interface Props {
editor: Editor
node: ProseMirrorNode
decorations: Decoration
selected: boolean
extension: Node<any, any>
getPos: () => number
updateAttributes: (attributes: Record<string, any>) => void
deleteNode: () => void
}
const props = defineProps<Props>()
const mediaType = computed<"img" | "video">(
() => props.node.attrs["media-type"]
)
const resizableImg = ref<HTMLImageElement | HTMLVideoElement | null>(null) // template ref
const aspectRatio = ref(0)
const proseMirrorContainerWidth = ref(0)
const mediaActionActiveState = ref<Record<string, boolean>>({})
const showActionMenu = ref(true)
const setMediaActionActiveStates = () => {
const activeStates: Record<string, boolean> = {}
for (const { tooltip, isActive } of resizableMediaActions)
activeStates[tooltip] = !!isActive?.(props.node.attrs)
mediaActionActiveState.value = activeStates
}
watch(
() => props.node.attrs,
() => setMediaActionActiveStates(),
{ deep: true }
)
const mediaSetupOnLoad = () => {
// ! TODO: move this to extension storage
const proseMirrorContainerDiv = document.querySelector(".ProseMirror")
if (proseMirrorContainerDiv)
proseMirrorContainerWidth.value = proseMirrorContainerDiv?.clientWidth
// When the media has loaded
if (!resizableImg.value) return
aspectRatio.value =
(resizableImg.value as HTMLVideoElement).videoWidth /
(resizableImg.value as HTMLVideoElement).videoHeight
}
onMounted(() => mediaSetupOnLoad())
const isHorizontalResizeActive = ref(false)
const activeDragHandle = ref("left")
const lastCursorX = ref(-1)
interface WidthAndHeight {
width: number
height: number
}
const limitWidthOrHeightToFiftyPixels = ({ width, height }: WidthAndHeight) =>
width < 250 || height < 250
const startHorizontalResize = (e: MouseEvent, dragHandle: string) => {
activeDragHandle.value = dragHandle
isHorizontalResizeActive.value = true
lastCursorX.value = e.clientX
document.addEventListener("mousemove", onHorizontalMouseMove)
document.addEventListener("mouseup", stopHorizontalResize)
}
const stopHorizontalResize = () => {
isHorizontalResizeActive.value = false
lastCursorX.value = -1
showActionMenu.value = false
document.removeEventListener("mousemove", onHorizontalMouseMove)
document.removeEventListener("mouseup", stopHorizontalResize)
}
const onHorizontalResize = (
directionOfMouseMove: "right" | "left",
diff: number
) => {
if (!resizableImg.value) {
console.error("Media ref is undefined|null", {
resizableImg: resizableImg.value,
})
return
}
const currentMediaDimensions = {
width: resizableImg.value?.width,
height: resizableImg.value?.height,
}
const newMediaDimensions = {
width: -1,
height: -1,
}
if (directionOfMouseMove === "left") {
newMediaDimensions.width = currentMediaDimensions.width - Math.abs(diff)
} else {
newMediaDimensions.width = currentMediaDimensions.width + Math.abs(diff)
}
//if (newMediaDimensions.width > proseMirrorContainerWidth.value)
// newMediaDimensions.width = proseMirrorContainerWidth.value;
newMediaDimensions.height = newMediaDimensions.width / aspectRatio.value
if (limitWidthOrHeightToFiftyPixels(newMediaDimensions)) return
props.updateAttributes(newMediaDimensions)
}
const onHorizontalMouseMove = (e: MouseEvent) => {
if (!isHorizontalResizeActive.value) return
const { clientX } = e
const diff = lastCursorX.value - clientX
lastCursorX.value = clientX
if (diff === 0) return
let directionOfMouseMove: "left" | "right"
if (activeDragHandle.value === "left") {
directionOfMouseMove = diff > 0 ? "right" : "left"
} else if (activeDragHandle.value === "right") {
directionOfMouseMove = diff > 0 ? "left" : "right"
}
onHorizontalResize(directionOfMouseMove, Math.abs(diff))
}
const lastCursorY = ref(-1)
const floatClass = computed(() => {
switch (props.node.attrs.dataFloat) {
case "left":
return "float-left mr-4"
case "right":
return "float-right ml-4"
default:
return ""
}
})
const alignClass = computed(() => {
switch (props.node.attrs.dataAlign) {
case "left":
return "justify-start"
case "center":
return "justify-center"
case "right":
return "justify-end"
default:
return "justify-end"
}
})
</script>
<template>
<node-view-wrapper
as="div"
class="group relative flex not-prose"
:class="props.node.attrs.dataAlign ? alignClass : floatClass"
>
<div
class="relative flex items-center group"
v-if="props.editor.options.editable"
draggable="true"
data-drag-handle
>
<div
class="transition-opacity duration-100 ease-in-out opacity-0 group-hover:opacity-100 absolute -top-10 right-0 bg-white border flex items-center justify-center shadow-lg rounded-[0.55rem] gap-x-1 p-0.5"
>
<button
class="rounded p-1"
:class="
props.node.attrs.dataAlign === 'left'
? 'bg-gray-200 text-gray-600'
: ''
"
:variant="'ghost'"
@click="
props.updateAttributes({
dataAlign: 'left',
dataFloat: null,
})
"
>
<AlignItemLeft class="rounded-none w-4 h-auto" />
</button>
<button
class="rounded p-1"
:class="
props.node.attrs.dataAlign === 'center'
? 'bg-gray-200 text-gray-600'
: ''
"
:variant="'ghost'"
@click="
props.updateAttributes({
dataAlign: 'center',
dataFloat: null,
})
"
>
<AlignItemCenter class="rounded-none w-4 h-auto" />
</button>
<button
class="rounded p-1"
:class="
props.node.attrs.dataAlign === 'right'
? 'bg-gray-200 text-gray-600'
: ''
"
:variant="'ghost'"
@click="
props.updateAttributes({
dataAlign: 'right',
dataFloat: null,
})
"
>
<AlignItemRight class="w-4 h-auto" />
</button>
<button
class="rounded p-1"
:class="
props.node.attrs.dataFloat === 'left'
? 'bg-gray-200 text-gray-600'
: ''
"
:variant="'ghost'"
@click="
props.updateAttributes({
dataAlign: null,
dataFloat: 'left',
})
"
>
<FloatItemLeft class="w-4 h-auto" />
</button>
<button
class="rounded p-1"
:class="
props.node.attrs.dataFloat === 'right'
? 'bg-gray-200 text-gray-600'
: ''
"
:variant="'ghost'"
@click="
props.updateAttributes({
dataAlign: null,
dataFloat: 'right',
})
"
>
<FloatItemRight class="w-4 h-auto" />
</button>
</div>
<!-- Left Handle -->
<div
class="z-10 absolute left-0 flex items-center justify-center w-5 h-full bg-transparent cursor-ew-resize"
@mousedown.lazy.prevent="startHorizontalResize($event, 'left')"
@mouseup.lazy.prevent="stopHorizontalResize"
>
<div
class="transition-opacity duration-100 ease-in-out opacity-0 group-hover:opacity-100 absolute w-2 bg-white bg-opacity-80 rounded h-[55px] shadow-xl"
/>
</div>
<img
v-if="mediaType === 'img'"
v-bind="node.attrs"
loading="lazy"
ref="resizableImg"
class="rounded"
draggable="false"
/>
<video
v-else-if="mediaType === 'video'"
v-bind="node.attrs"
loading="lazy"
ref="resizableImg"
class="rounded"
controls="true"
draggable="false"
controlslist="nodownload noremoteplayback noplaybackrate disablepictureinpicture"
>
<source :src="node.attrs.src" />
</video>
<!-- Right Handle -->
<div
class="absolute z-10 right-0 flex items-center justify-center w-5 h-full bg-transparent cursor-ew-resize"
@mousedown.lazy.prevent="startHorizontalResize($event, 'right')"
@mouseup.lazy.prevent="stopHorizontalResize"
>
<div
class="absolute w-2 bg-white bg-opacity-80 rounded h-[55px] transition-opacity duration-100 ease-in-out opacity-0 group-hover:opacity-100 shadow-xl"
/>
</div>
</div>
<div v-else class="w-fit flex relative">
<img
v-if="mediaType === 'img'"
loading="lazy"
v-bind="node.attrs"
ref="resizableImg"
class="rounded"
draggable="false"
/>
<video
v-else-if="mediaType === 'video'"
loading="lazy"
v-bind="node.attrs"
ref="resizableImg"
class="rounded"
draggable="false"
controls="true"
controlslist="nodownload noremoteplayback noplaybackrate disablepictureinpicture"
>
<source :src="node.attrs.src" />
</video>
</div>
</node-view-wrapper>
</template>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/ResizableMediaNodeView.vue
|
Vue
|
agpl-3.0
| 9,981
|
<template>
<Dialog v-model="open" :options="{ title: 'none', size: '4xl' }">
<template #body>
<div v-if="snapshotData" class="px-4 pb-6 pt-5 sm:px-6">
<div class="w-full mb-4">
<h3 class="text-2xl font-semibold leading-6 text-gray-900">
{{ snapshotData.snapshot_message }}
</h3>
<div class="flex items-center justify-start mt-1 mb-4">
<span class="text-gray-700 text-sm"
>Created on {{ snapshotData.creation }} by
{{ snapshotData.owner }}</span
>
<span class="ml-auto text-gray-700 text-sm mr-2"
>Highlight changes</span
>
<Switch v-model="showChanges" />
</div>
<Button
icon="x"
:variant="'ghost'"
class="absolute top-3 right-3"
@click="$emit('update:modelValue', false)"
></Button>
</div>
<div class="mb-3">
<PreviewEditor
v-if="snapshotData"
:show-changes="showChanges"
class="border h-[68vh] rounded-md overflow-y-auto"
:yjs-update="encodeStateAsUpdate(snapshotData.snapshot_data)"
/>
</div>
<div class="flex">
<Button class="ml-auto" :variant="'solid'" @click="applySnapshot"
>Restore</Button
>
</div>
</div>
</template>
</Dialog>
</template>
<script setup>
import {
inject,
computed,
defineEmits,
defineProps,
onMounted,
onBeforeUnmount,
ref,
} from "vue"
import { Dialog, Button, Switch } from "frappe-ui"
import PreviewEditor from "../PreviewEditor.vue"
import { encodeStateAsUpdate } from "yjs"
defineOptions({
inheritAttrs: false,
})
const emitter = inject("emitter")
// Define props
const props = defineProps({
modelValue: {
type: Boolean,
required: true,
},
snapshotData: {
type: Object,
required: true,
},
})
const showChanges = ref(false)
const emit = defineEmits(["update:modelValue", "success"])
const open = computed({
get: () => props.modelValue,
set: (value) => emit("update:modelValue", value),
})
const applySnapshot = () => {
emit("success", props.snapshotData)
emit("update:modelValue", false)
}
onMounted(() => {
emitter.emit("forceHideBubbleMenu", true)
})
onBeforeUnmount(() => {
emitter.emit("forceHideBubbleMenu", false)
})
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/SnapshotPreviewDialog.vue
|
Vue
|
agpl-3.0
| 2,413
|
<script setup lang="ts">
import type { Editor } from "@tiptap/vue-3"
import { CellSelection } from "@tiptap/pm/tables"
import TableCellMenu from "./TableCellMenu.vue"
import TableRowMenu from "./TableRowMenu.vue"
import TableColumnMenu from "./TableColumnMenu.vue"
interface Props {
editor: Editor
}
const props = withDefaults(defineProps<Props>(), {})
function onDeleteTable() {
props.editor.chain().focus().deleteTable().run()
}
function onMergeCell() {
props.editor.chain().focus().mergeCells().run()
}
function onHeaderCell() {
props.editor.chain().focus().toggleHeaderCell().run()
}
function onSplitCell() {
const posQueue: Array<number> = []
;(props.editor.state.selection as CellSelection).forEachCell((cell, pos) => {
if (cell.attrs.colspan > 1 || cell.attrs.rowspan > 1) {
posQueue.push(pos)
}
})
let chain = props.editor.chain()
posQueue
.sort((x, y) => y - x)
.forEach((pos) => {
chain = chain.setCellSelection({ anchorCell: pos }).splitCell()
})
chain.run()
}
</script>
<template>
<TableCellMenu
:editor="editor"
@on-split-cell="onSplitCell"
@on-header-cell="onHeaderCell"
@on-merge-cell="onMergeCell"
@on-delete-table="onDeleteTable"
/>
<TableColumnMenu
:editor="editor"
@on-split-cell="onSplitCell"
@on-header-cell="onHeaderCell"
@on-merge-cell="onMergeCell"
/>
<TableRowMenu
:editor="editor"
@on-split-cell="onSplitCell"
@on-header-cell="onHeaderCell"
@on-merge-cell="onMergeCell"
/>
</template>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/TableBubbleMenu.vue
|
Vue
|
agpl-3.0
| 1,533
|
<script setup lang="ts">
import { computed } from "vue"
import { Editor } from "@tiptap/vue-3"
import { BubbleMenu } from "@tiptap/vue-3"
import { Editor as CoreEditor } from "@tiptap/core"
import { EditorState } from "@tiptap/pm/state"
import { EditorView } from "@tiptap/pm/view"
import { NodeSelection } from "@tiptap/pm/state"
import { CellSelection } from "@tiptap/pm/tables"
import {
analyzeCellSelection,
isTableCellSelected,
isTableSelected,
} from "../extensions/table/utils"
import { TableCellsMerge, TableCellsSplit } from "lucide-vue-next"
import ToggleHeaderCell from "../icons/ToggleHeaderCell.vue"
interface Props {
editor: Editor
}
export interface ShouldShowProps {
editor?: CoreEditor
view: EditorView
state?: EditorState
oldState?: EditorState
from?: number
to?: number
}
export interface Emits {
(event: "onDeleteTable"): void
(event: "onMergeCell"): void
(event: "onSplitCell"): void
(event: "onHeaderCell"): void
}
const emits = defineEmits<Emits>()
const props = withDefaults(defineProps<Props>(), {})
const shouldShow = ({ view, state, from }: ShouldShowProps) => {
if (!state) {
return false
}
return isTableCellSelected({
editor: props.editor,
view,
state,
from: from || 0,
})
}
const Selection = computed(() => {
const NodeSelection = props.editor.state.selection as NodeSelection
const isCell = NodeSelection instanceof CellSelection
if (isCell) {
return analyzeCellSelection(props.editor)
}
{
return null
}
})
</script>
<template>
<BubbleMenu
:editor="editor"
pluginKey="tableCellMenu"
:updateDelay="0"
:should-show="shouldShow"
:tippy-options="{
appendTo: 'parent',
offset: [0, 15],
popperOptions: {
modifiers: [{ name: 'flip', enabled: false }],
},
}"
>
<div
class="flex flex-row h-full leading-none gap-0.5 p-0.5 bg-white rounded shadow-sm border border-border"
>
<Button
variant="ghost"
v-if="Selection?.cellCount! > 1"
@click="() => emits('onMergeCell')"
><template #icon><TableCellsMerge class="w-4 stroke-[1.5]" /></template
></Button>
<Button
variant="ghost"
v-if="Selection?.mergedCellCount! > 0"
@click="() => emits('onSplitCell')"
><template #icon>
<TableCellsSplit class="w-4 stroke-[1.5]" /> </template
></Button>
<Button
variant="ghost"
v-if="Selection?.mergedCellCount! > 0"
@click="() => emits('onSplitCell')"
><template #icon>
<TableCellsSplit class="w-4 stroke-[1.5]" /> </template
></Button>
<Button variant="ghost" @click="() => emits('onHeaderCell')"
><template #icon>
<ToggleHeaderCell class="w-4 stroke-[1.5]" /> </template
></Button>
<Button
v-if="isTableSelected(props.editor.state.selection)"
icon="trash-2"
@click="() => emits('onDeleteTable')"
/>
</div>
</BubbleMenu>
</template>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/TableCellMenu.vue
|
Vue
|
agpl-3.0
| 3,015
|
<script setup lang="ts">
import { computed } from "vue"
import type { Editor } from "@tiptap/vue-3"
import { BubbleMenu } from "@tiptap/vue-3"
import { Editor as CoreEditor } from "@tiptap/core"
import { EditorState } from "@tiptap/pm/state"
import { EditorView } from "@tiptap/pm/view"
import type { NodeSelection } from "@tiptap/pm/state"
import { CellSelection } from "@tiptap/pm/tables"
import {
analyzeCellSelection,
isColumnGripSelected,
} from "../extensions/table/utils"
import { Button } from "frappe-ui"
import { TableCellsMerge, TableCellsSplit } from "lucide-vue-next"
import ToggleHeaderCell from "../icons/ToggleHeaderCell.vue"
interface Props {
editor: Editor
}
export interface ShouldShowProps {
editor?: CoreEditor
view: EditorView
state?: EditorState
oldState?: EditorState
from?: number
to?: number
}
const props = withDefaults(defineProps<Props>(), {})
export interface Emits {
(event: "onMergeCell"): void
(event: "onSplitCell"): void
(event: "onHeaderCell"): void
}
const emits = defineEmits<Emits>()
const shouldShow = ({ view, state, from }: ShouldShowProps) => {
if (!state) {
return false
}
return isColumnGripSelected({
editor: props.editor,
view,
state,
from: from || 0,
})
}
const Selection = computed(() => {
const NodeSelection = props.editor.state.selection as NodeSelection
const isCell = NodeSelection instanceof CellSelection
if (isCell) {
return analyzeCellSelection(props.editor)
}
{
return null
}
})
function onAddColumnBefore() {
props.editor.chain().focus().addColumnBefore().run()
}
function onAddColumnAfter() {
props.editor.chain().focus().addColumnAfter().run()
}
function onDeleteColumn() {
props.editor.chain().focus().deleteColumn().run()
}
</script>
<template>
<BubbleMenu
:editor="editor"
pluginKey="tableColumnMenu"
:updateDelay="0"
:should-show="shouldShow"
:tippy-options="{
appendTo: 'parent',
offset: [0, 15],
popperOptions: {
modifiers: [{ name: 'flip', enabled: false }],
},
}"
>
<div
class="min-w-32 flex flex-row h-full leading-none gap-0.5 p-0.5 bg-white rounded shadow-sm border"
>
<Button
title="Insert Row Left"
variant="ghost"
icon="arrow-left"
@click="onAddColumnBefore"
/>
<Button
title="Insert Row Right"
variant="ghost"
icon="arrow-right"
@click="onAddColumnAfter"
/>
<Button
variant="ghost"
title="Merge Cells"
v-if="Selection?.cellCount! > 1"
@click="emits('onMergeCell')"
><template #icon><TableCellsMerge class="w-4 stroke-[1.5]" /></template
></Button>
<Button
variant="ghost"
title="Split Cells"
v-if="Selection?.mergedCellCount! > 0"
@click="emits('onSplitCell')"
>
<template #icon> <TableCellsSplit class="w-4 stroke-[1.5]" /> </template
>Split Cells
</Button>
<Button variant="ghost" @click="() => emits('onHeaderCell')"
><template #icon>
<ToggleHeaderCell class="w-4 stroke-[1.5]" /> </template
></Button>
<Button
title="Delete Column"
variant="ghost"
icon="trash-2"
@click="onDeleteColumn"
/>
</div>
</BubbleMenu>
</template>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/TableColumnMenu.vue
|
Vue
|
agpl-3.0
| 3,351
|
<script setup lang="ts">
import { computed } from "vue"
import { Editor } from "@tiptap/vue-3"
import { BubbleMenu } from "@tiptap/vue-3"
import { Editor as CoreEditor } from "@tiptap/core"
import { EditorState } from "@tiptap/pm/state"
import { EditorView } from "@tiptap/pm/view"
import { NodeSelection } from "@tiptap/pm/state"
import { CellSelection } from "@tiptap/pm/tables"
import {
analyzeCellSelection,
isRowGripSelected,
} from "../extensions/table/utils"
import { TableCellsMerge, TableCellsSplit } from "lucide-vue-next"
import ToggleHeaderCell from "../icons/ToggleHeaderCell.vue"
interface Props {
editor: Editor
}
export interface ShouldShowProps {
editor?: CoreEditor
view: EditorView
state?: EditorState
oldState?: EditorState
from?: number
to?: number
}
const props = withDefaults(defineProps<Props>(), {})
export interface Emits {
(event: "onMergeCell"): void
(event: "onSplitCell"): void
(event: "onHeaderCell"): void
}
const emits = defineEmits<Emits>()
const shouldShow = ({ view, state, from }: ShouldShowProps) => {
if (!state) {
return false
}
return isRowGripSelected({
editor: props.editor,
view,
state,
from: from || 0,
})
}
const Selection = computed(() => {
const NodeSelection = props.editor.state.selection as NodeSelection
const isCell = NodeSelection instanceof CellSelection
if (isCell) {
return analyzeCellSelection(props.editor)
} else {
return null
}
})
function onAddRowBefore() {
props.editor.chain().focus().addRowBefore().run()
}
function onAddRowAfter() {
props.editor.chain().focus().addRowAfter().run()
}
function onDeleteRow() {
props.editor.chain().focus().deleteRow().run()
}
</script>
<template>
<BubbleMenu
:editor="editor"
pluginKey="tableRowMenu"
:updateDelay="0"
:should-show="shouldShow"
:tippy-options="{
appendTo: 'parent',
placement: 'left',
offset: [0, 5],
popperOptions: {
modifiers: [{ name: 'flip', enabled: false }],
},
}"
>
<div
class="flex flex-col h-full leading-none bg-white gap-0.5 p-0.5 rounded shadow-sm border border-border"
>
<Button
title="Add Row Above"
variant="ghost"
icon="arrow-up"
@click="onAddRowBefore"
/>
<Button
title="Add Row Below"
variant="ghost"
icon="arrow-down"
@click="onAddRowAfter"
/>
<Button
title="Merge Cells"
variant="ghost"
v-if="Selection?.cellCount! > 1"
@click="() => emits('onMergeCell')"
><template #icon><TableCellsMerge class="w-4 stroke-[1.5]" /></template
></Button>
<Button
title="Split Cells"
variant="ghost"
v-if="Selection?.mergedCellCount! > 0"
@click="() => emits('onSplitCell')"
><template #icon>
<TableCellsSplit class="w-4 stroke-[1.5]" /> </template
></Button>
<Button
title="Delete Row"
variant="ghost"
@click="() => emits('onHeaderCell')"
><template #icon>
<ToggleHeaderCell class="w-4 stroke-[1.5]" /> </template
></Button>
<Button variant="ghost" icon="trash-2" @click="onDeleteRow" />
</div>
</BubbleMenu>
</template>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/TableRowMenu.vue
|
Vue
|
agpl-3.0
| 3,273
|
<template>
<div
ref="scrollContainer"
class="flex w-44 flex-col rounded-md border bg-white p-1.5 text-base shadow gap-y-0.5 overflow-y-auto"
>
<template v-if="enabledItems.length">
<div v-for="(item, index) in enabledItems" :key="index">
<span
v-if="item.type"
class="flex w-full p-1 text-sm font-medium text-gray-600"
>{{ item.title }}</span
>
<button
v-else
class="flex h-7 w-full cursor-pointer items-center rounded-[0.4rem] px-1 text-base"
:class="{ 'bg-gray-100': index === selectedIndex }"
@click="selectItem(index)"
@mouseenter="selectedIndex = index"
>
<component :is="item.icon" class="mr-2 h-4 w-4 text-gray-600" />
{{ item.title }}
<component
:is="item.component"
v-if="item.component"
:editor="editor"
:is-open="item.isOpen"
@toggle-is-open="toggleIsOpen(item)"
>
{{ item.title }}
</component>
</button>
</div>
</template>
<div v-else class="item">No result</div>
</div>
</template>
<script>
import { Minus } from "lucide-vue-next"
export default {
components: {
Minus,
},
props: {
items: {
type: Array,
required: true,
},
editor: {
type: Object,
required: true,
},
command: {
type: Function,
required: true,
},
},
data() {
return {
selectedIndex: 0,
}
},
computed: {
enabledItems() {
return this.items.filter((item) =>
item.disabled ? !item.disabled(this.editor) : true
)
},
},
watch: {
items() {
this.selectedIndex = 0
},
},
methods: {
toggleIsOpen(item) {
item.isOpen = !item.isOpen
},
onKeyDown({ event }) {
if (event.key === "ArrowUp") {
this.upHandler()
return true
}
if (event.key === "ArrowDown") {
this.downHandler()
return true
}
if (event.key === "Enter") {
this.enterHandler()
return true
}
return false
},
upHandler() {
this.selectedIndex =
(this.selectedIndex + this.enabledItems.length - 1) %
this.enabledItems.length
},
downHandler() {
this.selectedIndex = (this.selectedIndex + 1) % this.enabledItems.length
},
enterHandler() {
this.selectItem(this.selectedIndex)
},
selectItem(index) {
const item = this.enabledItems[index]
if (item.command) {
this.command(item)
} else if (item.component) {
item.isOpen = true
}
},
},
}
</script>
|
2302_79757062/drive
|
frontend/src/components/DocEditor/components/suggestionList.vue
|
Vue
|
agpl-3.0
| 2,719
|
import { Mark, mergeAttributes, Range } from "@tiptap/core"
import { Mark as PMMark } from "@tiptap/pm/model"
import { Plugin } from "@tiptap/pm/state"
declare module "@tiptap/core" {
interface Commands<ReturnType> {
annotation: {
/**
* Set annotation (add)
*/
setAnnotation: (annotationID: string) => ReturnType
/**
* Unset a annotation (remove)
*/
unsetAnnotation: (annotationID: string) => ReturnType
}
}
}
export interface MarkWithRange {
mark: PMMark
range: Range
}
export interface AnnotationOptions {
HTMLAttributes: Record<string, any>
onAnnotationActivated: (annotationID: string) => void
onAnnotationClicked: (annotationID: string) => void
}
export interface AnnotationStorage {
activeAnnotationId: string | null
}
export const Annotation = Mark.create<AnnotationOptions, AnnotationStorage>({
name: "annotation",
excludes: "",
// https://github.com/ueberdosis/tiptap/pull/2925
// https://github.com/ueberdosis/tiptap/pull/1200
// exitable: true, Validation needed
inclusive: false,
addOptions() {
return {
HTMLAttributes: {},
onAnnotationActivated: () => {},
onAnnotationClicked: () => {},
}
},
addAttributes() {
return {
annotationID: {
default: null,
parseHTML: (el) =>
(el as HTMLSpanElement).getAttribute("data-annotation-id"),
renderHTML: (attrs) => ({ "data-annotation-id": attrs.annotationID }),
},
}
},
parseHTML() {
return [
{
tag: "span[data-annotation-id]",
getAttrs: (el) =>
!!(el as HTMLSpanElement)
.getAttribute("data-annotation-id")
?.trim() && null,
},
]
},
renderHTML({ HTMLAttributes }) {
return [
"span",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
0,
]
},
onSelectionUpdate() {
const { $from } = this.editor.state.selection
const marks = $from.marks()
if (!marks.length) {
this.storage.activeAnnotationId = null
this.options.onAnnotationActivated(this.storage.activeAnnotationId)
return
}
const annotationMark = this.editor.schema.marks.annotation
const activeAnnotationMark = marks.find(
(mark) => mark.type === annotationMark
)
this.storage.activeAnnotationId =
activeAnnotationMark?.attrs.annotationID || null
this.options.onAnnotationActivated(this.storage.activeAnnotationId)
},
addStorage() {
return {
activeAnnotationId: null,
}
},
addCommands() {
return {
setAnnotation:
(annotationID) =>
({ commands }) => {
if (!annotationID) return false
commands.setMark("annotation", { annotationID })
},
unsetAnnotation:
(annotationID) =>
({ tr, dispatch }) => {
if (!annotationID) return false
const annotationMarksWithRange: MarkWithRange[] = []
tr.doc.descendants((node, pos) => {
const annotationMark = node.marks.find(
(mark) =>
mark.type.name === "annotation" &&
mark.attrs.annotationID === annotationID
)
if (!annotationMark) return
annotationMarksWithRange.push({
mark: annotationMark,
range: {
from: pos,
to: pos + node.nodeSize,
},
})
})
annotationMarksWithRange.forEach(({ mark, range }) => {
tr.removeMark(range.from, range.to, mark)
})
return dispatch?.(tr)
},
}
},
addProseMirrorPlugins() {
return [
new Plugin({
props: {
handleDOMEvents: {
click: (view, event) => {
const pos = view.posAtCoords({
left: event.clientX,
top: event.clientY,
})
const node = pos ? view.state.doc.nodeAt(pos.pos) : null
const mark = node
? node.marks.find(
(m) => m.type === view.state.schema.marks.annotation
)
: null
if (mark) {
const annotationID = mark.attrs.annotationID
if (annotationID) {
// Call the onAnnotationActivated function
this.options.onAnnotationClicked(annotationID)
this.options.onAnnotationActivated(annotationID)
return true // Prevent default handling
}
}
return false // Allow default handling for other clicks
},
},
},
}),
]
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/AnnotationExtension/annotation.ts
|
TypeScript
|
agpl-3.0
| 4,747
|
import { mergeAttributes, Node } from "@tiptap/core"
export interface DetailContentOptions {
readonly HTMLAttributes: Record<string, unknown>
}
export const DetailsContent = Node.create<DetailContentOptions>({
name: `detailsContent`,
content: `block+`,
group: `block`,
allowGapCursor: true,
parseHTML() {
return [
{
tag: `div[data-type="details-content"]`,
},
]
},
renderHTML({ HTMLAttributes }) {
return [
`div`,
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
"data-type": `details-content`,
}),
0,
]
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/DetailsExtension/DetailsExtension/details-item.ts
|
TypeScript
|
agpl-3.0
| 617
|
import { deleteNode } from "../../../utils/deleteNodes"
import { getSelectedContent } from "../../../utils/getSelectedContent"
import { mergeAttributes, Node, RawCommands } from "@tiptap/core"
export interface DetailsOptions {
readonly HTMLAttributes: Record<string, unknown>
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
details: {
setDetails: () => ReturnType
removeDetails: () => ReturnType
}
}
}
export const Details = Node.create<DetailsOptions>({
name: `details`,
addOptions() {
return {
HTMLAttributes: {},
}
},
addAttributes() {
return {
opened: {
default: true,
keepOnSplit: false,
parseHTML: (element) => element.getAttribute(`data-opened`) === `true`,
renderHTML: (attributes) => ({
"data-opened": attributes.opened,
}),
},
}
},
content: `summary detailsContent`,
group: `block`,
allowGapCursor: true,
isolating: true,
parseHTML() {
return [
{
tag: `details`,
},
]
},
renderHTML({ HTMLAttributes }) {
return [
`div`,
{ class: `details-wrapper details-wrapper_rendered` },
[
`details`,
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
0,
],
[`button`, { class: `details-arrow` }],
]
},
addNodeView() {
return ({ node }) => {
const wrapper = document.createElement(`div`)
const details = document.createElement(`details`)
const button = document.createElement(`button`)
wrapper.className = `details-wrapper`
button.className = `details-arrow`
details.open = node.attrs.opened
button.addEventListener(`click`, () => {
details.open = !details.open
;(node.attrs as unknown as Record<string, unknown>).opened =
details.open
})
wrapper.append(details, button)
return {
dom: wrapper,
contentDOM: details,
}
}
},
addCommands(): Partial<RawCommands> {
return {
setDetails:
() =>
({ commands, state }) => {
const content = getSelectedContent(state)
return commands.insertContent(
`<details data-opened="true"><summary><p></p></summary><div data-type="details-content"><p>${content}</p></div></details><p></p>`
)
},
removeDetails:
() =>
({ state, dispatch }) =>
deleteNode(state, dispatch, this.name),
}
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/DetailsExtension/DetailsExtension/details.ts
|
TypeScript
|
agpl-3.0
| 2,524
|
export * from "./details"
export * from "./details-item"
export * from "./summary"
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/DetailsExtension/DetailsExtension/index.ts
|
TypeScript
|
agpl-3.0
| 83
|
import { mergeAttributes, Node } from "@tiptap/core"
export interface SummaryOptions {
readonly HTMLAttributes: Record<string, unknown>
}
export const DetailsSummary = Node.create<SummaryOptions>({
name: `summary`,
addOptions() {
return {
HTMLAttributes: {},
}
},
content: `paragraph`,
group: `block`,
parseHTML() {
return [
{
tag: `summary`,
},
]
},
renderHTML({ HTMLAttributes }) {
return [
`summary`,
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
0,
]
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/DetailsExtension/DetailsExtension/summary.ts
|
TypeScript
|
agpl-3.0
| 572
|
import { Mark, mergeAttributes } from "@tiptap/core"
export const Ins = Mark.create({
name: "ins",
parseHTML() {
return [
{
tag: "ins",
priority: 600,
getAttrs: (node) => {
if (node.closest("code, table")) {
return false
}
return true
},
},
]
},
renderHTML({ HTMLAttributes }) {
return ["ins", mergeAttributes(HTMLAttributes), 0]
},
})
export const Del = Mark.create({
name: "del",
parseHTML() {
return [
{
tag: "del",
priority: 600,
getAttrs: (node) => {
if (node.closest("code, table")) {
return false
}
return true
},
},
]
},
renderHTML({ HTMLAttributes }) {
return ["del", mergeAttributes(HTMLAttributes), 0]
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/InsDelMark.ts
|
TypeScript
|
agpl-3.0
| 837
|
import { Node, mergeAttributes } from "@tiptap/core"
export const InsNode = Node.create({
name: "ins",
inline: true,
group: "inline*",
parseHTML() {
return [{ tag: "ins" }]
},
renderHTML({ HTMLAttributes }) {
return ["ins", mergeAttributes(HTMLAttributes), 0]
},
addAttributes() {
return {
class: {
default: null,
},
}
},
})
export const DelNode = Node.create({
name: "del",
inline: true,
group: "inline*",
parseHTML() {
return [{ tag: "del" }]
},
renderHTML({ HTMLAttributes }) {
return ["del", mergeAttributes(HTMLAttributes), 0]
},
addAttributes() {
return {
class: {
default: null,
},
}
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/InsDelNode.ts
|
TypeScript
|
agpl-3.0
| 707
|
import { mergeAttributes, Node } from "@tiptap/core"
import { TextSelection } from "prosemirror-state"
export interface PageBreakRuleOptions {
HTMLAttributes: Record<string, any>
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
pageBreak: {
/**
* Add a page break
*/
setPageBreak: () => ReturnType
/**
* Remove a page break
*/
unsetPageBreak: () => ReturnType
}
}
}
export const PageBreak = Node.create<PageBreakRuleOptions>({
name: "pageBreak",
addOptions() {
return {
HTMLAttributes: {
id: "page-break-div",
style:
"page-break-after: always; border: 2px dashed lightgray; margin: 25px 0px;",
"data-page-break": "true",
},
}
},
group: "block",
parseHTML() {
return [
{
tag: "div",
getAttrs: (node) =>
(node as HTMLElement).style.pageBreakAfter === "always" &&
(node as HTMLElement).dataset.pageBreak === "true" &&
null,
},
]
},
renderHTML({ HTMLAttributes }) {
return ["div", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]
},
addCommands() {
return {
setPageBreak:
() =>
({ chain }) => {
return (
chain()
.insertContent({ type: this.name })
// set cursor after page break
.command(({ dispatch, tr }) => {
if (dispatch) {
const { $to } = tr.selection
const posAfter = $to.end()
if ($to.nodeAfter) {
tr.setSelection(TextSelection.create(tr.doc, $to.pos))
} else {
// add node after page break if it’s the end of the document
const node =
$to.parent.type.contentMatch.defaultType?.create({
style: {
pageBreakAfter: "always",
},
"data-page-break": "true",
})
if (node) {
tr.insert(posAfter, node)
tr.setSelection(TextSelection.create(tr.doc, posAfter))
}
}
tr.scrollIntoView()
}
return true
})
.run()
)
},
unsetPageBreak:
() =>
({ chain }) => {
return chain()
.deleteSelection()
.command(() => true)
.run()
},
}
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/Pagebreak.ts
|
TypeScript
|
agpl-3.0
| 2,629
|
import { Extension } from "@tiptap/core"
import "@tiptap/extension-text-style"
/* Default highlight extension creates a mark which is not compatible with `fontSize` */
export type HighlightOptions = {
types: string[]
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
backgroundColor: {
/**
* Set the font size
*/
toggleHighlight: (backgroundColor: string) => ReturnType
/**
* Unset the font size
*/
unsetHighlight: () => ReturnType
}
}
}
export const Highlight = Extension.create<HighlightOptions>({
name: "backgroundColor",
addOptions() {
return {
types: ["textStyle"],
}
},
addGlobalAttributes() {
return [
{
types: this.options.types,
attributes: {
backgroundColor: {
default: null,
parseHTML: (element) =>
element.style.backgroundColor.replace(/['"]+/g, ""),
renderHTML: (attributes) => {
if (!attributes.backgroundColor) {
return {}
}
return {
style: `background-color: ${attributes.backgroundColor}`,
}
},
},
},
},
]
},
addCommands() {
return {
toggleHighlight:
(backgroundColor) =>
({ chain }) => {
return chain().setMark("textStyle", { backgroundColor }).run()
},
unsetHighlight:
() =>
({ chain }) => {
return chain()
.setMark("textStyle", { backgroundColor: null })
.removeEmptyTextStyle()
.run()
},
}
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/backgroundColor.ts
|
TypeScript
|
agpl-3.0
| 1,674
|
import { Extension } from "@tiptap/core"
import { Node as ProseMirrorNode } from "@tiptap/pm/model"
import { Plugin, PluginKey } from "@tiptap/pm/state"
export interface CharacterCountOptions {
/**
* The maximum number of characters that should be allowed. Defaults to `0`.
* @default null
* @example 180
*/
limit: number | null | undefined
/**
* The mode by which the size is calculated. If set to `textSize`, the textContent of the document is used.
* If set to `nodeSize`, the nodeSize of the document is used.
* @default 'textSize'
* @example 'textSize'
*/
mode: "textSize" | "nodeSize"
}
export interface CharacterCountStorage {
/**
* Get the number of characters for the current document.
* @param options The options for the character count. (optional)
* @param options.node The node to get the characters from. Defaults to the current document.
* @param options.mode The mode by which the size is calculated. If set to `textSize`, the textContent of the document is used.
*/
characters: (options?: {
node?: ProseMirrorNode
mode?: "textSize" | "nodeSize"
}) => number
/**
* Get the number of words for the current document.
* @param options The options for the character count. (optional)
* @param options.node The node to get the words from. Defaults to the current document.
*/
words: (options?: { node?: ProseMirrorNode }) => number
}
/**
* This extension allows you to count the characters and words of your document.
* @see https://tiptap.dev/api/extensions/character-count
*/
export const CharacterCount = Extension.create<
CharacterCountOptions,
CharacterCountStorage
>({
name: "characterCount",
addOptions() {
return {
limit: null,
mode: "textSize",
}
},
addStorage() {
return {
characters: () => 0,
words: () => 0,
}
},
onBeforeCreate() {
this.storage.characters = (options) => {
const node = options?.node || this.editor.state.doc
const mode = options?.mode || this.options.mode
if (mode === "textSize") {
const text = node.textBetween(0, node.content.size, undefined, " ")
return text.length
}
return node.nodeSize
}
this.storage.words = (options) => {
const node = options?.node || this.editor.state.doc
const text = node.textBetween(0, node.content.size, " ", " ")
const words = text.split(" ").filter((word) => word !== "")
return words.length
}
},
addProseMirrorPlugins() {
return [
new Plugin({
key: new PluginKey("characterCount"),
filterTransaction: (transaction, state) => {
const limit = this.options.limit
// Nothing has changed or no limit is defined. Ignore it.
if (
!transaction.docChanged ||
limit === 0 ||
limit === null ||
limit === undefined
) {
return true
}
const oldSize = this.storage.characters({ node: state.doc })
const newSize = this.storage.characters({ node: transaction.doc })
// Everything is in the limit. Good.
if (newSize <= limit) {
return true
}
// The limit has already been exceeded but will be reduced.
if (oldSize > limit && newSize > limit && newSize <= oldSize) {
return true
}
// The limit has already been exceeded and will be increased further.
if (oldSize > limit && newSize > limit && newSize > oldSize) {
return false
}
const isPaste = transaction.getMeta("paste")
// Block all exceeding transactions that were not pasted.
if (!isPaste) {
return false
}
// For pasted content, we try to remove the exceeding content.
const pos = transaction.selection.$head.pos
const over = newSize - limit
const from = pos - over
const to = pos
// It’s probably a bad idea to mutate transactions within `filterTransaction`
// but for now this is working fine.
transaction.deleteRange(from, to)
// In some situations, the limit will continue to be exceeded after trimming.
// This happens e.g. when truncating within a complex node (e.g. table)
// and ProseMirror has to close this node again.
// If this is the case, we prevent the transaction completely.
const updatedSize = this.storage.characters({ node: transaction.doc })
if (updatedSize > limit) {
return false
}
return true
},
}),
]
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/character-count.ts
|
TypeScript
|
agpl-3.0
| 4,726
|
import { Extension } from "@tiptap/core"
import { EditorView } from "@tiptap/pm/view"
import {
redo,
undo,
ySyncPlugin,
yUndoPlugin,
yUndoPluginKey,
} from "y-prosemirror"
import { UndoManager } from "yjs"
type YSyncOpts = Parameters<typeof ySyncPlugin>[1]
declare module "@tiptap/core" {
interface Commands<ReturnType> {
collaboration: {
/**
* Undo recent changes
* @example editor.commands.undo()
*/
undo: () => ReturnType
/**
* Reapply reverted changes
* @example editor.commands.redo()
*/
redo: () => ReturnType
}
}
}
export interface CollaborationOptions {
/**
* An initialized Y.js document.
* @example new Y.Doc()
*/
document: any
/**
* Name of a Y.js fragment, can be changed to sync multiple fields with one Y.js document.
* @default 'default'
* @example 'my-custom-field'
*/
field: string
/**
* A raw Y.js fragment, can be used instead of `document` and `field`.
* @example new Y.Doc().getXmlFragment('body')
*/
fragment: any
/**
* Fired when the content from Yjs is initially rendered to Tiptap.
*/
onFirstRender?: () => void
ySyncOptions?: YSyncOpts
}
/**
* This extension allows you to collaborate with others in real-time.
* @see https://tiptap.dev/api/extensions/collaboration
*/
export const Collaboration = Extension.create<CollaborationOptions>({
name: "collaboration",
priority: 1000,
addOptions() {
return {
document: null,
field: "default",
fragment: null,
}
},
onCreate() {
if (
this.editor.extensionManager.extensions.find(
(extension) => extension.name === "history"
)
) {
console.warn(
'[tiptap warn]: "@tiptap/extension-collaboration" comes with its own history support and is not compatible with "@tiptap/extension-history".'
)
}
},
addCommands() {
return {
undo:
() =>
({ tr, state, dispatch }) => {
tr.setMeta("preventDispatch", true)
const undoManager: UndoManager =
yUndoPluginKey.getState(state).undoManager
if (undoManager.undoStack.length === 0) {
return false
}
if (!dispatch) {
return true
}
return undo(state)
},
redo:
() =>
({ tr, state, dispatch }) => {
tr.setMeta("preventDispatch", true)
const undoManager: UndoManager =
yUndoPluginKey.getState(state).undoManager
if (undoManager.redoStack.length === 0) {
return false
}
if (!dispatch) {
return true
}
return redo(state)
},
}
},
addKeyboardShortcuts() {
return {
"Mod-z": () => this.editor.commands.undo(),
"Mod-y": () => this.editor.commands.redo(),
"Shift-Mod-z": () => this.editor.commands.redo(),
}
},
addProseMirrorPlugins() {
const fragment = this.options.fragment
? this.options.fragment
: this.options.document.getXmlFragment(this.options.field)
// Quick fix until there is an official implementation (thanks to @hamflx).
// See https://github.com/yjs/y-prosemirror/issues/114 and https://github.com/yjs/y-prosemirror/issues/102
const yUndoPluginInstance = yUndoPlugin()
const originalUndoPluginView = yUndoPluginInstance.spec.view
yUndoPluginInstance.spec.view = (view: EditorView) => {
const { undoManager } = yUndoPluginKey.getState(view.state)
if (undoManager.restore) {
undoManager.restore()
// eslint-disable-next-line
undoManager.restore = () => {}
}
const viewRet = originalUndoPluginView
? originalUndoPluginView(view)
: undefined
return {
destroy: () => {
const hasUndoManSelf = undoManager.trackedOrigins.has(undoManager)
// eslint-disable-next-line
const observers = undoManager._observers
undoManager.restore = () => {
if (hasUndoManSelf) {
undoManager.trackedOrigins.add(undoManager)
}
undoManager.doc.on(
"afterTransaction",
undoManager.afterTransactionHandler
)
// eslint-disable-next-line
undoManager._observers = observers
}
if (viewRet?.destroy) {
viewRet.destroy()
}
},
}
}
const ySyncPluginOptions: YSyncOpts = {
...this.options.ySyncOptions,
onFirstRender: this.options.onFirstRender,
}
const ySyncPluginInstance = ySyncPlugin(fragment, ySyncPluginOptions)
return [ySyncPluginInstance, yUndoPluginInstance]
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/collaboration.ts
|
TypeScript
|
agpl-3.0
| 4,776
|
import { Extension } from "@tiptap/core"
import { DecorationAttrs } from "@tiptap/pm/view"
import { defaultSelectionBuilder, yCursorPlugin } from "y-prosemirror"
type CollaborationCursorStorage = {
users: { clientId: number; [key: string]: any }[]
}
export interface CollaborationCursorOptions {
/**
* The Hocuspocus provider instance. This can also be a TiptapCloudProvider instance.
* @type {HocuspocusProvider | TiptapCloudProvider}
* @example new HocuspocusProvider()
*/
provider: any
/**
* The user details object – feel free to add properties to this object as needed
* @example { name: 'John Doe', color: '#305500' }
*/
user: Record<string, any>
/**
* A function that returns a DOM element for the cursor.
* @param user The user details object
* @example
* render: user => {
* const cursor = document.createElement('span')
* cursor.classList.add('collaboration-cursor__caret')
* cursor.setAttribute('style', `border-color: ${user.color}`)
*
* const label = document.createElement('div')
* label.classList.add('collaboration-cursor__label')
* label.setAttribute('style', `background-color: ${user.color}`)
* label.insertBefore(document.createTextNode(user.name), null)
*
* cursor.insertBefore(label, null)
* return cursor
* }
*/
render(user: Record<string, any>): HTMLElement
/**
* A function that returns a ProseMirror DecorationAttrs object for the selection.
* @param user The user details object
* @example
* selectionRender: user => {
* return {
* nodeName: 'span',
* class: 'collaboration-cursor__selection',
* style: `background-color: ${user.color}`,
* 'data-user': user.name,
* }
*/
selectionRender(user: Record<string, any>): DecorationAttrs
/**
* @deprecated The "onUpdate" option is deprecated. Please use `editor.storage.collaborationCursor.users` instead. Read more: https://tiptap.dev/api/extensions/collaboration-cursor
*/
onUpdate: (users: { clientId: number; [key: string]: any }[]) => null
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
collaborationCursor: {
/**
* Update details of the current user
* @example editor.commands.updateUser({ name: 'John Doe', color: '#305500' })
*/
updateUser: (attributes: Record<string, any>) => ReturnType
/**
* Update details of the current user
*
* @deprecated The "user" command is deprecated. Please use "updateUser" instead. Read more: https://tiptap.dev/api/extensions/collaboration-cursor
*/
user: (attributes: Record<string, any>) => ReturnType
}
}
}
const awarenessStatesToArray = (states: Map<number, Record<string, any>>) => {
return Array.from(states.entries()).map(([key, value]) => {
return {
clientId: key,
...value.user,
}
})
}
const defaultOnUpdate = () => null
/**
* This extension allows you to add collaboration cursors to your editor.
* @see https://tiptap.dev/api/extensions/collaboration-cursor
*/
export const CollaborationCursor = Extension.create<
CollaborationCursorOptions,
CollaborationCursorStorage
>({
name: "collaborationCursor",
priority: 999,
addOptions() {
return {
provider: null,
user: {
name: null,
color: null,
},
render: (user) => {
const cursor = document.createElement("span")
cursor.classList.add("collaboration-cursor__caret")
cursor.setAttribute("style", `border-color: ${user.color}`)
const label = document.createElement("div")
label.classList.add("collaboration-cursor__label")
label.setAttribute("style", `background-color: ${user.color}`)
label.insertBefore(document.createTextNode(user.name), null)
cursor.insertBefore(label, null)
return cursor
},
selectionRender: defaultSelectionBuilder,
onUpdate: defaultOnUpdate,
}
},
onCreate() {
if (this.options.onUpdate !== defaultOnUpdate) {
console.warn(
'[tiptap warn]: DEPRECATED: The "onUpdate" option is deprecated. Please use `editor.storage.collaborationCursor.users` instead. Read more: https://tiptap.dev/api/extensions/collaboration-cursor'
)
}
if (!this.options.provider) {
throw new Error(
'The "provider" option is required for the CollaborationCursor extension'
)
}
},
addStorage() {
return {
users: [],
}
},
addCommands() {
return {
updateUser: (attributes) => () => {
this.options.user = attributes
this.options.provider.awareness.setLocalStateField(
"user",
this.options.user
)
return true
},
user:
(attributes) =>
({ editor }) => {
console.warn(
'[tiptap warn]: DEPRECATED: The "user" command is deprecated. Please use "updateUser" instead. Read more: https://tiptap.dev/api/extensions/collaboration-cursor'
)
return editor.commands.updateUser(attributes)
},
}
},
addProseMirrorPlugins() {
return [
yCursorPlugin(
(() => {
this.options.provider.awareness.setLocalStateField(
"user",
this.options.user
)
this.storage.users = awarenessStatesToArray(
this.options.provider.awareness.states
)
this.options.provider.awareness.on("update", () => {
this.storage.users = awarenessStatesToArray(
this.options.provider.awareness.states
)
})
return this.options.provider.awareness
})(),
// @ts-ignore
{
cursorBuilder: this.options.render,
selectionBuilder: this.options.selectionRender,
}
),
]
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/collaborationCursor.ts
|
TypeScript
|
agpl-3.0
| 5,872
|
import "@tiptap/extension-text-style"
import { Extension } from "@tiptap/core"
export type ColorOptions = {
/**
* The types where the color can be applied
* @default ['textStyle']
* @example ['heading', 'paragraph']
*/
types: string[]
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
color: {
/**
* Set the text color
* @param color The color to set
* @example editor.commands.setColor('red')
*/
setColor: (color: string) => ReturnType
/**
* Unset the text color
* @example editor.commands.unsetColor()
*/
unsetColor: () => ReturnType
}
}
}
/**
* This extension allows you to color your text.
* @see https://tiptap.dev/api/extensions/color
*/
export const Color = Extension.create<ColorOptions>({
name: "color",
addOptions() {
return {
types: ["textStyle"],
}
},
addGlobalAttributes() {
return [
{
types: this.options.types,
attributes: {
color: {
default: null,
parseHTML: (element) => element.style.color?.replace(/['"]+/g, ""),
renderHTML: (attributes) => {
if (!attributes.color) {
return {}
}
return {
style: `color: ${attributes.color}`,
}
},
},
},
},
]
},
addCommands() {
return {
setColor:
(color) =>
({ chain }) => {
return chain().setMark("textStyle", { color }).run()
},
unsetColor:
() =>
({ chain }) => {
return chain()
.setMark("textStyle", { color: null })
.removeEmptyTextStyle()
.run()
},
}
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/color.ts
|
TypeScript
|
agpl-3.0
| 1,796
|
import { getMarkRange, Mark, mergeAttributes } from "@tiptap/vue-3"
import { Plugin, TextSelection } from "prosemirror-state"
export interface CommentOptions {
HTMLAttributes: Record<string, any>
isCommentModeOn: boolean
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
comment: {
/**
* Set a comment mark
*/
setComment: (comment: string) => ReturnType
/**
* Toggle a comment mark
*/
toggleComment: () => ReturnType
/**
* Unset a comment mark
*/
unsetComment: () => ReturnType
}
}
}
export const Comment = Mark.create<CommentOptions>({
name: "comment",
/* Need to validate exitable */
// https://github.com/ueberdosis/tiptap/pull/2925
// https://github.com/ueberdosis/tiptap/pull/1200
/* exitable: true, */
inclusive: false,
addOptions() {
return {
HTMLAttributes: {},
isCommentModeOn: false,
}
},
addAttributes() {
return {
comment: {
default: null,
parseHTML: (el) => (el as HTMLSpanElement).getAttribute("data-comment"),
renderHTML: (attrs) => ({ "data-comment": attrs.comment }),
},
}
},
parseHTML() {
return [
{
tag: "span[data-comment]",
getAttrs: (el) =>
!!(el as HTMLSpanElement).getAttribute("data-comment")?.trim() &&
null,
},
]
},
renderHTML({ HTMLAttributes }) {
return [
"span",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
0,
]
},
addCommands() {
return {
setComment:
(comment: string) =>
({ commands }) =>
commands.setMark("comment", { comment }),
toggleComment:
() =>
({ commands }) =>
commands.toggleMark("comment"),
unsetComment:
() =>
({ commands }) =>
commands.unsetMark("comment"),
}
},
addProseMirrorPlugins() {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const extensionThis = this
const plugins = [
new Plugin({
props: {
handleClick(view, pos) {
if (!extensionThis.options.isCommentModeOn) return false
const { schema, doc, tr } = view.state
const range = getMarkRange(doc.resolve(pos), schema.marks.comment)
if (!range) return false
const [$start, $end] = [
doc.resolve(range.from),
doc.resolve(range.to),
]
view.dispatch(tr.setSelection(new TextSelection($start, $end)))
return true
},
},
}),
]
return plugins
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/comment.ts
|
TypeScript
|
agpl-3.0
| 2,681
|
import { Mark, mergeAttributes } from "@tiptap/core"
import { DiffType } from "./diffType"
export const DiffMarkExtension = Mark.create({
name: "diffMark",
addAttributes() {
return {
type: {
renderHTML: ({ type }) => {
const color = {
[DiffType.Inserted]: "#bcf5bc",
[DiffType.Deleted]: "#ff8989",
}[type]
return {
style: "background-color: " + color,
}
},
},
}
},
renderHTML({ HTMLAttributes }) {
return [
"span",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
0,
]
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/createDiffMark.ts
|
TypeScript
|
agpl-3.0
| 639
|
export const DiffType = {
Unchanged: 0,
Deleted: -1,
Inserted: 1,
}
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/diffType.js
|
JavaScript
|
agpl-3.0
| 74
|
import { Node } from "@tiptap/core"
/**
* The default document node which represents the top level node of the editor.
* @see https://tiptap.dev/api/nodes/document
*/
export const Document = Node.create({
name: "doc",
topNode: true,
content: "block+",
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/document.ts
|
TypeScript
|
agpl-3.0
| 265
|
import "@tiptap/extension-text-style"
import { Extension } from "@tiptap/core"
export type FontFamilyOptions = {
/**
* A list of node names where the font family can be applied.
* @default ['textStyle']
* @example ['heading', 'paragraph']
*/
types: string[]
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
fontFamily: {
/**
* Set the font family
* @param fontFamily The font family
* @example editor.commands.setFontFamily('Arial')
*/
setFontFamily: (fontFamily: string) => ReturnType
/**
* Unset the font family
* @example editor.commands.unsetFontFamily()
*/
unsetFontFamily: () => ReturnType
}
}
}
/**
* This extension allows you to set a font family for text.
* @see https://www.tiptap.dev/api/extensions/font-family
*/
export const FontFamily = Extension.create<FontFamilyOptions>({
name: "fontFamily",
addOptions() {
return {
types: ["textStyle"],
}
},
addGlobalAttributes() {
return [
{
types: this.options.types,
attributes: {
fontFamily: {
default: null,
parseHTML: (element) =>
element.style.fontFamily?.replace(/['"]+/g, ""),
renderHTML: (attributes) => {
if (!attributes.fontFamily) {
return {}
}
return {
style: `font-family: ${attributes.fontFamily}`,
}
},
},
},
},
]
},
addCommands() {
return {
setFontFamily:
(fontFamily) =>
({ chain }) => {
return chain().setMark("textStyle", { fontFamily }).run()
},
unsetFontFamily:
() =>
({ chain }) => {
return chain()
.setMark("textStyle", { fontFamily: null })
.removeEmptyTextStyle()
.run()
},
}
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/font-family.ts
|
TypeScript
|
agpl-3.0
| 1,957
|
import { Extension } from "@tiptap/core"
import "@tiptap/extension-text-style"
export type FontSizeOptions = {
types: string[]
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
fontSize: {
/**
* Set the font size
*/
setFontSize: (fontSize: string) => ReturnType
/**
* Unset the font size
*/
unsetFontSize: () => ReturnType
}
}
}
export const FontSize = Extension.create<FontSizeOptions>({
name: "fontSize",
addOptions() {
return {
types: ["textStyle"],
}
},
addGlobalAttributes() {
return [
{
types: this.options.types,
attributes: {
fontSize: {
default: null,
parseHTML: (element) =>
element.style.fontSize.replace(/['"]+/g, ""),
renderHTML: (attributes) => {
if (!attributes.fontSize) {
return {}
}
return {
style: `font-size: ${attributes.fontSize}`,
}
},
},
},
},
]
},
addCommands() {
return {
setFontSize:
(fontSize) =>
({ chain }) => {
return chain().setMark("textStyle", { fontSize }).run()
},
unsetFontSize:
() =>
({ chain }) => {
return chain()
.setMark("textStyle", { fontSize: null })
.removeEmptyTextStyle()
.run()
},
}
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/font-size.ts
|
TypeScript
|
agpl-3.0
| 1,494
|
// Plugin adapted from the following examples:
// - https://github.com/ueberdosis/tiptap/blob/main/packages/extension-image/src/image.ts
// - https://gist.github.com/slava-vishnyakov/16076dff1a77ddaca93c4bccd4ec4521
import { mergeAttributes, Node, nodeInputRule } from "@tiptap/core"
import { Plugin } from "prosemirror-state"
import fileToBase64 from "@/utils/file-to-base64"
export const inputRegex =
/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/
export default Node.create({
name: "image",
addOptions() {
return {
inline: false,
HTMLAttributes: {},
}
},
inline() {
return this.options.inline
},
group() {
return this.options.inline ? "inline" : "block"
},
draggable: true,
addAttributes() {
return {
src: {
default: null,
},
alt: {
default: null,
},
title: {
default: null,
},
}
},
parseHTML() {
return [
{
tag: "img[src]",
},
]
},
renderHTML({ HTMLAttributes }) {
return ["img", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]
},
addCommands() {
return {
setImage:
(options) =>
({ commands }) => {
return commands.insertContent({
type: this.name,
attrs: options,
})
},
}
},
addInputRules() {
return [
nodeInputRule({
find: inputRegex,
type: this.type,
getAttributes: (match) => {
const [, , alt, src, title] = match
return { src, alt, title }
},
}),
]
},
addProseMirrorPlugins() {
return [dropImagePlugin()]
},
})
const dropImagePlugin = () => {
return new Plugin({
props: {
handlePaste(view, event) {
const items = Array.from(event.clipboardData?.items || [])
const { schema } = view.state
items.forEach((item) => {
const image = item.getAsFile()
if (!image) return
if (item.type.indexOf("image") === 0) {
event.preventDefault()
fileToBase64(image).then((base64) => {
const node = schema.nodes.image.create({
src: base64,
})
const transaction = view.state.tr.replaceSelectionWith(node)
view.dispatch(transaction)
})
}
})
return false
},
handleDOMEvents: {
drop: (view, event) => {
const hasFiles =
event.dataTransfer &&
event.dataTransfer.files &&
event.dataTransfer.files.length
if (!hasFiles) {
return false
}
const images = Array.from(event.dataTransfer?.files ?? []).filter(
(file) => /image/i.test(file.type)
)
if (images.length === 0) {
return false
}
event.preventDefault()
const { schema } = view.state
const coordinates = view.posAtCoords({
left: event.clientX,
top: event.clientY,
})
if (!coordinates) return false
images.forEach(async (image) => {
fileToBase64(image).then((base64) => {
const node = schema.nodes.image.create({
src: base64,
})
const transaction = view.state.tr.insert(coordinates.pos, node)
view.dispatch(transaction)
})
})
return true
},
},
},
})
}
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/image-extension.js
|
JavaScript
|
agpl-3.0
| 3,539
|
import {
CommandProps,
Extension,
Extensions,
isList,
KeyboardShortcutCommand,
} from "@tiptap/core"
import { TextSelection, Transaction } from "prosemirror-state"
declare module "@tiptap/core" {
interface Commands<ReturnType> {
indent: {
indent: () => ReturnType
outdent: () => ReturnType
}
}
}
type IndentOptions = {
names: Array<string>
indentRange: number
minIndentLevel: number
maxIndentLevel: number
defaultIndentLevel: number
HTMLAttributes: Record<string, any>
}
export const Indent = Extension.create<IndentOptions, never>({
name: "indent",
addOptions() {
return {
names: ["heading", "paragraph"],
indentRange: 24,
minIndentLevel: 0,
maxIndentLevel: 24 * 10,
defaultIndentLevel: 0,
HTMLAttributes: {},
}
},
addGlobalAttributes() {
return [
{
types: this.options.names,
attributes: {
indent: {
default: this.options.defaultIndentLevel,
renderHTML: (attributes) => ({
style: `margin-left: ${attributes.indent}px!important;`,
}),
parseHTML: (element) =>
parseInt(element.style.marginLeft, 10) ||
this.options.defaultIndentLevel,
},
},
},
]
},
addCommands(this) {
return {
indent:
() =>
({ tr, state, dispatch, editor }: CommandProps) => {
const { selection } = state
tr = tr.setSelection(selection)
tr = updateIndentLevel(
tr,
this.options,
editor.extensionManager.extensions,
"indent"
)
if (tr.docChanged && dispatch) {
dispatch(tr)
return true
}
return false
},
outdent:
() =>
({ tr, state, dispatch, editor }: CommandProps) => {
const { selection } = state
tr = tr.setSelection(selection)
tr = updateIndentLevel(
tr,
this.options,
editor.extensionManager.extensions,
"outdent"
)
if (tr.docChanged && dispatch) {
dispatch(tr)
return true
}
return false
},
}
},
addKeyboardShortcuts() {
return {
Tab: getIndent(),
"Shift-Tab": getOutdent(false),
Backspace: getOutdent(true),
"Mod-]": getIndent(),
"Mod-[": getOutdent(false),
}
},
onUpdate() {
const { editor } = this
// インデントされたparagraphがlistItemに変更されたらindentをリセット
if (editor.isActive("listItem")) {
const node = editor.state.selection.$head.node()
if (node.attrs.indent) {
editor.commands.updateAttributes(node.type.name, { indent: 0 })
}
}
},
})
export const clamp = (val: number, min: number, max: number): number => {
if (val < min) {
return min
}
if (val > max) {
return max
}
return val
}
function setNodeIndentMarkup(
tr: Transaction,
pos: number,
delta: number,
min: number,
max: number
): Transaction {
if (!tr.doc) return tr
const node = tr.doc.nodeAt(pos)
if (!node) return tr
const indent = clamp((node.attrs.indent || 0) + delta, min, max)
if (indent === node.attrs.indent) return tr
const nodeAttrs = {
...node.attrs,
indent,
}
return tr.setNodeMarkup(pos, node.type, nodeAttrs, node.marks)
}
type IndentType = "indent" | "outdent"
const updateIndentLevel = (
tr: Transaction,
options: IndentOptions,
extensions: Extensions,
type: IndentType
): Transaction => {
const { doc, selection } = tr
if (!doc || !selection) return tr
if (!(selection instanceof TextSelection)) {
return tr
}
const { from, to } = selection
doc.nodesBetween(from, to, (node, pos) => {
if (options.names.includes(node.type.name)) {
tr = setNodeIndentMarkup(
tr,
pos,
options.indentRange * (type === "indent" ? 1 : -1),
options.minIndentLevel,
options.maxIndentLevel
)
return false
}
return !isList(node.type.name, extensions)
})
return tr
}
export const getIndent: () => KeyboardShortcutCommand =
() =>
({ editor }) => {
if (editor.can().sinkListItem("listItem")) {
return editor.chain().focus().sinkListItem("listItem").run()
}
return editor.chain().focus().indent().run()
}
export const getOutdent: (
outdentOnlyAtHead: boolean
) => KeyboardShortcutCommand =
(outdentOnlyAtHead) =>
({ editor }) => {
if (outdentOnlyAtHead && editor.state.selection.$head.parentOffset > 0) {
return false
}
if (
/**
* editor.state.selection.$head.parentOffset > 0があるのは
* ```
* - Hello
* |<<ここにカーソル
* ```
* この状態でBackSpaceを繰り返すとlistItemのtoggleが繰り返されるのを防ぐため
*/
(!outdentOnlyAtHead || editor.state.selection.$head.parentOffset > 0) &&
editor.can().liftListItem("listItem")
) {
return editor.chain().focus().liftListItem("listItem").run()
}
return editor.chain().focus().outdent().run()
}
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/indent.ts
|
TypeScript
|
agpl-3.0
| 5,220
|
import { Extension } from "@tiptap/core"
export interface LineHeightOptions {
types: string[]
heights: string[]
defaultHeight: string
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
lineHeight: {
/**
* Set the line height attribute
*/
setLineHeight: (height: string) => ReturnType
/**
* Unset the text align attribute
*/
unsetLineHeight: () => ReturnType
}
}
}
export const LineHeight = Extension.create<LineHeightOptions>({
name: "lineHeight",
addOptions() {
return {
types: ["heading", "paragraph"],
heights: ["100%", "26px", "150%", "200%", "250%", "300%"],
defaultHeight: "100%",
}
},
addGlobalAttributes() {
return [
{
types: this.options.types,
attributes: {
lineHeight: {
default: this.options.defaultHeight,
parseHTML: (element) =>
element.style.lineHeight || this.options.defaultHeight,
renderHTML: (attributes) => {
if (attributes.lineHeight === this.options.defaultHeight) {
return {}
}
return { style: `line-height: ${attributes.lineHeight}` }
},
},
},
},
]
},
addCommands() {
return {
setLineHeight:
(height: string) =>
({ commands }) => {
if (!this.options.heights.includes(height)) {
return false
}
return this.options.types.every((type) =>
commands.updateAttributes(type, { lineHeight: height })
)
},
unsetLineHeight:
() =>
({ commands }) => {
return this.options.types.every((type) =>
commands.resetAttributes(type, "lineHeight")
)
},
}
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/lineHeight.ts
|
TypeScript
|
agpl-3.0
| 1,846
|
import {
Mark,
markPasteRule,
mergeAttributes,
PasteRuleMatch,
} from "@tiptap/core"
import { Plugin } from "@tiptap/pm/state"
import { find, registerCustomProtocol, reset } from "linkifyjs"
import { autolink } from "./helpers/autolink.js"
import { clickHandler } from "./helpers/clickHandler.js"
import { pasteHandler } from "./helpers/pasteHandler.js"
export interface LinkProtocolOptions {
/**
* The protocol scheme to be registered.
* @default '''
* @example 'ftp'
* @example 'git'
*/
scheme: string
/**
* If enabled, it allows optional slashes after the protocol.
* @default false
* @example true
*/
optionalSlashes?: boolean
}
export const pasteRegex =
/https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z]{2,}\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi
/**
* @deprecated The default behavior is now to open links when the editor is not editable.
*/
type DeprecatedOpenWhenNotEditable = "whenNotEditable"
export interface LinkOptions {
/**
* If enabled, the extension will automatically add links as you type.
* @default true
* @example false
*/
autolink: boolean
/**
* An array of custom protocols to be registered with linkifyjs.
* @default []
* @example ['ftp', 'git']
*/
protocols: Array<LinkProtocolOptions | string>
/**
* Default protocol to use when no protocol is specified.
* @default 'http'
*/
defaultProtocol: string
/**
* If enabled, links will be opened on click.
* @default true
* @example false
*/
openOnClick: boolean | DeprecatedOpenWhenNotEditable
/**
* Adds a link to the current selection if the pasted content only contains an url.
* @default true
* @example false
*/
linkOnPaste: boolean
/**
* HTML attributes to add to the link element.
* @default {}
* @example { class: 'foo' }
*/
HTMLAttributes: Record<string, any>
/**
* A validation function that modifies link verification for the auto linker.
* @param url - The url to be validated.
* @returns - True if the url is valid, false otherwise.
*/
validate: (url: string) => boolean
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
link: {
/**
* Set a link mark
* @param attributes The link attributes
* @example editor.commands.setLink({ href: 'https://tiptap.dev' })
*/
setLink: (attributes: {
href: string
target?: string | null
rel?: string | null
class?: string | null
}) => ReturnType
/**
* Toggle a link mark
* @param attributes The link attributes
* @example editor.commands.toggleLink({ href: 'https://tiptap.dev' })
*/
toggleLink: (attributes: {
href: string
target?: string | null
rel?: string | null
class?: string | null
}) => ReturnType
/**
* Unset a link mark
* @example editor.commands.unsetLink()
*/
unsetLink: () => ReturnType
}
}
}
// From DOMPurify
// https://github.com/cure53/DOMPurify/blob/main/src/regexp.js
// eslint-disable-next-line no-control-regex
const ATTR_WHITESPACE =
/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g
function isAllowedUri(
uri: string | undefined,
protocols?: LinkOptions["protocols"]
) {
const allowedProtocols: string[] = [
"http",
"https",
"ftp",
"ftps",
"mailto",
"tel",
"callto",
"sms",
"cid",
"xmpp",
]
if (protocols) {
protocols.forEach((protocol) => {
const nextProtocol =
typeof protocol === "string" ? protocol : protocol.scheme
if (nextProtocol) {
allowedProtocols.push(nextProtocol)
}
})
}
// eslint-disable-next-line no-useless-escape
return (
!uri ||
uri
.replace(ATTR_WHITESPACE, "")
.match(
new RegExp(
`^(?:(?:${allowedProtocols.join(
"|"
)}):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))`,
"i"
)
)
)
}
/**
* This extension allows you to create links.
* @see https://www.tiptap.dev/api/marks/link
*/
export const Link = Mark.create<LinkOptions>({
name: "link",
priority: 1000,
keepOnSplit: false,
exitable: true,
onCreate() {
this.options.protocols.forEach((protocol) => {
if (typeof protocol === "string") {
registerCustomProtocol(protocol)
return
}
registerCustomProtocol(protocol.scheme, protocol.optionalSlashes)
})
},
onDestroy() {
reset()
},
inclusive() {
return this.options.autolink
},
addOptions() {
return {
openOnClick: true,
linkOnPaste: true,
autolink: true,
protocols: [],
defaultProtocol: "http",
HTMLAttributes: {
target: "_blank",
rel: "noopener noreferrer nofollow",
class: null,
},
validate: (url) => !!url,
}
},
addAttributes() {
return {
href: {
default: null,
parseHTML(element) {
return element.getAttribute("href")
},
},
target: {
default: this.options.HTMLAttributes.target,
},
rel: {
default: this.options.HTMLAttributes.rel,
},
class: {
default: this.options.HTMLAttributes.class,
},
}
},
parseHTML() {
return [
{
tag: "a[href]",
getAttrs: (dom) => {
const href = (dom as HTMLElement).getAttribute("href")
// prevent XSS attacks
if (!href || !isAllowedUri(href, this.options.protocols)) {
return false
}
return null
},
},
]
},
renderHTML({ HTMLAttributes }) {
// prevent XSS attacks
if (!isAllowedUri(HTMLAttributes.href, this.options.protocols)) {
// strip out the href
return [
"a",
mergeAttributes(this.options.HTMLAttributes, {
...HTMLAttributes,
href: "",
}),
0,
]
}
return [
"a",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
0,
]
},
addCommands() {
return {
setLink:
(attributes) =>
({ chain }) => {
return chain()
.setMark(this.name, attributes)
.setMeta("preventAutolink", true)
.run()
},
toggleLink:
(attributes) =>
({ chain }) => {
return chain()
.toggleMark(this.name, attributes, { extendEmptyMarkRange: true })
.setMeta("preventAutolink", true)
.run()
},
unsetLink:
() =>
({ chain }) => {
return chain()
.unsetMark(this.name, { extendEmptyMarkRange: true })
.setMeta("preventAutolink", true)
.run()
},
}
},
addPasteRules() {
return [
markPasteRule({
find: (text) => {
const foundLinks: PasteRuleMatch[] = []
if (text) {
const { validate } = this.options
const links = find(text).filter(
(item) => item.isLink && validate(item.value)
)
if (links.length) {
links.forEach((link) =>
foundLinks.push({
text: link.value,
data: {
href: link.href,
},
index: link.start,
})
)
}
}
return foundLinks
},
type: this.type,
getAttributes: (match) => {
return {
href: match.data?.href,
}
},
}),
]
},
addProseMirrorPlugins() {
const plugins: Plugin[] = []
if (this.options.autolink) {
plugins.push(
autolink({
type: this.type,
defaultProtocol: this.options.defaultProtocol,
validate: this.options.validate,
})
)
}
if (this.options.openOnClick === true) {
plugins.push(
clickHandler({
type: this.type,
})
)
}
if (this.options.linkOnPaste) {
plugins.push(
pasteHandler({
editor: this.editor,
defaultProtocol: this.options.defaultProtocol,
type: this.type,
})
)
}
return plugins
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/link.ts
|
TypeScript
|
agpl-3.0
| 8,392
|
import { mergeAttributes, Node } from "@tiptap/core"
import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model"
import { PluginKey } from "@tiptap/pm/state"
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"
// See `addAttributes` below
export interface MentionNodeAttrs {
/**
* The identifier for the selected item that was mentioned, stored as a `data-id`
* attribute.
*/
id: string | null
/**
* The label to be rendered by the editor as the displayed text for this mentioned
* item, if provided. Stored as a `data-label` attribute. See `renderLabel`.
*/
label?: string | null
author?: string | null
type?: string | null
}
export type MentionOptions<
SuggestionItem = any,
Attrs extends Record<string, any> = MentionNodeAttrs
> = {
/**
* The HTML attributes for a mention node.
* @default {}
* @example { class: 'foo' }
*/
HTMLAttributes: Record<string, any>
/**
* A function to render the label of a mention.
* @deprecated use renderText and renderHTML instead
* @param props The render props
* @returns The label
* @example ({ options, node }) => `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`
*/
renderLabel?: (props: {
options: MentionOptions<SuggestionItem, Attrs>
node: ProseMirrorNode
}) => string
/**
* A function to render the text of a mention.
* @param props The render props
* @returns The text
* @example ({ options, node }) => `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`
*/
renderText: (props: {
options: MentionOptions<SuggestionItem, Attrs>
node: ProseMirrorNode
}) => string
/**
* A function to render the HTML of a mention.
* @param props The render props
* @returns The HTML as a ProseMirror DOM Output Spec
* @example ({ options, node }) => ['span', { 'data-type': 'mention' }, `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`]
*/
renderHTML: (props: {
options: MentionOptions<SuggestionItem, Attrs>
node: ProseMirrorNode
}) => DOMOutputSpec
/**
* Whether to delete the trigger character with backspace.
* @default false
*/
deleteTriggerWithBackspace: boolean
/**
* The suggestion options.
* @default {}
* @example { char: '@', pluginKey: MentionPluginKey, command: ({ editor, range, props }) => { ... } }
*/
suggestion: Omit<SuggestionOptions<SuggestionItem, Attrs>, "editor">
}
/**
* The plugin key for the mention plugin.
* @default 'mention'
*/
export const MentionPluginKey = new PluginKey("mention")
/**
* This extension allows you to insert mentions into the editor.
* @see https://www.tiptap.dev/api/extensions/mention
*/
export const Mention = Node.create<MentionOptions>({
name: "mention",
addOptions() {
return {
HTMLAttributes: {},
renderText({ options, node }) {
return `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`
},
deleteTriggerWithBackspace: false,
renderHTML({ options, node }) {
return [
"span",
mergeAttributes(this.HTMLAttributes, options.HTMLAttributes),
`${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`,
]
},
suggestion: {
char: "@",
pluginKey: MentionPluginKey,
command: ({ editor, range, props }) => {
// increase range.to by one when the next node is of type "text"
// and starts with a space character
const nodeAfter = editor.view.state.selection.$to.nodeAfter
const overrideSpace = nodeAfter?.text?.startsWith(" ")
if (overrideSpace) {
range.to += 1
}
editor
.chain()
.focus()
.insertContentAt(range, [
{
type: this.name,
attrs: props,
},
{
type: "text",
text: " ",
},
])
.run()
window.getSelection()?.collapseToEnd()
},
allow: ({ state, range }) => {
const $from = state.doc.resolve(range.from)
const type = state.schema.nodes[this.name]
const allow = !!$from.parent.type.contentMatch.matchType(type)
return allow
},
},
}
},
group: "inline",
inline: true,
selectable: false,
atom: true,
addAttributes() {
return {
id: {
default: null,
parseHTML: (element) => element.getAttribute("data-id"),
renderHTML: (attributes) => {
if (!attributes.id) {
return {}
}
return {
"data-id": attributes.id,
}
},
},
label: {
default: null,
parseHTML: (element) => element.getAttribute("data-label"),
renderHTML: (attributes) => {
if (!attributes.label) {
return {}
}
return {
"data-label": attributes.label,
}
},
},
author: {
default: null,
parseHTML: (element) => element.getAttribute("data-author"),
renderHTML: (attributes) => {
if (!attributes.author) {
return {}
}
return {
"data-author": attributes.author,
}
},
},
type: {
default: null,
parseHTML: (element) => element.getAttribute("data-type"),
renderHTML: (attributes) => {
if (!attributes.type) {
return {}
}
return {
"data-type": attributes.type,
}
},
},
}
},
parseHTML() {
return [
{
tag: `span[data-type="${this.name}"]`,
},
]
},
renderHTML({ node, HTMLAttributes }) {
if (this.options.renderLabel !== undefined) {
console.warn(
"renderLabel is deprecated use renderText and renderHTML instead"
)
return [
"span",
mergeAttributes(
{ "data-type": this.name },
this.options.HTMLAttributes,
HTMLAttributes
),
this.options.renderLabel({
options: this.options,
node,
}),
]
}
const mergedOptions = { ...this.options }
mergedOptions.HTMLAttributes = mergeAttributes(
{ "data-type": this.name },
this.options.HTMLAttributes,
HTMLAttributes
)
const html = this.options.renderHTML({
options: mergedOptions,
node,
})
if (typeof html === "string") {
return [
"span",
mergeAttributes(
{ "data-type": this.name },
this.options.HTMLAttributes,
HTMLAttributes
),
html,
]
}
return html
},
renderText({ node }) {
if (this.options.renderLabel !== undefined) {
console.warn(
"renderLabel is deprecated use renderText and renderHTML instead"
)
return this.options.renderLabel({
options: this.options,
node,
})
}
return this.options.renderText({
options: this.options,
node,
})
},
addKeyboardShortcuts() {
return {
Backspace: () =>
this.editor.commands.command(({ tr, state }) => {
let isMention = false
const { selection } = state
const { empty, anchor } = selection
if (!empty) {
return false
}
state.doc.nodesBetween(anchor - 1, anchor, (node, pos) => {
if (node.type.name === this.name) {
isMention = true
tr.insertText(
this.options.deleteTriggerWithBackspace
? ""
: this.options.suggestion.char || "",
pos,
pos + node.nodeSize
)
return false
}
})
return isMention
}),
}
},
addProseMirrorPlugins() {
return [
Suggestion({
editor: this.editor,
...this.options.suggestion,
}),
]
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/mention/MentionExtension.ts
|
TypeScript
|
agpl-3.0
| 8,136
|
import tippy from "tippy.js"
import { VueRenderer } from "@tiptap/vue-3"
import { Mention } from "./MentionExtension"
import MentionList from "../../components/MentionList.vue"
export default function configureMention(options) {
return Mention.configure({
HTMLAttributes: {
class: "mention",
},
suggestion: getSuggestionOptions(options),
})
}
function getSuggestionOptions(options) {
return {
items: ({ query }) => {
return options
.filter((item) =>
item.label.toLowerCase().startsWith(query.toLowerCase())
)
.slice(0, 10)
},
render: () => {
let component
let popup
return {
onStart: (props) => {
component = new VueRenderer(MentionList, {
props,
editor: props.editor,
})
if (!props.clientRect) {
return
}
popup = tippy("body", {
getReferenceClientRect: props.clientRect,
appendTo: () => document.body,
content: component.element,
showOnCreate: true,
interactive: true,
trigger: "manual",
placement: "bottom-start",
})
},
onUpdate(props) {
component.updateProps(props)
if (!props.clientRect) {
return
}
popup[0].setProps({
getReferenceClientRect: props.clientRect,
})
},
onKeyDown(props) {
if (props.event.key === "Escape") {
popup[0].hide()
return true
}
return component.ref?.onKeyDown(props)
},
onExit() {
popup[0].destroy()
component.destroy()
},
}
},
}
}
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/mention/mention.js
|
JavaScript
|
agpl-3.0
| 1,763
|
import { mergeAttributes, Node } from "@tiptap/core"
export interface ParagraphOptions {
/**
* The HTML attributes for a paragraph node.
* @default {}
* @example { class: 'foo' }
*/
HTMLAttributes: Record<string, any>
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
paragraph: {
/**
* Toggle a paragraph
* @example editor.commands.toggleParagraph()
*/
setParagraph: () => ReturnType
}
}
}
/**
* This extension allows you to create paragraphs.
* @see https://www.tiptap.dev/api/nodes/paragraph
*/
export const Paragraph = Node.create<ParagraphOptions>({
name: "paragraph",
priority: 1000,
addOptions() {
return {
HTMLAttributes: {},
}
},
group: "block",
content: "inline*",
parseHTML() {
return [{ tag: "p" }]
},
renderHTML({ HTMLAttributes }) {
return [
"p",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
0,
]
},
addCommands() {
return {
setParagraph:
() =>
({ commands }) => {
return commands.setNode(this.name)
},
}
},
addKeyboardShortcuts() {
return {
"Mod-Alt-0": () => this.editor.commands.setParagraph(),
}
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/paragraph.ts
|
TypeScript
|
agpl-3.0
| 1,263
|
import { Editor, Extension, isNodeEmpty } from "@tiptap/core"
import { Node as ProsemirrorNode } from "@tiptap/pm/model"
import { Plugin, PluginKey } from "@tiptap/pm/state"
import { Decoration, DecorationSet } from "@tiptap/pm/view"
export interface PlaceholderOptions {
/**
* **The class name for the empty editor**
* @default 'is-editor-empty'
*/
emptyEditorClass: string
/**
* **The class name for empty nodes**
* @default 'is-empty'
*/
emptyNodeClass: string
/**
* **The placeholder content**
*
* You can use a function to return a dynamic placeholder or a string.
* @default 'Write something …'
*/
placeholder:
| ((PlaceholderProps: {
editor: Editor
node: ProsemirrorNode
pos: number
hasAnchor: boolean
}) => string)
| string
/**
* See https://github.com/ueberdosis/tiptap/pull/5278 for more information.
* @deprecated This option is no longer respected and this type will be removed in the next major version.
*/
considerAnyAsEmpty?: boolean
/**
* **Checks if the placeholder should be only shown when the editor is editable.**
*
* If true, the placeholder will only be shown when the editor is editable.
* If false, the placeholder will always be shown.
* @default true
*/
showOnlyWhenEditable: boolean
/**
* **Checks if the placeholder should be only shown when the current node is empty.**
*
* If true, the placeholder will only be shown when the current node is empty.
* If false, the placeholder will be shown when any node is empty.
* @default true
*/
showOnlyCurrent: boolean
/**
* **Controls if the placeholder should be shown for all descendents.**
*
* If true, the placeholder will be shown for all descendents.
* If false, the placeholder will only be shown for the current node.
* @default false
*/
includeChildren: boolean
}
/**
* This extension allows you to add a placeholder to your editor.
* A placeholder is a text that appears when the editor or a node is empty.
* @see https://www.tiptap.dev/api/extensions/placeholder
*/
export const Placeholder = Extension.create<PlaceholderOptions>({
name: "placeholder",
addOptions() {
return {
emptyEditorClass: "is-editor-empty",
emptyNodeClass: "is-empty",
placeholder: "Write something …",
showOnlyWhenEditable: true,
showOnlyCurrent: true,
includeChildren: false,
}
},
addProseMirrorPlugins() {
return [
new Plugin({
key: new PluginKey("placeholder"),
props: {
decorations: ({ doc, selection }) => {
const active =
this.editor.isEditable || !this.options.showOnlyWhenEditable
const { anchor } = selection
const decorations: Decoration[] = []
if (!active) {
return null
}
const isEmptyDoc = this.editor.isEmpty
doc.descendants((node, pos) => {
const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize
const isEmpty = !node.isLeaf && isNodeEmpty(node)
if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) {
const classes = [this.options.emptyNodeClass]
if (isEmptyDoc) {
classes.push(this.options.emptyEditorClass)
}
const decoration = Decoration.node(pos, pos + node.nodeSize, {
class: classes.join(" "),
"data-placeholder":
typeof this.options.placeholder === "function"
? this.options.placeholder({
editor: this.editor,
node,
pos,
hasAnchor,
})
: this.options.placeholder,
})
decorations.push(decoration)
}
return this.options.includeChildren
})
return DecorationSet.create(doc, decorations)
},
},
}),
]
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/placeholder.ts
|
TypeScript
|
agpl-3.0
| 4,160
|
import { Plugin, PluginKey } from "prosemirror-state"
export type UploadFnType = (image: File) => Promise<string>
export const getMediaPasteDropPlugin = (upload: UploadFnType) => {
return new Plugin({
key: new PluginKey("media-paste-drop"),
props: {
handlePaste(view, event) {
const items = Array.from(event.clipboardData?.items || [])
const { schema } = view.state
items.forEach((item) => {
const file = item.getAsFile()
const isImageOrVideo =
file?.type.indexOf("image") === 0 ||
file?.type.indexOf("video") === 0
if (isImageOrVideo) {
event.preventDefault()
if (upload && file) {
upload(file).then((src) => {
const node = schema.nodes.resizableMedia.create({
src,
"media-type":
file.type.indexOf("image") === 0 ? "img" : "video",
width: "800",
height: "400",
})
const transaction = view.state.tr.replaceSelectionWith(node)
view.dispatch(transaction)
})
}
} else {
const reader = new FileReader()
reader.onload = (readerEvent) => {
const node = schema.nodes.resizableMedia.create({
src: readerEvent.target?.result,
"media-type": "",
width: "800",
height: "400",
})
const transaction = view.state.tr.replaceSelectionWith(node)
view.dispatch(transaction)
}
if (!file) return
reader.readAsDataURL(file)
}
})
return false
},
handleDrop(view, event) {
const hasFiles =
event.dataTransfer &&
event.dataTransfer.files &&
event.dataTransfer.files.length
if (!hasFiles) {
return false
}
const imagesAndVideos = Array.from(
event.dataTransfer?.files ?? []
).filter(({ type: t }) => /image|video/i.test(t))
if (imagesAndVideos.length === 0) return false
event.preventDefault()
const { schema } = view.state
const coordinates = view.posAtCoords({
left: event.clientX,
top: event.clientY,
})
if (!coordinates) return false
imagesAndVideos.forEach(async (imageOrVideo) => {
const reader = new FileReader()
if (upload) {
const node = schema.nodes.resizableMedia.create({
src: await upload(imageOrVideo),
"media-type": imageOrVideo.type.includes("image")
? "img"
: "video",
})
const transaction = view.state.tr.insert(coordinates.pos, node)
view.dispatch(transaction)
} else {
reader.onload = (readerEvent) => {
const node = schema.nodes.resizableMedia.create({
src: readerEvent.target?.result,
"media-type": imageOrVideo.type.includes("image")
? "img"
: "video",
})
const transaction = view.state.tr.insert(coordinates.pos, node)
view.dispatch(transaction)
}
reader.readAsDataURL(imageOrVideo)
}
})
return true
},
},
})
}
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/resizenode/dropMedia.ts
|
TypeScript
|
agpl-3.0
| 3,481
|
export * from "./resizableMedia"
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/resizenode/index.ts
|
TypeScript
|
agpl-3.0
| 33
|
import { mergeAttributes, Node, nodeInputRule } from "@tiptap/core"
import { VueNodeViewRenderer } from "@tiptap/vue-3"
import ResizableMediaNodeView from "../../components/ResizableMediaNodeView.vue"
import { getMediaPasteDropPlugin, UploadFnType } from "./dropMedia.ts"
declare module "@tiptap/core" {
interface Commands<ReturnType> {
resizableMedia: {
/**
* Set media
*/
setMedia: (options: {
"media-type": "img" | "video"
src: string
alt?: string
title?: string
width?: string
height?: string
}) => ReturnType
}
}
}
export interface MediaOptions {
// inline: boolean, // we have floating support, so block is good enough
// allowBase64: boolean, // we're not going to allow this
HTMLAttributes: Record<string, any>
uploadFn: UploadFnType
}
export const IMAGE_INPUT_REGEX =
/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/
export const VIDEO_INPUT_REGEX = /!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\)/
export const ResizableMedia = Node.create<MediaOptions>({
name: "resizableMedia",
addOptions() {
return {
inline: false,
allowBase64: false,
HTMLAttributes: {},
}
},
inline: false,
group: "block",
draggable: true,
addAttributes() {
return {
src: {
default: null,
},
"media-type": {
default: null,
},
alt: {
default: null,
},
title: {
default: null,
},
width: {
default: "100%",
},
height: {
default: "auto",
},
dataAlign: {
default: null, // 'left' | 'center' | 'right'
},
dataFloat: {
default: null, // 'left' | 'right'
},
}
},
selectable: true,
parseHTML() {
return [
{
tag: 'img[src]:not([src^="data:"])',
getAttrs: (el) => ({
src: (el as HTMLImageElement).getAttribute("src"),
"media-type": "img",
}),
},
{
tag: "video",
getAttrs: (el) => ({
src: (el as HTMLVideoElement).getAttribute("src"),
"media-type": "video",
}),
},
]
},
renderHTML({ HTMLAttributes }) {
const { "media-type": mediaType } = HTMLAttributes
if (mediaType === "img") {
return [
"img",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
]
} else if (mediaType === "video") {
return [
"video",
{ controls: "true", style: "width: 100%", ...HTMLAttributes },
["source", HTMLAttributes],
]
}
if (!mediaType)
console.error(
"TiptapMediaExtension-renderHTML method: Media Type not set, going default with image"
)
return ["img", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]
},
addCommands() {
return {
setMedia:
(options) =>
({ commands }) => {
const { "media-type": mediaType } = options
if (mediaType === "img") {
return commands.insertContent({
type: this.name,
attrs: options,
})
} else if (mediaType === "video") {
return commands.insertContent({
type: this.name,
attrs: {
...options,
controls: "true",
},
})
}
if (!mediaType)
console.error(
"TiptapMediaExtension-setMedia: Media Type not set, going default with image"
)
return commands.insertContent({
type: this.name,
attrs: options,
})
},
}
},
addNodeView() {
return VueNodeViewRenderer(ResizableMediaNodeView)
},
addInputRules() {
return [
nodeInputRule({
find: IMAGE_INPUT_REGEX,
type: this.type,
getAttributes: (match) => {
const [, , alt, src, title] = match
return {
src,
alt,
title,
"media-type": "img",
}
},
}),
nodeInputRule({
find: VIDEO_INPUT_REGEX,
type: this.type,
getAttributes: (match) => {
const [, , src] = match
return {
src,
"media-type": "video",
}
},
}),
]
},
addProseMirrorPlugins() {
return [getMediaPasteDropPlugin(this.options.uploadFn)]
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/resizenode/resizableMedia.ts
|
TypeScript
|
agpl-3.0
| 4,486
|
import {
AlignLeft,
AlignRight,
AlignCenter,
AlignHorizontalJustifyStart,
AlignHorizontalJustifyEnd,
Trash,
} from "lucide-vue-next"
import { Component } from "vue"
interface ResizableMediaAction {
tooltip: string
icon: Component
action?: (updateAttributes: (o: Record<string, any>) => any) => void
isActive?: (attrs: Record<string, any>) => boolean
delete?: (d: () => void) => void
}
export const resizableMediaActions: ResizableMediaAction[] = [
{
tooltip: "Align left",
action: (updateAttributes) =>
updateAttributes({
dataAlign: "left",
dataFloat: null,
}),
icon: AlignLeft,
isActive: (attrs) => attrs.dataAlign === "left",
},
{
tooltip: "Align center",
action: (updateAttributes) =>
updateAttributes({
dataAlign: "center",
dataFloat: null,
}),
icon: AlignCenter,
isActive: (attrs) => attrs.dataAlign === "center",
},
{
tooltip: "Align right",
action: (updateAttributes) =>
updateAttributes({
dataAlign: "right",
dataFloat: null,
}),
icon: AlignRight,
isActive: (attrs) => attrs.dataAlign === "right",
},
{
tooltip: "Float left",
action: (updateAttributes) =>
updateAttributes({
dataAlign: null,
dataFloat: "left",
}),
icon: AlignHorizontalJustifyStart,
isActive: (attrs) => attrs.dataFloat === "left",
},
{
tooltip: "Float right",
action: (updateAttributes) =>
updateAttributes({
dataAlign: null,
dataFloat: "right",
}),
icon: AlignHorizontalJustifyEnd,
isActive: (attrs) => attrs.dataFloat === "right",
},
{
tooltip: "Delete",
icon: Trash,
delete: (deleteNode) => deleteNode(),
},
]
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/resizenode/resizableMediaMenuUtil.ts
|
TypeScript
|
agpl-3.0
| 1,769
|
import { VueRenderer } from "@tiptap/vue-3"
import {
Type,
Heading1,
Heading2,
Table,
Minus,
ArrowLeft,
ArrowRight,
ArrowUp,
ArrowDown,
ArrowUpWideNarrow,
} from "lucide-vue-next"
import tippy from "tippy.js"
import List from "../../icons/List.vue"
import OrderList from "../../icons/OrderList.vue"
import Check from "../../icons/Check.vue"
import Codeblock from "../../icons/Codeblock.vue"
import BlockQuote from "../../icons/BlockQuote.vue"
import Image from "../../icons/Image.vue"
import Video from "../../icons/Video.vue"
import PageBreak from "../../icons/PageBreak.vue"
import CommandsList from "../../components/suggestionList.vue"
import Mention from "../../icons/Mention.vue"
import emitter from "../../../../event-bus"
export default {
items: ({ query }) => {
return [
{
title: "Style",
type: "Section",
//disabled: () => false,
},
{
title: "Title",
icon: Type,
command: ({ editor, range }) => {
editor
.chain()
.focus()
.deleteRange(range)
.setNode("heading", { level: 1 })
.run()
},
disabled: (editor) => editor.isActive("table"),
},
{
title: "Subtitle",
icon: Heading1,
command: ({ editor, range }) => {
editor
.chain()
.focus()
.deleteRange(range)
.setNode("heading", { level: 2 })
.run()
},
disabled: (editor) => editor.isActive("table"),
},
{
title: "Heading",
icon: Heading2,
command: ({ editor, range }) => {
editor
.chain()
.focus()
.deleteRange(range)
.setNode("heading", { level: 3 })
.run()
},
disabled: (editor) => editor.isActive("table"),
},
{
title: "Ordered List",
icon: OrderList,
command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).toggleOrderedList().run()
},
disabled: (editor) => editor.isActive("bulletList"),
},
{
title: "Bullet List",
icon: List,
command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).toggleBulletList().run()
},
disabled: (editor) => editor.isActive("bulletList"),
},
{
title: "Task List",
icon: Check,
command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).toggleTaskList().run()
},
disabled: (editor) => editor.isActive("bulletList"),
},
{
title: "Code Block",
icon: Codeblock,
command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).toggleCodeBlock().run()
},
disabled: (editor) => editor.isActive("table"),
},
{
title: "Focus Block",
icon: BlockQuote,
command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).toggleBlockquote().run()
},
disabled: (editor) => editor.isActive("table"),
},
{
title: "Mention",
icon: Mention,
command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).insertContent("@").run()
},
disabled: () => false,
},
{
title: "Insert",
type: "Section",
},
{
title: "Table",
icon: Table,
command: ({ editor, range }) => {
editor
.chain()
.focus()
.deleteRange(range)
.insertTable({ rows: 3, cols: 3, withHeaderRow: true })
.run()
},
disabled: (editor) => editor.isActive("table"),
},
{
title: "Add Column",
icon: ArrowRight,
command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).addColumnAfter().run()
},
disabled: (editor) => !editor.isActive("table"),
},
{
title: "Add Row",
icon: ArrowDown,
command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).addRowAfter().run()
},
disabled: (editor) => !editor.isActive("table"),
},
{
title: "Image",
icon: Image,
command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).run()
emitter.emit("addImage")
},
disabled: (editor) => editor.isActive("table"),
},
{
title: "Video",
icon: Video,
command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).run()
emitter.emit("addVideo")
},
disabled: (editor) => editor.isActive("table"),
},
{
title: "Horizontal rule",
icon: Minus,
command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).setHorizontalRule().run()
},
disabled: (editor) => editor.isActive("table"),
},
{
title: "Page Break",
icon: PageBreak,
command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).setPageBreak().run()
},
disabled: (editor) => editor.isActive("table"),
},
].filter((item) => item.title.toLowerCase().includes(query.toLowerCase()))
},
render: () => {
let component
let popup
return {
onStart: (props) => {
component = new VueRenderer(CommandsList, {
props,
popup,
editor: props.editor,
})
if (!props.clientRect) {
return
}
popup = tippy("body", {
getReferenceClientRect: props.clientRect,
appendTo: () => document.body,
content: component.element,
showOnCreate: true,
interactive: true,
trigger: "manual",
placement: "bottom-start",
})
},
onUpdate(props) {
component.updateProps(props)
component.updateProps(popup)
if (!props.clientRect) {
return
}
popup[0].setProps({
getReferenceClientRect: props.clientRect,
})
},
onKeyDown(props) {
if (props.event.key === "Escape") {
popup[0].hide()
return true
}
return component.ref?.onKeyDown(props)
},
onExit() {
popup[0].destroy()
component.destroy()
},
}
},
}
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/suggestion/suggestion.js
|
JavaScript
|
agpl-3.0
| 6,597
|
import { Extension } from "@tiptap/core"
import Suggestion from "@tiptap/suggestion"
export default Extension.create({
name: "slash-commands",
addOptions() {
return {
suggestion: {
char: "/",
command: ({ editor, range, props }) => {
props.command({ editor, range })
},
},
}
},
addProseMirrorPlugins() {
return [
Suggestion({
editor: this.editor,
...this.options.suggestion,
}),
]
},
})
|
2302_79757062/drive
|
frontend/src/components/DocEditor/extensions/suggestion/suggestionExtension.js
|
JavaScript
|
agpl-3.0
| 489
|