Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • oss/minerva/grapesjs-project-manager
1 result
Show changes
Commits on Source (2)
Showing with 44058 additions and 55 deletions
{
"presets": [
"@babel/preset-env"
],
"plugins": [
"@babel/plugin-proposal-object-rest-spread"
]
}
\ No newline at end of file
.DS_Store
private/
/locale
node_modules/
*.log
_index.html
dist/
stats.json
##################### IDE / Tools ###
# @see https://github.com/github/gitignore/
# PHPUnit
.phpunit.result.cache
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
.cache
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Cloud9 IDE - http://c9.io
.c9revisions
.c9
##Exclipse
.metadata
#bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
#local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
.apt_generated_test/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
# Uncomment this line if you wish to ignore the project description file.
# Typically, this file would be tracked if it contains build/dependency configurations:
#.project
##Kate
# Swap Files #
.*.kate-swp
.swp.*
## KDEDevelop
*.kdev4
.kdev4/
## LibreOffice
# LibreOffice locks
.~lock.*#
### LINUX
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
## Patches
*.orig
*.rej
# Private key
*.ppk
## Sublime
# Cache files for Sublime Text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
# Workspace files are user-specific
*.sublime-workspace
# Project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using Sublime Text
# *.sublime-project
# SFTP configuration file
sftp-config.json
sftp-config-alt*.json
# Package control specific files
Package Control.last-run
Package Control.ca-list
Package Control.ca-bundle
Package Control.system-ca-bundle
Package Control.cache/
Package Control.ca-certs/
Package Control.merged-ca-bundle
Package Control.user-ca-bundle
oscrypto-ca-bundle.crt
bh_unicode_properties.cache
# Sublime-github package stores a github token in this file
# https://packagecontrol.io/packages/sublime-github
GitHub.sublime-settings
## VIM
# Swap
[._]*.s[a-v][a-z]
!*.svg # comment out if you don't need vector files
[._]*.sw[a-p]
[._]s[a-rt-v][a-z]
[._]ss[a-gi-z]
[._]sw[a-p]
# Session
Session.vim
Sessionx.vim
# Temporary
.netrwhist
# Auto-generated tag files
tags
# Persistent undo
[._]*.un~
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# gitignore template for AWS Serverless Application Model project
# website: https://docs.aws.amazon.com/serverless-application-model
# Ignore build folder
.aws-sam/
# Netbeans
**/nbproject/private/
**/nbproject/Makefile-*.mk
**/nbproject/Package-*.bash
build/
nbbuild/
nbdist/
.nb-gradle/
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
## GOLANG
go.work
webpack.config.js
*.iml
Makefile
.babelrc
.eslintrc.js
.vimspector.json
*.tgz
index.html
/scripts/
\ No newline at end of file
Copyright (C) 2022 schukai GmbH
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
MIT License
Copyright (c) 2021-current Grapesjs Template Manager
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
\ No newline at end of file
#############################################################################################
#############################################################################################
##
## PROJECT-DEFINITIONS
##
#############################################################################################
#############################################################################################
COPYRIGHT_TEXT := © schukai GmbH, Released under the AGPL 3.0 License.
#############################################################################################
#############################################################################################
##
## more general block with standard definitions
##
#############################################################################################
#############################################################################################
# get Makefile directory name: http://stackoverflow.com/a/5982798/376773
THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd)/
THIS_MAKEFILE:=$(THIS_DIR)$(THIS_MAKEFILE_PATH)
# colors
BLACK := $(shell tput -Txterm setaf 0)
RED := $(shell tput -Txterm setaf 1)
GREEN := $(shell tput -Txterm setaf 2)
YELLOW := $(shell tput -Txterm setaf 3)
LIGHTPURPLE := $(shell tput -Txterm setaf 4)
PURPLE := $(shell tput -Txterm setaf 5)
BLUE := $(shell tput -Txterm setaf 6)
WHITE := $(shell tput -Txterm setaf 7)
RESET := $(shell tput -Txterm sgr0)
INFO := $(GREEN)
COMMENT := $(YELLOW)
# Output control and standard outputs
MARKER := $(BLUE)[+]$(RESET)
ERRORMARKER := $(RED)[-]$(RESET)
## Deactivate the QUIET mode by overwriting the value with space
ifndef DEBUG
QUIET = @
else
QUIET =
endif
ifndef DONTOPENBROWSER
OPENBROWSER = true
else
OPENBROWSER = false
endif
ECHO := @echo
ECHOMARKER := @echo "$(MARKER) $0"
ECHOERRORMARKER := @echo "$(ERRORMARKER) $0"
# Use bash instead of sh
## Sets the shell used
SHELL = bash
# path and binaries
AWK := awk
CP := cp
CD := cd
KILL := /bin/kill
M4 := m4
MV := mv
RM := rm -f
MKDIR := mkdir -p
SED := sed
FIND := find
SORT := sort
TOUCH := touch
WGET := wget
CHMOD := chmod
RSYNC := rsync
DOCKER := docker
NPX := npx
AWS := aws
XARGS := xargs
GREP := grep
NPM := npm
make := make
GIT := git
NPX := npx
NODE := node
CAT := cat
ECHO := echo
# Executable Programs the Installed be have to
EXECUTABLES = $(AWK) $(CP) $(KILL) $(M4) $(MV) rm mkdir $(SED) $(SORT) $(TOUCH) $(WGET) $(CHMOD) $(NPX) $(FIND) $(XARGS) $(GREP) $(NPM) $(GIT) $(NPX) $(ECHO) $(CAT);
K := $(foreach exec,$(EXECUTABLES),\
$(if $(shell which $(exec)),some string,$(error "Missing $(exec) in PATH; please install")))
#############################################################################################
#############################################################################################
##
## DEFAULT-TARGETS
##
#############################################################################################
#############################################################################################
# @see .PHONY https://www.gnu.org/software/make/manual/html_node/Phony-Targets.html#Phony-Targets
.DEFAULT_GOAL := help
.PHONY: print
print:
$(ECHO) "THIS_MAKEFILE: $(THIS_MAKEFILE)"
$(ECHO) "THIS_MAKEFILE_PATH: $(THIS_MAKEFILE_PATH)"
$(ECHO) "THIS_DIR: $(THIS_DIR)"
# Add a comment to the public targets so that it appears
# in this help Use two # characters for a help comment
.PHONY: help
help:
@printf "${COMMENT}Usage:${RESET}\n"
@printf " make [target] [arg=\"val\"...]\n\n"
@printf "${COMMENT}Available targets:${RESET}\n"
@awk '/^[a-zA-Z\-_0-9\.@]+:/ { \
helpMessage = match(lastLine, /^## (.*)/); \
if (helpMessage) { \
helpCommand = substr($$1, 0, index($$1, ":")); \
helpMessage = substr(lastLine, RSTART + 3, RLENGTH); \
printf " ${INFO}%-22s${RESET} %s\n", helpCommand, helpMessage; \
} \
} \
{ lastLine = $$0 }' $(MAKEFILE_LIST)
@printf "\n${COMMENT}Available arguments:${RESET}\n"
@printf "\n ${INFO}DONTOPENBROWSER${RESET} disable open chrome"
@printf "\n ${INFO}NEXTVERSION${RESET} see target release => 0 – major, 1 – minor (default), 2 – patch\n"
@awk '/^(([a-zA-Z\-_0-9\.@]+)\s=)/ { \
helpMessage = match(lastLine, /^## (.*)/); \
if (helpMessage) { \
helpMessage = substr(lastLine, RSTART + 3, RLENGTH); \
printf " ${INFO}%-22s${RESET} %s (Default: %s)\n", $$1, helpMessage, $$3; \
} \
} \
{ lastLine = $$0 }' $(MAKEFILE_LIST)
@printf "\n"
.PHONY: variables
## Print all Variables
variables:
@$(foreach v, $(.VARIABLES), $(if $(filter file,$(origin $(v))), $(info $(INFO)$(v)$(RESET)=$($(v))$(RESET))))
#############################################################################################
#############################################################################################
##
## DIRECTORIES
##
#############################################################################################
#############################################################################################
SCRIPT_PATH := $(THIS_DIR)scripts/
PACKAGE_DIR := $(THIS_DIR)
PACKAGE_DIST_DIR := $(THIS_DIR)dist/
PACKAGE_DIST_FILE := $(PACKAGE_DIST_DIR)@schukai/grapesjs-blocks-bootstrap5.min.js
PACKAGE_SOURCE_DIR := $(THIS_DIR)source/
PACKAGE_SOURCE_FILES := $(shell find $(PACKAGE_SOURCE_DIR) -name '*.js')
PACKAGE_RELATIVE_SOURCE_FILES := $(shell find $(PACKAGE_SOURCE_DIR) -name '*.js' -exec realpath --relative-to $(THIS_DIR) {} \; )
PACKAGE_VERSION := $(shell jq -r ".version" $(PACKAGE_DIR)package.json)
#############################################################################################
#############################################################################################
##
## GIT-TARGETS
##
#############################################################################################
#############################################################################################
## Git Commit Message for git-push
MESSAGE := current status
.PHONY: git-branch
## create new branch (use TAG-Variable)
git-branch:
ifeq (, $(shell command -v uuidgen))
$(error "No uuidgen in PATH, consider doing apt-get install uuidgen")
endif
$(QUIET) export BRANCH="$(shell uuidgen --random)" ; \
$(GIT) checkout -b $${BRANCH} && \
RESULT=$$($(GIT) push origin $$BRANCH 2>&1) && \
RESULT2=$$($(GIT) branch --set-upstream-to=origin/$$BRANCH $$BRANCH) && \
GITLABURL=$$(echo "$$RESULT" | tr '\n' '\#' | grep -o 'remote\:\s*https:\/\/gitlab\.schukai\.com[^ ]*' | cut -d " " -f2-9 | sed -e 's/^[ \t]*//') && \
if $(OPENBROWSER) ; then google-chrome --profile-directory="Default" $$GITLABURL ; fi
.PHONY: git-to-master
## git checkout master, fetch and merge
git-to-master:
$(GIT) checkout master && $(GIT) fetch -pP && $(GIT) merge
.PHONY: git-push-to-server
## git push changes to server
git-push-to-server:
$(GIT) add -A
$(GIT) commit -m"$(MESSAGE)"
$(GIT) push
.PHONY: git-push
## git create branch and push changes to server
git-push: git-branch git-push-to-server
.PHONY: git-tag
## git create version tag
git-tag:
$(GIT) tag -a "$(PACKAGE_VERSION)" -m "release $(PACKAGE_VERSION)"
#############################################################################################
#############################################################################################
##
## NODE-DEFINITIONS
##
#############################################################################################
#############################################################################################
NODE_MODULES_DIR := $(THIS_DIR)node_modules/
NODE_MODULES_BIN_DIR := $(NODE_MODULES_DIR).bin/
WEBPACK := $(NODE_MODULES_BIN_DIR)webpack
BABEL := $(NODE_MODULES_BIN_DIR)babel
UGLIFYJS := $(NODE_MODULES_BIN_DIR)uglifyjs
$(NODE_MODULES_DIR): $(THIS_DIR)package.json
$(QUIET) $(NPM) install
$(QUIET) $(RM) node_modules/.modified
$(QUIET) $(TOUCH) -m node_modules/.modified
#############################################################################################
#############################################################################################
##
## DEFAULT-DEFINITIONS
##
#############################################################################################
#############################################################################################
.PHONY: clean
## clean
clean:
$(QUIET) $(RM) --recursive $(THIS_DIR)dist/
$(PACKAGE_DIST_FILE): $(PACKAGE_SOURCE_FILES)
$(QUIET) $(NPM) run build
.PHONY: build
## create all packages
build: $(NODE_MODULES_DIR) $(PACKAGE_DIST_FILE)
.PHONY: dev
## start dev server
dev: $(NODE_MODULES_DIR)
$(QUIET) $(NPM) run start
FILEMARKER:=\#GITIGNORE-START
$(PACKAGE_DIR).npmignore: $(PACKAGE_DIR).gitignore
$(QUIET) $(SED) -i -n '/$(FILEMARKER)/q;p' $(PACKAGE_DIR).npmignore
$(QUIET) $(ECHO) "$(FILEMARKER)" >> $(PACKAGE_DIR).npmignore
$(QUIET) $(ECHO) "" >> $(PACKAGE_DIR).npmignore
$(QUIET) $(ECHO) "" >> $(PACKAGE_DIR).npmignore
$(QUIET) $(CAT) $(PACKAGE_DIR).gitignore >> $(PACKAGE_DIR).npmignore
.PHONY: release
## release repos with new version (use NEXTVERSION)
release:
$(ECHOMARKER) "release"
$(QUIET) $(SCRIPT_PATH)increase-version.sh "$(PACKAGE_DIR)package.json" "$(PACKAGE_VERSION)" "$(NEXTVERSION)"
$(QUIET) $(MAKE) clean
$(QUIET) $(MAKE) build
$(QUIET) $(MAKE) npm-publish
$(QUIET) touch $(THIS_DIR)package.json
.PHONY: npm-publish
## publish library to npm
npm-publish: build $(PACKAGE_DIR).npmignore
$(ECHOMARKER) "publish"
$(QUIET) $(CD) $(THIS_DIR) ; \
$(NPM) pack ; \
$(CD) -
# $(NPM) publish --access public ; \
# grapesjs-project-manager
# Grapesjs Project Manager
> Requires GrapesJS v0.17.3 or higher.
Project, template and page manager for grapesjs. This version makes use of the [`PageManager`](https://github.com/artf/grapesjs/pull/3411) and has different plugin and package name, the previous version which doesn't make use of the `PageManager` can be found [here](https://github.com/Ju99ernaut/grapesjs-template-manager/tree/template-manager).
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
| Project | Project settings |
| ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| ![Screenshot (224)](https://user-images.githubusercontent.com/48953676/130074718-0e50d99a-d004-41e0-890c-66f05175e45c.png) | ![Screenshot (226)](https://user-images.githubusercontent.com/48953676/130074800-075eab50-3059-493d-afa7-0b9f8af9fdf6.png) |
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
| Pages | Page settings |
| ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| ![Screenshot (225)](https://user-images.githubusercontent.com/48953676/130074843-81c120f9-37a0-4ee1-b8d4-019a16de6a46.png) | ![Screenshot (227)](https://user-images.githubusercontent.com/48953676/130074992-12a1774a-0a85-4e4f-8a14-1c95e0a7a7b6.png) |
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
### HTML
```html
<link href="https://unpkg.com/grapesjs/dist/css/grapes.min.css" rel="stylesheet">
<link href="https://unpkg.com/grapesjs-project-manager/dist/grapesjs-project-manager.min.css" rel="stylesheet">
<script src="https://unpkg.com/grapesjs"></script>
<script src="https://unpkg.com/grapesjs-project-manager"></script>
<div id="gjs"></div>
```
cd existing_repo
git remote add origin https://gitlab.schukai.com/oss/minerva/grapesjs-project-manager.git
git branch -M master
git push -uf origin master
### JS
```js
const editor = grapesjs.init({
container: '#gjs',
height: '100%',
fromElement: true,
pageManager: true, // This should be set to true
storageManager: {
type: 'indexeddb',
// ...
},
plugins: ['grapesjs-project-manager'],
});
// Running commands from panels
const pn = editor.Panels;
pn.addButton('options', {
id: 'open-templates',
className: 'fa fa-folder-o',
attributes: {
title: 'Open projects and templates'
},
command: 'open-templates', //Open modal
});
pn.addButton('views', {
id: 'open-pages',
className: 'fa fa-file-o',
attributes: {
title: 'Take Screenshot'
},
command: 'open-pages',
togglable: false
});
```
## Integrate with your tools
### CSS
- [ ] [Set up project integrations](https://gitlab.schukai.com/oss/minerva/grapesjs-project-manager/-/settings/integrations)
```css
body, html {
margin: 0;
height: 100%;
}
```
## Collaborate with your team
## Summary
* Plugin name: `grapesjs-project-manager`
* Commands
* `open-templates`
* `open-pages`
* `open-settings`
* `get-uuidv4`
* `take-screenshot`
* `save-as-template`
* `delete-template`
* Storages
* `indexeddb`
* `firestore`
* `rest-api`
## Options
| Option | Description | Default |
| --------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| `dbName` | Database name | `gjs` |
| `objectStoreName` | Collection name | `templates` |
| `loadFirst` | Load first template in storage | `true` |
| `customLoad` | Use custom onload function(skips default onload steps),`(ed, cs) => ...` | `false` |
| `components` | Default components since`fromElement` is not supported | `undefined` |
| `style` | Default style since`fromElement` is not supported | `undefined` |
| `indexeddbVersion` | IndexedDB schema version | `5` |
| `onDelete` | On successful template deletion | `Function(Check source)` |
| `onDeleteError` | On error template deletion | `Function(Check source)` |
| `onScreenShotError` | On error capturing screenshot | `Function(Check source)` |
| `quality` | Generated screenshot quality | `.01` |
| `mdlTitle` | Modal title | `Project Manager` |
| `apiKey` | `Firebase` API key | `` |
| `authDomain` | `Firebase` Auth domain | `` |
| `projectId` | `Cloud Firestore` project ID | `` |
| `firebaseConfig` | Extra firebase app credentials | `{}` |
| `enableOffline` | Enable`Firestore` support for offline data persistence | `true` |
| `settings` | `Firestore` database settings | `{ timestampsInSnapshots: true }` |
| `uuidInPath` | Add uuid as path parameter on store for`rest-api`(useful for validation) | `true` |
| `size` | Display estimated project sizes | `true` |
| `currentPageOpen` | Send feedback when open is clicked on current page | `check source` |
| `ì18n` | I18n object containing language[more info](https://grapesjs.com/docs/modules/I18n.html#configuration) | `{}` |
* Setting `loadFirst` to `false` prevents overwritting the contents of the editor with the contents of the first template in storage.
* Only use options for `Firebase` when using `Cloud Firestore` storage.
* `dbName` and `indexeddbVersion` only apply to `indexddb` storage.
* `objectStoreName` acts as collection name for both `firestore` and ` indexeddb`.
* When `uuidInPath` is set to `false` the store request will be `http://endpoint/store/` instead of `http://endpoint/store/{uuid}`
## Local/IndexedDB
```js
window.editor = grapesjs.init({
container: '#gjs',
// ...
pageManager: true,
storageManager: {
type: 'indexeddb'
},
plugins: ['grapesjs-project-manager'],
pluginsOpts: {
'grapesjs-project-manager': { /* Options */ }
}
});
```
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Firestore
## Test and Deploy
> Tested on firebase v8+. Firebase v9+ not yet supported.
Use the built-in continuous integration in GitLab.
Configure firestore access rules for your app.
Add libraries to `head` of document:
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
```html
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.3.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.3.1/firebase-firestore.js"></script>
```
***
Add credentials:
```js
window.editor = grapesjs.init({
container: '#gjs',
// ...
pageManager: true,
storageManager: {
type: 'firestore'
},
plugins: ['grapesjs-project-manager'],
pluginsOpts: {
'grapesjs-project-manager': {
// Firebase API key
apiKey: 'FIREBASE_API_KEY',
// Firebase Auth domain
authDomain: 'app-id-00a00.firebaseapp.com',
// Cloud Firestore project ID
projectId: 'app-id-00a00',
}
}
});
```
# Editing this README
## Remote/REST-API
Example backend https://github.com/Ju99ernaut/gjs-api
```js
window.editor = grapesjs.init({
container: '#gjs',
// ...
pageManager: true,
storageManager: {
type: 'rest-api',
// the URIs below can be the same depending on your API design
urlStore: 'https://endpoint/store/',// POST
urlLoad: 'https://endpoint/load/',// GET
urlDelete: 'https://endpoint/delete/',// DELETE
params: { _some_token: '...' },
headers: { Authorization: 'Basic ...' }
},
plugins: ['grapesjs-project-manager'],
pluginsOpts: {
'grapesjs-project-manager': { /* options */ }
}
});
```
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
The backend schema can be something like:
`GET` `https://api/templates/` load all templates
Returns
```json
[
{
"id": "UUIDv4",
"name": "Page name",
"template": false,
"thumbnail": "",
"description": "No description",
"gjs-assets": "[]",
"gjs-pages": "[]",
"gjs-styles": "[]",
"updated_at": ""
}
]
```
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
`POST` `https://api/templates/{idx: UUIDv4}` store template
Expects
```json
{
"id": "UUIDv4",
"name": "Page name",
"template": false,
"thumbnail": "",
"description": "No description",
"gjs-assets": "[]",
"gjs-pages": "[]",
"gjs-styles": "[]",
"updated_at": ""
}
```
## Name
Choose a self-explaining name for your project.
`GET` `https://api/templates/{idx: UUIDv4}` load template
Returns
```json
{
"id": "UUIDv4",
"name": "Page name",
"template": false,
"thumbnail": "",
"description": "No description",
"gjs-assets": "[]",
"gjs-pages": "[]",
"gjs-styles": "[]",
"updated_at": ""
}
```
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
`DELETE` `https://api/templates/{idx: UUIDv4}` delete template
Which would have the following setup:
```js
window.editor = grapesjs.init({
container: '#gjs',
// ...
storageManager: {
type: 'rest-api',
// the URIs below can be the same depending on your API design
urlStore: 'https://api/templates/',// POST
urlLoad: 'https://api/templates/',// GET
urlDelete: 'https://api/templates/',// DELETE
},
plugins: ['grapesjs-template-manager'],
pluginsOpts: {
'grapesjs-template-manager': { /* options */ }
}
});
```
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
All the fields are generated from the editor so you just need to setup your API to receive and return data in that format. I'd recommend you check the network tab so you get a more accurate format for the payloads.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Download
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
* CDN
* `https://unpkg.com/grapesjs-project-manager`
* NPM
* `npm i grapesjs-project-manager`
* GIT
* `git clone https://github.com/Ju99ernaut/grapesjs-template-manager.git`
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
Directly in the browser
```html
<link href="https://unpkg.com/grapesjs/dist/css/grapes.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/grapesjs-project-manager/dist/grapesjs-project-manager.min.css" rel="stylesheet">
<script src="https://unpkg.com/grapesjs"></script>
<script src="path/to/grapesjs-project-manager.min.js"></script>
<div id="gjs"></div>
<script type="text/javascript">
var editor = grapesjs.init({
container: '#gjs',
// ...
pageManager: true,
storageManager: {
type: 'indexeddb',
// ...
},
plugins: ['grapesjs-project-manager'],
pluginsOpts: {
'grapesjs-project-manager': { /* options */ }
}
});
</script>
```
Modern javascript
```js
import grapesjs from 'grapesjs';
import plugin from 'grapesjs-project-manager';
import 'grapesjs/dist/css/grapes.min.css';
import 'grapesjs-project-manager/dist/grapesjs-project-manager.min.css';
const editor = grapesjs.init({
container : '#gjs',
// ...
pageManager: true,
storageManager: {
type: 'indexeddb',
// ...
},
plugins: [plugin],
pluginsOpts: {
[plugin]: { /* options */ }
}
// or
plugins: [
editor => plugin(editor, { /* options */ }),
],
});
```
## Development
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
Clone the repository
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
```sh
$ git clone https://github.com/Ju99ernaut/grapesjs-template-manager.git
$ cd grapesjs-template-manager
```
Install dependencies
```sh
$ npm i
```
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
Build css or watch scss
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
```sh
$ npm run build:css
```
`OR`
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
```
$ npm run watch:scss
```
Start the dev server
```sh
$ npm start
```
Build the source
```sh
$ npm run build
```
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
[AGPL 3.0](https://www.gnu.org/licenses/agpl-3.0.de.html)
This is a fork from [github.com/Ju99ernaut/grapesjs-template-manager](https://github.com/Ju99ernaut/grapesjs-template-manager)
licensed under the MIT License by Brendon Ngirazi.
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/source" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>GrapesJS Project Manager</title>
<link href="https://unpkg.com/grapesjs/dist/css/grapes.min.css" rel="stylesheet">
<script src="https://unpkg.com/grapesjs"></script>
<script src="@schukai/grapesjs-project-manager.min.js"></script>
<style>
body,
html {
height: 100%;
margin: 0;
}
</style>
</head>
<body>
<div id="gjs" style="height:0px; overflow:hidden">
<div style="margin:100px 100px 25px; padding:25px; font:caption">
This is a demo content from index.html. You can use this template file for
development purpose.
</div>
</div>
<script type="text/javascript">
var editor = grapesjs.init({
height: '100%',
pageManager: {},
storageManager: {
type: 'indexeddb'
},
showOffsets: 1,
noticeOnUnload: 0,
container: '#gjs',
fromElement: true,
showDevices: false,
plugins: ['@schukai/grapesjs-project-manager'],
pluginsOpts: {
'@schukai/grapesjs-project-manager': {}
},
});
editor.Panels.addButton('options', {
id: 'open-templates',
className: 'fa fa-folder-o',
attributes: {
title: 'Open projects and templates'
},
command: 'open-templates', //Open modal
});
editor.Panels.addButton('views', {
id: 'open-pages',
className: 'fa fa-file-o',
attributes: {
title: 'Open Pages'
},
command: 'open-pages',
togglable: false
});
editor.BlockManager.add('demo', {
label: '<h1>Headline</h1><p>Lorem Ipsum</p>',
content: `
<h1>Headline</h1><p>Lorem Ipsum</p>
`,
category: 'demo',
attributes: {
title: 'Insert h1 block'
}
});
window.editor = editor;
</script>
</body>
</html>
\ No newline at end of file
This diff is collapsed.
{
"name": "@schukai/grapesjs-project-manager",
"version": "1.0.0",
"description": "Grapesjs Project Manager",
"main": "dist/@schukai/grapesjs-project-manager.min.js",
"repository": {
"type": "git",
"url": "https://gitlab.schukai.com/oss/minerva/grapesjs-project-manager.git"
},
"scripts": {
"lint": "eslint source",
"build": "webpack --env production",
"build-dev": "npm run && webpack --env production",
"start": "webpack-cli serve --mode development --progress",
"postinstall": "npm-install-peers"
},
"keywords": [
"grapesjs",
"plugin"
],
"devDependencies": {
"grapesjs-cli": "^1.0.14",
"sass": "^1.32.8",
"@babel/core": "^7.18.2",
"@babel/plugin-proposal-object-rest-spread": "^7.18.0",
"@babel/preset-env": "^7.18.2",
"@webpack-cli/init": "^1.1.3",
"babel-loader": "^8.2.5",
"eslint": "^8.16.0",
"html-webpack-plugin": "^5.5.0",
"raw-loader": "^4.0.2",
"terser-webpack-plugin": "^5.3.1",
"webpack": "^5.72.1",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.9.0",
"npm": "^8.11.0",
"npm-install-peers": "^1.2.2"
},
"author": "schukai GmbH, Brendon Ngirazi",
"license": "AGPL 3.0",
"dependencies": {
"dom-to-image": "^2.6.0"
},
"peerDependencies": {
"grapesjs": "0.x"
}
}
#!/bin/bash
### Increments the part of the string
## $1: version itself
## $2: number of part: 0 – major, 1 – minor, 2 – patch
increment_version() {
local delimiter=.
local array=($(echo "$1" | tr $delimiter '\n'))
array[$2]=$((array[$2] + 1))
if [ $2 -lt 2 ]; then array[2]=0; fi
if [ $2 -lt 1 ]; then array[1]=0; fi
echo $(
local IFS=$delimiter
echo "${array[*]}"
)
}
JSON="${1}"
VERSION="${2}"
MODE="${3:-1}"
jq '.version="'$(increment_version "${VERSION}" "${MODE}")'"' "${JSON}" > "${JSON}.new"
rm "${JSON}"
mv "${JSON}.new" "${JSON}"
import domtoimage from 'dom-to-image';
export default (editor, opts = {}) => {
const cm = editor.Commands;
const cs = editor.Storage.getCurrentStorage();
const mdl = editor.Modal;
const pfx = editor.getConfig('stylePrefix');
const mdlClass = `${pfx}mdl-dialog-tml`;
const mdlClassMd = `${pfx}mdl-dialog-md`;
editor.domtoimage = domtoimage;
cm.add('open-templates', {
run(editor, sender) {
const mdlDialog = document.querySelector(`.${pfx}mdl-dialog`);
mdlDialog.classList.add(mdlClass);
sender?.set && sender.set('active');
mdl.setTitle(opts.mdlTitle);
mdl.setContent(editor.TemplateManager.render());
mdl.open();
mdl.getModel().once('change:open', () => {
mdlDialog.classList.remove(mdlClass);
});
}
});
cm.add('open-settings', {
run(editor, sender) {
const mdlDialog = document.querySelector(`.${pfx}mdl-dialog`);
mdlDialog.classList.add(mdlClassMd);
sender?.set && sender.set('active');
mdl.setTitle(opts.mdlTitle);
mdl.setContent(editor.SettingsApp.render());
mdl.open();
mdl.getModel().once('change:open', () => {
mdlDialog.classList.remove(mdlClassMd);
});
}
});
cm.add('open-pages', {
run(editor) {
editor.PagesApp.showPanel();
},
stop(editor) {
editor.PagesApp.hidePanel();
}
})
//some magic from gist.github.com/jed/982883
const uuidv4 = () => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
const getJpeg = (node, opts = {}, clb, clbErr) => {
domtoimage.toJpeg(node, opts)
.then(dataUrl => clb && clb(dataUrl))
.catch(err => clbErr && clbErr(err))
};
cm.add('get-uuidv4', () => {
if (crypto) {
return crypto.randomUUID ? crypto.randomUUID() : uuidv4();
}
});
cm.add('take-screenshot', (editor, s, options = { clb(d) { return d } }) => {
const el = editor.getWrapper().getEl();
getJpeg(el, {
quality: opts.quality,
height: 1000,
'cacheBust': true,
style: {
'background-color': 'white',
...editor.getWrapper().getStyle()
},
}, options.clb, opts.onScreenshotError);
});
cm.add('save-as-template', editor => {
cs.setIsTemplate(true);
editor.store();
});
cm.add('delete-template', editor => {
cs.delete(opts.onDelete, opts.onDeleteError);
});
}
\ No newline at end of file
export const storageIDB = 'indexeddb',
storageRemote = 'rest-api',
storageFireStore = 'firestore';
\ No newline at end of file
import TemplateManager, { PagesApp, SettingsApp } from './manager';
import commands from './commands';
import storage from './storage';
import en from './locale/en';
export default (editor, opts = {}) => {
const options = {
...{
// default options
// Database name
dbName: 'gjs',
// Collection name
objectStoreName: 'projects',
// Load first template in storage
loadFirst: true,
// Custom load
customLoad: false,
// Add uuid as path parameter to store path for rest-api
uuidInPath: true,
// Indexeddb version schema
indexeddbVersion: 5,
// When template or page is deleted
onDelete(res) {
console.log('Deleted:', res)
},
// When error onDelete
onDeleteError(err) {
console.log(err)
},
// On screenshot error
onScreenshotError(err) {
console.log(err)
},
// Quality of screenshot image from 0 to 1, more quality increases the image size
quality: .01,
// Content for templates modal title
mdlTitle: 'Project Manager',
// Show when no pages yet pages
nopages: '<div style="display:flex;align-items:center;padding:50px;margin:auto;">No Projects Yet</div>',
// Firebase API key
apiKey: '',
// Firebase Auth domain
authDomain: '',
// Cloud Firestore project ID
projectId: '',
// Enable support for offline data persistence
enableOffline: true,
// Firebase app config
firebaseConfig: {},
// Database settings (https://firebase.google.com/docs/reference/js/firebase.firestore.Settings)
settings: { timestampsInSnapshots: true },
// Show estimated project statistics
size: false,
// Send feedback when open is clicked on current page
currentPageOpen() {
console.log('Current page already open')
},
i18n: {},
},
...opts,
};
editor.I18n.addMessages({
en,
...options.i18n,
});
// Init and add dashboard object to editor
editor.TemplateManager = new TemplateManager(editor, options);
editor.PagesApp = new PagesApp(editor, options);
editor.SettingsApp = new SettingsApp(editor, options);
// Load commands
commands(editor, options);
// Load storages
storage(editor, options);
// Load page with index zero
editor.on('load', () => {
const cs = editor.Storage.getCurrentStorage();
if (!cs?.loadAll?.call ){
console.error('Storage does not have loadAll method');
return
}
const { customLoad } = options;
customLoad && typeof customLoad === 'function' && customLoad(editor, cs);
!customLoad && cs.loadAll(res => {
const firstPage = res[0];
if (firstPage && options.loadFirst) {
cs.setId(firstPage.id);
cs.setName(firstPage.name);
cs.setThumbnail(firstPage.thumbnail);
cs.setIsTemplate(firstPage.template);
editor.load();
} else {
cs.setId(editor.runCommand('get-uuidv4'));
cs.setName(`Default-${cs.currentId.substr(0, 7)}`);
options.components && editor.setComponents(options.components);
options.style && editor.setStyle(options.style);
}
});
});
};
\ No newline at end of file
export default {
'grapesjs-project-manager': {
templates: {
all: 'All',
templates: 'Templates',
search: 'Search for sites by name or id',
open: 'Open',
new: 'Enter new page name',
create: 'Create',
help: 'Select a template, enter project name, then click create. If no template is selected a blank project will be created.',
info: 'Site Info',
updated: 'Last Updated',
pages: 'Pages',
created: 'Created At',
size: 'Size',
actions: 'Actions',
titles: {
open: 'Select to open site',
info: 'Click to sort by site name',
updated: 'Click to sort by last update date',
pages: 'Click to sort by number of pages',
created: 'Click to sort by site creation date',
size: 'Click to sort by site size',
actions: 'Click to sort by site name',
delete: 'Delete',
edit: 'Edit',
}
},
pages: {
placeholder: 'page name',
new: 'New Page +',
},
settings: {
save: 'Save',
generate: 'Generate',
help: 'Enter url, or generate thumbnail.',
labels: {
name: 'Name',
thumbnail: 'Thumbnail',
description: 'Description',
template: 'Template'
},
placeholders: {
name: 'Name...',
thumbnail: 'Thumbnail...',
description: 'Description...',
},
},
}
}
\ No newline at end of file
import TemplateManager from "./templates";
import PagesApp from "./pages";
import SettingsApp from "./settings";
export default TemplateManager;
export { TemplateManager, PagesApp, SettingsApp };
\ No newline at end of file
import UI from '../utils/ui';
export default class PagesApp extends UI {
constructor(editor, opts = {}) {
super(editor, opts);
this.addPage = this.addPage.bind(this);
this.selectPage = this.selectPage.bind(this);
this.removePage = this.removePage.bind(this);
this.isSelected = this.isSelected.bind(this);
this.handleNameInput = this.handleNameInput.bind(this);
this.openEdit = this.openEdit.bind(this);
/* Set initial app state */
this.state = {
editablePageId: '',
isShowing: true,
nameText: '',
pages: [],
loading: false
};
}
get editableId() {
return this.state.editablePageId;
}
onRender() {
const { pm, setState, editor } = this;
setState({
loading: true
});
setState({
pages: [...pm.getAll()]
});
editor.on('page', () => {
setState({
pages: [...pm.getAll()]
})
});
setState({
loading: false
});
}
isSelected(page) {
return this.pm.getSelected().id === page.id;
}
selectPage(e) {
this.pm.select(e.currentTarget.dataset.key);
this.update();
}
removePage(e) {
this.pm.remove(e.currentTarget.dataset.key);
this.update();
}
openEdit(e) {
const { editor } = this;
this.setStateSilent({
editablePageId: e.currentTarget.dataset.key
});
editor.Modal.close();
editor.SettingsApp.setTab('page');
editor.runCommand('open-settings');
}
editPage(id, name) {
const currentPage = this.pm.get(id);
currentPage?.set('name', name);
this.update()
}
addPage() {
const { pm } = this;
const { nameText } = this.state
if (!nameText) return;
pm.add({
name: nameText,
component: ''
});
this.update();
}
handleNameInput(e) {
this.setStateSilent({
nameText: e.target.value.trim()
})
}
renderPagesList() {
const { pages, loading } = this.state;
const { opts, isSelected } = this;
if (loading) return opts.loader || '<div>Loading pages...</div>';
return pages.map((page, i) => `<div
data-id="${i}"
data-key="${page.id}"
class="page ${isSelected(page) ? 'selected' : ''}"
>
<i class="fa fa-file-o" style="margin:5px;"></i>
${page.get('name') || page.id}
${isSelected(page) ? '' : `<span class="page-close" data-key="${page.id}">&Cross;</span>`}
<span class="page-edit" data-key="${page.id}"><i class="fa fa-hand-pointer-o"></i></span>
</div>`).join("\n");
}
update() {
this.$el?.find('.pages').html(this.renderPagesList());
this.$el?.find('.page').on('click', this.selectPage);
this.$el?.find('.page-edit').on('click', this.openEdit);
this.$el?.find('.page-close').on('click', this.removePage);
}
render() {
const { $, editor } = this;
// Do stuff on render
this.onRender();
this.$el?.remove();
const cont = $(`<div style="display: ${this.state.isShowing ? 'flex' : 'none'};" class="pages-wrp">
<div class="pages">
${this.renderPagesList()}
</div>
<div class="flex-row">
<input
class="tm-input sm"
type="text"
placeholder="${editor.I18n.t('grapesjs-project-manager.pages.placeholder')}"
/>
</div>
<div class="add-page">
${editor.I18n.t('grapesjs-project-manager.pages.new')}
</div>
</div>`);
cont.find('.add-page').on('click', this.addPage);
cont.find('input').on('change', this.handleNameInput);
this.$el = cont;
return cont;
}
get findPanel() {
return this.editor.Panels.getPanel('views-container');
}
showPanel() {
this.state.isShowing = true;
this.findPanel?.set('appendContent', this.render()).trigger('change:appendContent');
this.update();
}
hidePanel() {
this.state.isShowing = false;
this.render();
}
}
\ No newline at end of file
import UI from '../utils/ui';
export default class SettingsApp extends UI {
constructor(editor, opts = {}) {
super(editor, opts);
this.handleSave = this.handleSave.bind(this);
this.handleThumbnail = this.handleThumbnail.bind(this);
this.handleThumbnailInput = this.handleThumbnailInput.bind(this);
/* Set initial app state */
this.state = {
tab: 'page',
loading: false
};
}
setTab(tab) {
this.state.tab = tab;
}
update() {
const { $el } = this;
$el?.find('#settings').html(this.renderSettings());
$el?.find('#generate').on('click', this.handleThumbnail);
$el?.find('input#thumbnail').on('change', this.handleThumbnailInput);
}
onRender() {
const { setState } = this;
setState({
loading: true
});
//? Setup code here
setState({
loading: false
});
}
handleSave(e) {
const { $el, editor } = this;
const { tab } = this.state;
if (tab === 'page') {
const id = editor.PagesApp.editableId;
const name = $el?.find('input.name').val().trim();
id && editor.PagesApp.editPage(id, name);
} else {
const id = editor.TemplateManager.editableId;
const thumbnail = $el?.find('input.thumbnail').val().trim();
const name = $el?.find('input.name').val().trim();
const description = $el?.find('input.desc').val().trim();
const template = $el?.find('input.template').get(0).checked;
id && editor.TemplateManager.handleEdit({ id, thumbnail, name, description, template });
}
editor.Modal.close();
}
handleThumbnail(e) {
const { editor, $el } = this;
editor.runCommand('take-screenshot', {
clb(dataUrl) {
$el?.find('input.thumbnail').val(dataUrl);
$el?.find('img').attr('src', dataUrl);
}
})
}
handleThumbnailInput(e) {
this.$el?.find('img').attr('src', e.target.value.trim());
}
renderSettings() {
const { tab, loading } = this.state;
const { opts, pfx, pm, editor } = this;
if (loading) return opts.loader || '<div>Loading settings...</div>';
if (tab === 'page') {
const page = pm.get(editor.PagesApp.editableId);
const value = page?.get('name') || page?.id || '';
return `<label for="name">
${editor.I18n.t('grapesjs-project-manager.settings.labels.name')}
</label>
<div class="flex-row">
<input
class="name tm-input"
value="${value}"
placeholder="${editor.I18n.t('grapesjs-project-manager.settings.placeholders.name')}"/>
</div>`
} else {
const clb = site => site.id === editor.TemplateManager.editableId;
const site = editor.TemplateManager.allSites.find(clb);
return `<div class="${pfx}tip-about ${pfx}four-color">
${editor.I18n.t('grapesjs-project-manager.settings.help')}
</div>
<label for="thumbnail">
${editor.I18n.t('grapesjs-project-manager.settings.labels.thumbnail')}
</label>
<div class="flex-row">
<input
id="thumbnail"
class="thumbnail tm-input"
value="${site?.thumbnail || ''}"
placeholder="${editor.I18n.t('grapesjs-project-manager.settings.placeholders.thumbnail')}"
/>
</div>
<div class="flex-row" style="margin-bottom:15px;">
<div class="site-screenshot">
<img src="${site?.thumbnail || ''}" alt="screenshot" />
</div>
<button id="generate" class="primary-button">
${editor.I18n.t('grapesjs-project-manager.settings.generate')}
</button>
</div>
<label for="name">
${editor.I18n.t('grapesjs-project-manager.settings.labels.name')}
</label>
<div class="flex-row">
<input
id="name"
class="name tm-input"
value="${site?.name || ''}"
placeholder="${editor.I18n.t('grapesjs-project-manager.settings.placeholders.name')}"
/>
</div>
<label for="desc">
${editor.I18n.t('grapesjs-project-manager.settings.labels.description')}
</label>
<div class="flex-row">
<input
id="desc"
class="desc tm-input"
value="${site?.description || ''}"
placeholder="${editor.I18n.t('grapesjs-project-manager.settings.placeholders.description')}"
/>
</div>
<div class="flex-row group">
<input id="template" class="template" type="checkbox" ${site?.template ? 'checked' : ''}/>
<label for="template">
${editor.I18n.t('grapesjs-project-manager.settings.labels.template')}
</label>
</div>`
}
}
render() {
const { $, editor } = this;
// Do stuff on render
this.onRender();
this.$el?.remove();
const cont = $(`<div class="app">
<div id="settings">
${this.renderSettings()}
</div>
<div class="flex-row">
<button id="save" class="primary-button">
${editor.I18n.t('grapesjs-project-manager.settings.save')}
</button>
</div>
</div>`);
cont.find('#save').on('click', this.handleSave);
cont.find('#generate').on('click', this.handleThumbnail);
cont.find('input#thumbnail').on('change', this.handleThumbnailInput);
this.$el = cont;
return cont;
}
}
\ No newline at end of file
import ago from '../utils/timeago';
import UI from '../utils/ui';
import objSize from '../utils/objsize';
import { sortByDate, sortByName, sortByPages, sortBySize, matchText } from '../utils/sort';
export default class TemplateManager extends UI {
constructor(editor, opts = {}) {
super(editor, opts);
this.handleSort = this.handleSort.bind(this);
this.handleFilterInput = this.handleFilterInput.bind(this);
this.handleNameInput = this.handleNameInput.bind(this);
this.handleOpen = this.handleOpen.bind(this);
this.handleCreate = this.handleCreate.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.openEdit = this.openEdit.bind(this);
/* Set initial app state */
this.state = {
editableProjectId: '',
projectId: '',
tab: 'pages',
sites: [],
nameText: '',
filterText: '',
loading: false,
sortBy: 'published_at',
sortOrder: 'desc'
};
}
get editableId() {
return this.state.editableProjectId;
}
get allSites() {
return this.state.sites;
}
get allSitesSize() {
return objSize(this.state.sites);
}
onRender() {
const { setState, cs } = this;
/* Set request loading state */
setState({
loading: true
});
/* Fetch sites from storage API */
cs.loadAll(sites => {
/* Set sites and turn off loading state */
setState({
sites,
loading: false
});
},
err => console.log("Error", err));
}
handleFilterInput(e) {
this.setState({
filterText: e.target.value.trim()
});
}
handleNameInput(e) {
this.setStateSilent({
nameText: e.target.value.trim()
})
}
handleSort(e) {
const { sortOrder } = this.state;
if (e.target && e.target.dataset) {
this.setState({
sortBy: e.target.dataset.sort,
// invert sort order
sortOrder: sortOrder === 'desc' ? 'asc' : 'desc'
});
}
}
handleTabs(e) {
const { target } = e;
const { $el, pfx, $ } = this;
$el.find(`.${pfx}tablinks`).removeClass('active');
$(target).addClass('active');
if (target.id === 'pages') {
this.setState({ tab: 'pages' });
} else {
this.setState({ tab: 'templates' });
}
}
handleOpen(e) {
const { editor, cs } = this;
const { projectId } = this.state;
if (!projectId || projectId === cs.currentId) {
this.opts.currentPageOpen()
return;
}
cs.setId(projectId);
editor.load(res => {
cs.setName(res.name);
cs.setThumbnail(res.thumbnail || '');
cs.setIsTemplate(res.template);
cs.setDescription(res.description || 'No description');
editor.Modal.close();
});
}
handleCreate(e) {
const { editor, cs } = this;
const { projectId, nameText } = this.state;
const id = editor.runCommand('get-uuidv4');
const name = nameText || 'New-' + id.substr(0, 8);
const def = {
id,
name,
template: false,
thumbnail: '',
styles: '[]',
description: 'No description',
};
def[`${this.id}pages`] = `[{"id": "${crypto.randomUUID().substr(0, 8)}", "name": "index"}]`;
def[`${this.id}styles`] = '[]';
def[`${this.id}assets`] = '[]';
if (!projectId) {
cs.setId(id);
cs.store(def, res => {
cs.setIsTemplate(false);
editor.load(res => {
cs.setId(res.id);
cs.setName(res.name);
cs.setThumbnail(res.thumbnail || '');
cs.setDescription(res.description || 'No description');
editor.Modal.close();
});
});
} else {
cs.setId(projectId);
cs.setIsTemplate(false);
editor.load(res => {
cs.setId(id);
cs.setName(name);
cs.setThumbnail(res.thumbnail || '');
cs.setDescription(res.description || 'No description');
editor.Modal.close();
});
}
}
openEdit(e) {
const { editor, setStateSilent } = this;
setStateSilent({
editableProjectId: e.currentTarget.dataset.id
});
editor.Modal.close();
editor.SettingsApp.setTab('project');
editor.runCommand('open-settings');
}
handleEdit(data) {
this.cs.update({ ...data, updated_at: Date() });
}
handleDelete(e) {
const { cs, setState, opts } = this;
cs.delete(res => {
opts.onDelete(res);
cs.loadAll(sites => setState({ sites }),
err => console.log("Error", err));
}, opts.onDeleteError, e.currentTarget.dataset.id);
}
renderSiteList() {
const { sites, tab, filterText, loading, sortBy, sortOrder } = this.state;
const { pfx, opts, cs, editor } = this;
if (loading) return opts.loader || '<div>Loading sites...</div>';
if (!sites.length) return opts.nosites || '<div>No Sites</div>';
let order
if (sortBy === 'id') {
order = sortByName(sortBy, sortOrder);
} else if (sortBy === 'updated_at' || sortBy === 'created_at') {
order = sortByDate(sortBy, sortOrder);
} else if (sortBy === 'pages') {
order = sortByPages(this.id + sortBy, sortOrder);
} else if (sortBy === 'size') {
order = sortBySize(sortOrder);
}
const sortedSites = sites.sort(order);
let matchingSites = sortedSites.filter(site => {
// No search query. Show all
if (!filterText && tab === 'pages') {
return true;
}
const { id, name, template } = site;
if (
(matchText(filterText, id) ||
matchText(filterText, name)) &&
tab === 'pages'
) {
return true;
}
if (tab === 'templates' && template) {
return true;
}
// no match!
return false;
})
.map((site, i) => {
const {
id,
name,
description,
thumbnail,
created_at,
updated_at
} = site;
const size = objSize(site);
const pages = JSON.parse(site[`${this.id}pages`]);
const time = updated_at ? ago(new Date(updated_at).getTime()) : 'NA';
const createdAt = created_at ? ago(new Date(created_at).getTime()) : 'NA';
const pageNames = pages.map(page => page.name).join(', ');
return `<div
class="site-wrapper ${cs.currentId === id ? 'open' : ''}"
key="${i}"
data-id="${id}"
title="${editor.I18n.t('grapesjs-project-manager.templates.titles.open')}">
<div class="site-screenshot">
<img src="${thumbnail}" alt="" />
</div>
<div class="site-info">
<h2>
${name}
</h2>
<div class="site-meta">
${description}
</div>
</div>
<div class="site-update-time">${time}</div>
<div class="site-pages">
<div title="${pageNames || id}">
${pages.length || 1}
</div>
</div>
<div class="site-create-time">${createdAt}</div>
${opts.size ? `<div class="site-size" title="${size} KB">
${size.toFixed(2)} KB
</div>` : ''}
<div class="site-actions">
<i class="${pfx}caret-icon fa fa-hand-pointer-o edit" title="${editor.I18n.t('grapesjs-project-manager.templates.titles.edit')}" data-id="${id}"></i>
${!(cs.currentId === id) ? `<i class="${pfx}caret-icon fa fa-trash-o delete" title="${editor.I18n.t('grapesjs-project-manager.templates.titles.delete')}" data-id="${id}"></i>` : ''}
</div>
</div>`;
}).join('\n');
if (!matchingSites.length) {
if (tab === 'templates') return opts.nosites || '<div>No Templates Available.</div>';
matchingSites = `<div>
<h3>
No '${filterText}' examples found. Clear your search and try again.
</h3>
</div>`;
}
return matchingSites;
}
renderSiteActions() {
const { editor } = this;
return this.state.tab === 'pages' ?
`<div class="flex-row">
<input
class="search tm-input"
placeholder="${editor.I18n.t('grapesjs-project-manager.templates.search')}"
/>
<button id="open" class="primary-button">
${editor.I18n.t('grapesjs-project-manager.templates.open')}
</button>
</div>` :
`<div class="${this.pfx}tip-about ${this.pfx}four-color">
${editor.I18n.t('grapesjs-project-manager.templates.help')}
</div>
<div class="flex-row">
<input
class="name tm-input"
placeholder="${editor.I18n.t('grapesjs-project-manager.templates.new')}"
/>
<button id="create" class="primary-button">
${editor.I18n.t('grapesjs-project-manager.templates.create')}
</button>
</div>`;
}
renderThumbnail(thumbnail, page) {
const def = `<img src="${thumbnail}" alt="" />`;
if (thumbnail) return def;
else if (page.html) return `<svg xmlns="http://www.w3.org/2000/svg" class="template-preview" viewBox="0 0 1300 1100" width="99%" height="220">
<foreignObject width="100%" height="100%" style="pointer-events:none">
<div xmlns="http://www.w3.org/1999/xhtml">
${page.html + '<style scoped>' + page.css + '</style>'}
</div>
</foreignObject>
</svg>`;
return def;
}
update() {
this.$el?.find('#site-list').html(this.renderSiteList());
this.$el?.find('#tm-actions').html(this.renderSiteActions());
const sites = this.$el?.find('.site-wrapper');
const search = this.$el?.find('input.search');
const name = this.$el?.find('input.name');
this.setStateSilent({ projectId: '' });
if (sites) {
sites.on('click', e => {
sites.removeClass('selected');
this.$(e.currentTarget).addClass('selected');
this.setStateSilent({ projectId: e.currentTarget.dataset.id });
});
}
if (search) {
search.val(this.state.filterText);
search.on('change', this.handleFilterInput);
}
if (name) {
name.val(this.state.nameText);
name.on('change', this.handleNameInput);
}
this.$el?.find('#open').on('click', this.handleOpen);
this.$el?.find('#create').on('click', this.handleCreate);
this.$el?.find('i.edit').on('click', this.openEdit);
this.$el?.find('i.delete').on('click', this.handleDelete);
}
render() {
const { $, pfx, opts, editor } = this;
const { tab } = this.state
// Do stuff on render
this.onRender();
this.$el?.remove();
/* Show admin UI */
const cont = $(`<div class="app">
<div class="contents">
<div class="${pfx}tab">
<button id="pages" class="${pfx}tablinks ${tab === 'pages' ? 'active' : ''}">
${editor.I18n.t('grapesjs-project-manager.templates.all')}
</button>
<button id="templates" class="${pfx}tablinks ${tab === 'templates' ? 'active' : ''}"">
${editor.I18n.t('grapesjs-project-manager.templates.templates')}
</button>
</div>
<div id="tm-actions">
${this.renderSiteActions()}
</div>
<div class="site-wrapper-header">
<div
class="site-screenshot-header header"
data-sort="id"
title="${editor.I18n.t('grapesjs-project-manager.templates.titles.info')}"
>
${editor.I18n.t('grapesjs-project-manager.templates.info')}
</div>
<div
class="site-info header"
data-sort="id"
></div>
<div
class="site-update-time header"
data-sort="updated_at"
title="${editor.I18n.t('grapesjs-project-manager.templates.titles.updated')}"
>
${editor.I18n.t('grapesjs-project-manager.templates.updated')}
</div>
<div
class="site-pages header"
data-sort="pages"
title="${editor.I18n.t('grapesjs-project-manager.templates.titles.pages')}"
>
${editor.I18n.t('grapesjs-project-manager.templates.pages')}
</div>
<div
class="site-create-time header"
data-sort="created_at"
title="${editor.I18n.t('grapesjs-project-manager.templates.titles.created')}"
>
${editor.I18n.t('grapesjs-project-manager.templates.created')}
</div>
${opts.size ? `<div
class="site-size header"
data-sort="size"
title="${editor.I18n.t('grapesjs-project-manager.templates.titles.size')}"
>
${editor.I18n.t('grapesjs-project-manager.templates.size')}
</div>` : ''}
<div
class="site-actions header"
data-sort="id"
title="${editor.I18n.t('grapesjs-project-manager.templates.titles.actions')}"
>
${editor.I18n.t('grapesjs-project-manager.templates.actions')}
</div>
</div>
<div id="site-list">
${this.renderSiteList()}
</div>
</div>
</div>`);
cont.find('.header').on('click', this.handleSort);
cont.find('#pages, #templates').on('click', this.handleTabs);
this.$el = cont;
return cont;
}
}
\ No newline at end of file
import { storageFireStore } from '../consts';
export default (editor, opts = {}) => {
const sm = editor.StorageManager;
const storageName = storageFireStore;
let db;
let doc;
let collection;
const { apiKey, authDomain, projectId } = opts;
const dbSettings = opts.settings;
const onError = err => sm.onError(storageName, err.code || err);
const getDoc = () => doc;
const getAsyncCollection = (clb) => {
if (collection) return clb(collection);
if (!firebase.apps.length) {
firebase.initializeApp({ apiKey, authDomain, projectId, ...opts.firebaseConfig });
db = firebase.firestore();
db.settings(dbSettings);
}
else {
firebase.app();
db = firebase.firestore();
db.settings(dbSettings);
}
const callback = () => {
collection = db.collection(opts.objectStoreName);
clb(collection);
}
callback();
//if (opts.enableOffline) {
// db.enablePersistence().then(callback).catch(onError);
//} else {
// callback();
//}
};
const getAsyncDoc = (clb) => {
getAsyncCollection(cll => {
const cs = editor.Storage.getCurrentStorage();
doc = cll.doc(cs.currentId);
clb(doc);
});
};
sm.add(storageName, {
currentName: 'Default',
currentId: 'uuidv4',
currentThumbnail: '',
isTemplate: false,
description: 'No description',
getDoc,
setDocId(id) {
this.currentId = id;
},
setId(id) {
this.currentId = id;
},
setName(name) {
this.currentName = name;
},
setThumbnail(thumbnail) {
this.currentThumbnail = thumbnail;
},
setIsTemplate(isTemplate) {
this.isTemplate = !!isTemplate;
},
setDescription(description) {
this.description = description;
},
load(keys, clb, clbError) {
getAsyncDoc(doc => {
doc.get()
.then(doc => {
if (doc.exists) clb(doc.data());
else clb({});
})
.catch(clbError);
});
},
loadAll(clb, clbError) {
getAsyncCollection(cll => {
cll.get()
.then(docs => {
const data = [];
docs.forEach(doc => data.push(doc.data()));
clb(data);
})
.catch(clbError);
});
},
store(data, clb, clbError) {
getAsyncCollection(cll => {
cll.doc(data.id || this.currentId).set({
id: this.currentId,
name: this.currentName,
template: this.isTemplate,
thumbnail: this.currentThumbnail,
description: this.description,
updated_at: Date(),
...data
})
.then(clb)
.catch(clbError);
});
},
update(data, clb, clbError) {
const { id, ..._data } = data;
getAsyncCollection(cll => {
cll.doc(id).set(_data, { merge: true })
.then(clb)
.catch(clbError);
});
},
delete(clb, clbError, index) {
if (!index) {
getAsyncDoc(doc => {
doc.delete()
.then(clb)
.catch(clbError);
});
} else {
getAsyncCollection(cll => {
cll.doc(index).delete()
.then(clb)
.catch(clbError);
});
}
}
});
}
\ No newline at end of file