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 { useElementBounding } from "@vueuse/core";
import { nextTick, reactive } from "vue";
function setPanAndZoom(
props: CanvasProps,
target: HTMLElement,
panAndZoomAreaElement: HTMLElement,
zoomLimits = { min: 0.1, max: 10 }
) {
const targetBound = reactive(useElementBounding(target));
let pointFromCenterX = 0;
let pointFromCenterY = 0;
let startX = 0;
let startY = 0;
let pinchPointSet = false;
let wheeling: undefined | number;
const updatePanAndZoom = (e: WheelEvent) => {
clearTimeout(wheeling);
if (e.ctrlKey || e.metaKey) {
props.scaling = true;
if (!pinchPointSet) {
// set pinch point before setting new scale value
targetBound.update();
const middleX = targetBound.left + targetBound.width / 2;
const middleY = targetBound.top + targetBound.height / 2;
pointFromCenterX = (e.clientX - middleX) / props.scale;
pointFromCenterY = (e.clientY - middleY) / props.scale;
startX = e.clientX;
startY = e.clientY;
pinchPointSet = true;
let clearPinchPoint = () => {
pinchPointSet = false;
};
panAndZoomAreaElement.addEventListener("mousemove", clearPinchPoint, { once: true });
}
// Multiplying with 0.01 to make the zooming less sensitive
// Multiplying with scale to make the zooming feel consistent
let scale = props.scale - e.deltaY * 0.008 * props.scale;
scale = Math.min(Math.max(scale, zoomLimits.min), zoomLimits.max);
props.scale = scale;
nextTick(() => {
targetBound.update();
const middleX = targetBound.left + targetBound.width / 2;
const middleY = targetBound.top + targetBound.height / 2;
const pinchLocationX = middleX + pointFromCenterX * scale;
const pinchLocationY = middleY + pointFromCenterY * scale;
const diffX = startX - pinchLocationX;
const diffY = startY - pinchLocationY;
props.translateX += diffX / scale;
props.translateY += diffY / scale;
});
} else {
props.panning = true;
pinchPointSet = false;
// Dividing with scale to make the panning feel consistent
props.translateX -= e.deltaX / props.scale;
props.translateY -= e.deltaY / props.scale;
}
wheeling = setTimeout(() => {
props.scaling = false;
props.panning = false;
}, 200);
};
panAndZoomAreaElement.addEventListener(
"wheel",
(e) => {
e.preventDefault();
requestAnimationFrame(() => updatePanAndZoom(e));
},
{ passive: false }
);
}
export default setPanAndZoom;
|
2302_79757062/builder
|
frontend/src/utils/panAndZoom.ts
|
TypeScript
|
agpl-3.0
| 2,443
|
import { Socket } from "socket.io-client";
import { getCurrentInstance } from "vue";
export default class RealTimeHandler {
open_docs: Set<string>;
socket: Socket;
subscribing: boolean;
constructor() {
this.open_docs = new Set();
this.socket = getCurrentInstance()!.appContext.config.globalProperties.$socket;
this.subscribing = false;
}
on(event: string, callback: (...args: any[]) => void) {
if (this.socket) {
this.socket.on(event, callback);
}
}
off(event: string, callback: (...args: any[]) => void) {
if (this.socket) {
this.socket.off(event, callback);
}
}
emit(event: string, ...args: any[]) {
this.socket.emit(event, ...args);
}
doc_subscribe(doctype: string, docname: string) {
if (this.subscribing) {
console.log("throttled");
return;
}
if (this.open_docs.has(`${doctype}:${docname}`)) {
return;
}
this.subscribing = true;
// throttle to 1 per sec
setTimeout(() => {
this.subscribing = false;
}, 1000);
this.emit("doc_subscribe", doctype, docname);
this.open_docs.add(`${doctype}:${docname}`);
}
doc_unsubscribe(doctype: string, docname: string) {
this.emit("doc_unsubscribe", doctype, docname);
return this.open_docs.delete(`${doctype}:${docname}`);
}
doc_open(doctype: string, docname: string) {
this.emit("doc_open", doctype, docname);
}
doc_close(doctype: string, docname: string) {
this.emit("doc_close", doctype, docname);
}
publish(event: string, message: any) {
if (this.socket) {
this.emit(event, message);
}
}
}
|
2302_79757062/builder
|
frontend/src/utils/realtimeHandler.ts
|
TypeScript
|
agpl-3.0
| 1,531
|
import { useElementBounding, useMutationObserver } from "@vueuse/core";
import { nextTick, reactive, watch, watchEffect } from "vue";
import { addPxToNumber } from "./helpers";
declare global {
interface Window {
observer: any;
}
}
window.observer = null;
const updateList: (() => void)[] = [];
function trackTarget(target: HTMLElement | SVGElement, host: HTMLElement, canvasProps: CanvasProps) {
const targetBounds = reactive(useElementBounding(target));
const container = target.closest(".canvas-container");
// TODO: too much? find a better way to track changes
updateList.push(targetBounds.update);
watch(canvasProps, () => nextTick(targetBounds.update), { deep: true });
if (!window.observer) {
let callback = () => {
nextTick(() => {
updateList.forEach((fn) => {
fn();
});
});
};
window.observer = useMutationObserver(container as HTMLElement, callback, {
attributes: true,
childList: true,
subtree: true,
attributeFilter: ["style", "class"],
characterData: true,
});
}
watchEffect(() => {
host.style.width = addPxToNumber(targetBounds.width, false);
host.style.height = addPxToNumber(targetBounds.height, false);
host.style.top = addPxToNumber(targetBounds.top, false);
host.style.left = addPxToNumber(targetBounds.left, false);
});
return targetBounds.update;
}
export default trackTarget;
|
2302_79757062/builder
|
frontend/src/utils/trackTarget.ts
|
TypeScript
|
agpl-3.0
| 1,368
|
import useStore from "@/store";
import { useEventListener } from "@vueuse/core";
import Block from "./block";
import { findNearestSiblingIndex } from "./helpers";
const store = useStore();
export function useDraggableBlock(block: Block, target: HTMLElement, options: { ghostScale?: number }) {
let ghostElement = null as HTMLElement | null;
const handleDragStart = (e: DragEvent) => {
e.dataTransfer?.setData("draggingBlockId", block.blockId);
ghostElement = target.cloneNode(true) as HTMLElement;
ghostElement.id = "ghost";
ghostElement.style.position = "fixed";
ghostElement.style.transform = `scale(${options.ghostScale || 1})`;
ghostElement.style.pointerEvents = "none";
ghostElement.style.zIndex = "999999";
document.body.appendChild(ghostElement);
if (e.dataTransfer) {
e.dataTransfer.effectAllowed = "move";
const blankImage = new Image();
blankImage.src =
"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>";
e.dataTransfer.setDragImage(blankImage, e.offsetX, e.offsetY);
}
e.stopPropagation();
};
const handleDrag = (e: DragEvent) => {
const target = e.target as HTMLElement;
ghostElement = ghostElement as HTMLElement;
ghostElement.style.left = e.clientX - target.offsetWidth / 2 + "px";
ghostElement.style.top = e.clientY - target.offsetHeight / 2 + "px";
e.stopPropagation();
};
const handleDrop = (e: DragEvent) => {
store.activeCanvas?.history.pause();
// move block to new container
if (e.dataTransfer) {
const draggingBlockId = e.dataTransfer.getData("draggingBlockId");
const draggingBlock = store.activeCanvas?.findBlock(draggingBlockId) as Block;
const nearestElementIndex = findNearestSiblingIndex(e);
if (draggingBlock) {
const newParent = block;
const oldParent = draggingBlock.getParentBlock() as Block;
if (newParent.blockId === oldParent.blockId) {
newParent.moveChild(draggingBlock, nearestElementIndex);
} else if (newParent.canHaveChildren() && newParent.isContainer()) {
if (oldParent) {
oldParent.removeChild(draggingBlock);
}
newParent.addChild(draggingBlock, nearestElementIndex);
store.selectBlock(draggingBlock, e);
}
e.stopPropagation();
}
}
store.activeCanvas?.history.resume(true);
};
const handleDragEnd = (e: DragEvent) => {
if (ghostElement) {
ghostElement.remove();
}
if (e.dataTransfer && e.dataTransfer.getData("draggingBlockId")) {
e.dataTransfer.dropEffect = "none";
e.stopPropagation();
}
};
const handleDragEnter = (e: DragEvent) => {
e.preventDefault();
e.stopPropagation();
};
const handleDragOver = (e: DragEvent) => {
e.preventDefault();
e.stopPropagation();
};
const handleDragLeave = (e: DragEvent) => {
e.preventDefault();
e.stopPropagation();
};
useEventListener(target, "dragstart", handleDragStart);
useEventListener(target, "drag", handleDrag);
useEventListener(target, "drop", handleDrop);
useEventListener(target, "dragend", handleDragEnd);
useEventListener(target, "dragenter", handleDragEnter);
useEventListener(target, "dragover", handleDragOver);
useEventListener(target, "dragleave", handleDragLeave);
}
|
2302_79757062/builder
|
frontend/src/utils/useDraggableBlock.ts
|
TypeScript
|
agpl-3.0
| 3,198
|
import colors from "tailwindcss/colors";
import tailwindConfig from "frappe-ui/src/utils/tailwind.config";
import plugin from "tailwindcss/plugin";
module.exports = {
darkMode: "class",
presets: [tailwindConfig],
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}",
"./node_modules/frappe-ui/src/components/**/*.{vue,js,ts,jsx,tsx}",
"../node_modules/frappe-ui/src/components/**/*.{vue,js,ts,jsx,tsx}",
],
plugins: [
plugin(function ({ matchUtilities, theme }) {
matchUtilities(
{
"auto-fill": (value) => ({
gridTemplateColumns: `repeat(auto-fill, minmax(min(${value}, 100%), 1fr))`,
}),
"auto-fit": (value) => ({
gridTemplateColumns: `repeat(auto-fit, minmax(min(${value}, 100%), 1fr))`,
}),
},
{
values: theme("width", {}),
},
);
}),
],
theme: {
extend: {
transitionProperty: {
size: "transform, border-radius",
},
colors: {
zinc: colors.zinc,
},
},
},
};
|
2302_79757062/builder
|
frontend/tailwind.config.js
|
JavaScript
|
agpl-3.0
| 970
|
import vue from "@vitejs/plugin-vue";
import frappeui from "frappe-ui/vite";
import path from "path";
import { defineConfig } from "vite";
// https://vitejs.dev/config/
export default defineConfig({
define: {
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: false,
},
plugins: [frappeui({ source: "^/(app|login|api|assets|files|pages|builder_assets)" }), vue()],
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
},
},
build: {
outDir: `../builder/public/frontend`,
emptyOutDir: true,
target: "es2015",
sourcemap: true,
chunkSizeWarningLimit: 1000,
},
optimizeDeps: {
include: ["frappe-ui > feather-icons", "showdown", "engine.io-client"],
},
});
|
2302_79757062/builder
|
frontend/vite.config.mjs
|
JavaScript
|
agpl-3.0
| 677
|
#!bin/bash
set -e
if [[ -f "/workspaces/frappe_codespace/frappe-bench/apps/frappe" ]]
then
echo "Bench already exists, skipping init"
exit 0
fi
rm -rf /workspaces/frappe_codespace/.git
source /home/frappe/.nvm/nvm.sh
nvm alias default 18
nvm use 18
echo "nvm use 18" >> ~/.bashrc
cd /workspace
bench init \
--ignore-exist \
--skip-redis-config-generation \
frappe-bench
cd frappe-bench
# Use containers instead of localhost
bench set-mariadb-host mariadb
bench set-redis-cache-host redis-cache:6379
bench set-redis-queue-host redis-queue:6379
bench set-redis-socketio-host redis-socketio:6379
# Remove redis from Procfile
sed -i '/redis/d' ./Procfile
bench new-site dev.localhost \
--mariadb-root-password 123 \
--admin-password admin \
--no-mariadb-socket
bench --site dev.localhost set-config developer_mode 1
bench --site dev.localhost clear-cache
bench use dev.localhost
bench get-app builder
bench --site dev.localhost install-app builder
|
2302_79757062/builder
|
scripts/init.sh
|
Shell
|
agpl-3.0
| 963
|
import math
import random
def Kmeans(data, k, epsilon=1e-4, max_iterations=100):
# 辅助函数:计算两个向量的欧氏距离
def euclidean_distance(a, b):
return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))
# 辅助函数:将样本分配到最近的聚类中心
def assign_cluster(x, c):
min_distance = float('inf')
cluster_index = 0
for i, centroid in enumerate(c):
distance = euclidean_distance(x, centroid)
if distance < min_distance:
min_distance = distance
cluster_index = i
return cluster_index
# 初始化聚类中心 - 随机选择k个样本
c = random.sample(data, k)
# 初始化labels变量
labels = []
# 迭代优化
for _ in range(max_iterations):
# 分配样本到最近的聚类中心
clusters = [[] for _ in range(k)]
labels = [] # 重新初始化labels
for sample in data:
cluster_idx = assign_cluster(sample, c)
clusters[cluster_idx].append(sample)
labels.append(cluster_idx)
# 重新计算聚类中心
new_c = []
total_movement = 0.0
for i in range(k):
if clusters[i]: # 如果簇不为空
# 计算簇内均值作为新中心
dimension = len(clusters[i][0])
new_center = [0.0] * dimension
for point in clusters[i]:
for d in range(dimension):
new_center[d] += point[d]
for d in range(dimension):
new_center[d] /= len(clusters[i])
new_c.append(new_center)
# 计算中心移动距离
movement = euclidean_distance(c[i], new_center)
total_movement += movement
else:
# 如果簇为空,随机重新初始化该中心
new_c.append(random.choice(data))
# 检查收敛条件
if total_movement < epsilon:
break
c = new_c
return c, labels
|
2301_82233644/machine-learning-course
|
assignment3/1班01.py
|
Python
|
mit
| 2,119
|
import random
def assign_cluster(x, centers):
min_dist_sq = float('inf')
best_cluster_idx = 0
# 计算样本到每个聚类中心的欧氏距离平方
for idx, center in enumerate(centers):
dist_sq = sum((xi - ci) ** 2 for xi, ci in zip(x, center))
if dist_sq < min_dist_sq:
min_dist_sq = dist_sq
best_cluster_idx = idx
return best_cluster_idx
def Kmeans(data, k, epsilon=1e-3, iteration=100):
# 1. 输入参数校验
if not data:
raise ValueError("输入数据不能为空")
n_samples = len(data)
if k < 1 or k > n_samples:
raise ValueError(f"k值必须满足 1 ≤ k ≤ 样本数(当前样本数:{n_samples})")
n_features = len(data[0])
for sample in data:
if len(sample) != n_features:
raise ValueError("所有样本必须具有相同的维度")
# 2. 初始化聚类中心
init_indices = random.sample(range(n_samples), k)
final_centers = [data[i].copy() for i in init_indices]
# 3. 迭代优化聚类中心
for iter_cnt in range(iteration):
clusters = [[] for _ in range(k)]
labels = []
for sample_idx, sample in enumerate(data):
cluster_idx = assign_cluster(sample, final_centers)
clusters[cluster_idx].append(sample_idx)
labels.append(cluster_idx)
old_centers = [center.copy() for center in final_centers]
for cluster_idx in range(k):
cluster_samples = clusters[cluster_idx]
if not cluster_samples:
final_centers[cluster_idx] = data[random.randint(0, n_samples - 1)].copy()
continue
new_center = []
for dim in range(n_features):
dim_sum = sum(data[s_idx][dim] for s_idx in cluster_samples)
new_center.append(dim_sum / len(cluster_samples))
final_centers[cluster_idx] = new_center
total_center_dist = 0.0
for old_c, new_c in zip(old_centers, final_centers):
dist = sum((o - n) ** 2 for o, n in zip(old_c, new_c)) ** 0.5
total_center_dist += dist
if total_center_dist < epsilon:
print(f"迭代 {iter_cnt + 1} 次后收敛(中心总变化量:{total_center_dist:.6f} < ε={epsilon})")
break
else:
print(f"已达到最大迭代次数 {iteration},未完全收敛(最终中心总变化量:{total_center_dist:.6f})")
return labels, final_centers
|
2301_82233644/machine-learning-course
|
assignment3/1班13.py
|
Python
|
mit
| 2,511
|
import math
import random
def euclidean_distance(point1, point2):
#计算欧几里得距离
return math.sqrt(sum((a - b) ** 2 for a, b in zip(point1, point2)))
def assign_cluster(X, centers):
# X: list of lists, 数据点列表 centers: list of lists, 聚类中心列表 labels: 每个样本所属的簇索引
labels = []
for point in X:
min_dist = float('inf')
best_center = 0
for j, center in enumerate(centers):
dist = euclidean_distance(point, center)
if dist < min_dist:
min_dist = dist
best_center = j
labels.append(best_center)
return labels
def kmeans(X, k, epsilon=1e-4, max_iterations=100):
#X: 数据集 k: 聚类数 epsilon: 收敛阈值 max_iterations: 最大迭代次数 centers: 聚类中心 labels: 聚类标签
# 随机初始化中心
centers = random.sample(X, k)
for iteration in range(max_iterations):
# 分配簇
labels = assign_cluster(X, centers)
# 更新中心
new_centers = []
for j in range(k):
# 获取属于该簇的所有点
cluster_points = [X[i] for i in range(len(X)) if labels[i] == j]
if len(cluster_points) > 0:
# 计算新中心(均值)
n_features = len(X[0])
new_center = [
sum(point[d] for point in cluster_points) / len(cluster_points)
for d in range(n_features)
]
new_centers.append(new_center)
else:
# 空簇处理:重新随机初始化
new_centers.append(random.choice(X))
# 检查收敛
center_shift = sum(
euclidean_distance(centers[j], new_centers[j])
for j in range(k)
)
if center_shift < epsilon:
break
centers = new_centers
return centers, labels
|
2301_82233644/machine-learning-course
|
assignment3/1班23.py
|
Python
|
mit
| 2,012
|
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def assign_cluster(x, c):
distances = np.linalg.norm(x[:, np.newaxis] - c, axis=2)
return np.argmin(distances, axis=1)
def Kmeans(data, k, epsilon=1e-4, iteration=100):
n_samples, n_features = data.shape
np.random.seed(0)
centroids = data[np.random.choice(n_samples, k, replace=False)]
for i in range(iteration):
labels = assign_cluster(data, centroids)
new_centroids = np.array([
data[labels == j].mean(axis=0) if np.any(labels == j) else centroids[j]
for j in range(k)
])
shift = np.linalg.norm(new_centroids - centroids)
if shift < epsilon:
print(f"K-means算法在第 {i + 1} 次迭代后收敛 (质心移动距离: {shift:.6f})")
break
centroids = new_centroids
return labels, centroids
if __name__ == "__main__":
np.random.seed(42)
data = np.vstack([
np.random.randn(50, 2) + np.array([0, 0]),
np.random.randn(50, 2) + np.array([5, 5]),
np.random.randn(50, 2) + np.array([10, 0])
])
Y, C = Kmeans(data, k=3)
print("聚类结果标签:", Y)
print("聚类中心:\n", C)
plt.scatter(data[:, 0], data[:, 1], c=Y, cmap='viridis', s=30)
plt.scatter(C[:, 0], C[:, 1], c='red', marker='X', s=200, label='Centroids')
plt.legend()
plt.title("K-Means 聚类结果")
plt.show()
|
2301_82233644/machine-learning-course
|
assignment3/1班73.py
|
Python
|
mit
| 1,515
|
import random
import math
from collections import defaultdict
def euclidean_distance(p1, p2):
if len(p1) != len(p2):
raise ValueError("Points must have the same number of dimensions")
sum_squares = 0
for i in range(len(p1)):
sum_squares += (p1[i] - p2[i]) ** 2
return math.sqrt(sum_squares)
def assign_cluster(x, c):
min_dist = float('inf')
min_index = -1
for i, centroid in enumerate(c):
dist = euclidean_distance(x, centroid)
if dist < min_dist:
min_dist = dist
min_index = i
return min_index
def Kmeans(data, k, epsilon=1e-4, max_iterations=100):
if k > len(data):
raise ValueError("K cannot be greater than the number of data points.")
initial_indices = random.sample(range(len(data)), k)
centroids = [list(data[i]) for i in initial_indices]
loss_history = []
print(f"初始质心: {centroids}")
for i in range(max_iterations):
clusters = [-1] * len(data)
for point_idx, point in enumerate(data):
cluster_idx = assign_cluster(point, centroids)
clusters[point_idx] = cluster_idx
loss = 0.0
for point_idx, point in enumerate(data):
cluster_idx = clusters[point_idx]
centroid = centroids[cluster_idx]
loss += euclidean_distance(point, centroid) ** 2 # 使用平方距离作为损失
loss_history.append(loss)
new_centroids = []
for j in range(k):
cluster_points = [data[p_idx] for p_idx in range(len(data)) if clusters[p_idx] == j]
if not cluster_points:
new_centroids.append(centroids[j])
continue
num_points = len(cluster_points)
num_dimensions = len(cluster_points[0])
new_centroid = [0.0] * num_dimensions
for dim in range(num_dimensions):
sum_dim = sum(point[dim] for point in cluster_points)
new_centroid[dim] = sum_dim / num_points
new_centroids.append(new_centroid)
total_shift = sum(euclidean_distance(centroids[j], new_centroids[j]) for j in range(k))
print(f"--- 迭代 {i + 1} ---")
print(f"新质心: {new_centroids}")
print(f"损失: {loss:.4f}, 质心总位移: {total_shift:.6f}")
if total_shift < epsilon:
print(f"\n算法在 {i + 1} 次迭代后收敛。")
return new_centroids, clusters, loss_history
centroids = new_centroids
print(f"\n在 {max_iterations} 次迭代后未达到收敛阈值。")
return centroids, clusters, loss_history
if __name__ == "__main__":
dataset = [
[1.0, 2.0], [1.2, 1.8], [0.8, 2.2], [1.1, 1.9],
[5.0, 8.0], [5.2, 8.1], [4.8, 7.9], [5.1, 8.2],
[9.0, 2.0], [9.2, 1.8], [8.8, 2.2], [9.1, 1.9],
[5.0, 5.0], [5.2, 4.8], [4.8, 5.2], [5.1, 4.9], [4.9, 5.1]
]
print(f'数据集大小: {len(dataset)}')
K = 4
EPSILON = 1e-4
MAX_ITER = 100
random.seed(0)
final_centroids, final_clusters, loss_history = Kmeans(dataset, K, EPSILON, MAX_ITER)
print("\n==================== 最终结果 ====================")
print("最终质心:")
for i, centroid in enumerate(final_centroids):
print(f" 簇 {i + 1}: ({centroid[0]:.4f}, {centroid[1]:.4f})")
print("\n聚类分配 (数据点索引 -> 簇索引):")
for i, cluster_idx in enumerate(final_clusters):
print(f" 点 {i} -> 簇 {cluster_idx}")
print("\n损失函数历史:")
for i, loss in enumerate(loss_history):
print(f" 迭代 {i + 1}: {loss:.4f}")
|
2301_82233644/machine-learning-course
|
assignment3/2班39.py
|
Python
|
mit
| 3,654
|
import math
import random
def assign_cluster(x, c):
distances = []
for center in c:
dist = math.sqrt(sum((x[i] - center[i])**2 for i in range(len(x))))
distances.append(dist)
return distances.index(min(distances))
def Kmeans(data, k, epsilon=1e-4, iteration=100):
if not data or k <= 0 or k > len(data):
raise ValueError("Invalid input parameters")
n_features = len(data[0])
centroids = random.sample(data, k)
for iter_count in range(iteration):
clusters = {i: [] for i in range(k)}
for point in data:
cluster_idx = assign_cluster(point, centroids)
clusters[cluster_idx].append(point)
new_centroids = []
for i in range(k):
if clusters[i]:
centroid = []
for j in range(n_features):
dim_sum = sum(point[j] for point in clusters[i])
centroid.append(dim_sum / len(clusters[i]))
new_centroids.append(centroid)
else:
new_centroids.append(centroids[i])
max_change = 0
for i in range(k):
change = math.sqrt(sum((centroids[i][j] - new_centroids[i][j])**2 for j in range(n_features)))
max_change = max(max_change, change)
centroids = new_centroids
if max_change < epsilon:
print(f"Converged after {iter_count + 1} iterations")
break
return clusters, centroids
if __name__ == "__main__":
random.seed(42)
sample_data = []
for center in [[2, 2], [8, 8], [8, 2]]:
for _ in range(10):
sample_data.append([
center[0] + random.gauss(0, 1.5),
center[1] + random.gauss(0, 1.5)
])
clusters, centroids = Kmeans(sample_data, k=3, epsilon=1e-4, iteration=100)
print("聚类中心:")
for i, centroid in enumerate(centroids):
print(f"聚类 {i}: ({centroid[0]:.2f}, {centroid[1]:.2f})")
print("\n聚类结果:")
for cluster_idx, points in clusters.items():
print(f"聚类 {cluster_idx}: {len(points)} 个点")
for point in points:
print(f" ({point[0]:.2f}, {point[1]:.2f})")
|
2301_82233644/machine-learning-course
|
assignment3/2班40.py
|
Python
|
mit
| 2,271
|
import random
import math
def assign_cluster(x, c):
"""
将数据点x分配到最近的聚类中心
参数:
x: 数据点(列表或元组)
c: 聚类中心列表
返回:
最近的聚类中心的索引
"""
min_dist = float('inf')
cluster_idx = 0
for i, center in enumerate(c):
# 计算欧氏距离
dist = math.sqrt(sum((x[j] - center[j]) ** 2 for j in range(len(x))))
if dist < min_dist:
min_dist = dist
cluster_idx = i
return cluster_idx
def Kmeans(data, k, epsilon, iteration):
"""
K均值聚类算法
参数:
data: 数据点列表,每个数据点是一个列表或元组
k: 聚类数量
epsilon: 收敛阈值
iteration: 最大迭代次数
返回:
clusters: 每个数据点所属的聚类索引列表
centers: 最终的聚类中心列表
"""
if len(data) == 0 or k <= 0:
return [], []
# 初始化聚类中心(随机选择k个数据点)
centers = [list(data[i]) for i in random.sample(range(len(data)), min(k, len(data)))]
for _ in range(iteration):
# 分配每个数据点到最近的聚类中心
clusters = [assign_cluster(x, centers) for x in data]
# 计算新的聚类中心
new_centers = []
for i in range(k):
# 找到属于第i个聚类的所有点
cluster_points = [data[j] for j in range(len(data)) if clusters[j] == i]
if len(cluster_points) > 0:
# 计算均值作为新中心
new_center = [sum(point[d] for point in cluster_points) / len(cluster_points)
for d in range(len(data[0]))]
new_centers.append(new_center)
else:
# 如果某个聚类没有点,保持原中心
new_centers.append(centers[i])
# 检查是否收敛
max_change = max(math.sqrt(sum((centers[i][d] - new_centers[i][d]) ** 2
for d in range(len(centers[i]))))
for i in range(k))
if max_change < epsilon:
break
centers = new_centers
return clusters, centers
# 测试示例
if __name__ == "__main__":
# 示例数据
data = [
[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11],
[8, 2], [10, 2], [9, 3], [2, 1], [5, 5], [6, 6]
]
k = 3
epsilon = 0.01
max_iter = 100
clusters, centers = Kmeans(data, k, epsilon, max_iter)
print("聚类结果:")
for i, cluster_id in enumerate(clusters):
print(f"数据点 {data[i]} -> 聚类 {cluster_id}")
print("\n聚类中心:")
for i, center in enumerate(centers):
print(f"聚类 {i}: {center}")
|
2301_82233644/machine-learning-course
|
assignment3/2班50.py
|
Python
|
mit
| 2,920
|
import random
import math
def assign_cluster(x, c):
min_distance = float("inf") #初始化最小距离
cluster_index = 0
for i, center in enumerate(c):
#计算欧氏距离
distance = math.sqrt(sum((xi - ci) ** 2 for xi, ci in zip(x, center)))
if distance < min_distance:
min_distance = distance
cluster_index = i
return cluster_index
def Kmeans(data, k, epsilon=1e-4, max_iterations=100):
#随机选择中心
centers = random.sample(data, k)
#初始化聚类结果
for _ in range(max_iterations):
clusters = [[] for _ in range(k)]
labels = []
for point in data:
cluster_idx = assign_cluster(point, centers)
clusters[cluster_idx].append(point)
labels.append(cluster_idx)
#更新中心点
new_centers = []
for cluster in clusters:
if not cluster:
new_centers.append(random.choice(data))
else:
new_center = [sum(dim) / len(cluster) for dim in zip(*cluster)]
new_centers.append(new_center)
#检查中心点变化是否小于阈值
center_shift = sum(
math.sqrt(sum((ci - nci) ** 2 for ci, nci in zip(center, new_center)))
for center, new_center in zip(centers, new_centers)
)
if center_shift < epsilon:
break
centers = new_centers
return centers, labels
if __name__ == "__main__":
# 生成3类随机数据点
centers = [[1, 1], [4, 4], [7, 7]]
data = []
for center in centers:
for _ in range(100):
data.append([random.gauss(center[0], 0.5), random.gauss(center[1], 0.5)])
# 运行K-Means算法
k = 3
final_centers, labels = Kmeans(data, k)
# 输出结果
print("最终聚类中心:")
for i, center in enumerate(final_centers):
print(f"簇{i}: {center}")
# 可视化
import matplotlib.pyplot as plt
colors = ['r', 'g', 'b']
for i, point in enumerate(data):
plt.scatter(point[0], point[1], c=colors[labels[i]])
for center in final_centers:
plt.scatter(center[0], center[1], c='black', marker='x', s=100)
plt.title("K-Means")
plt.show()
|
2301_82233644/machine-learning-course
|
assignment3/2班67.py
|
Python
|
mit
| 2,266
|
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
def assign_cluster(x, c):
"""
将样本 x 分配到最近的聚类中心
"""
distances = np.linalg.norm(x[:, np.newaxis] - c, axis=2) # shape: (n_samples, K)
y = np.argmin(distances, axis=1)
return y
def Kmean(data, K, epsilon=1e-4, max_iteration=100):
"""
K-Means 聚类算法
"""
n_samples, n_features = data.shape
np.random.seed(42)
centers = data[np.random.choice(n_samples, K, replace=False)]
for i in range(max_iteration):
# Step 1: 分配簇
labels = assign_cluster(data, centers)
# Step 2: 更新中心
new_centers = np.array([
data[labels == k].mean(axis=0) if np.any(labels == k) else centers[k]
for k in range(K)
])
# Step 3: 判断收敛
shift = np.linalg.norm(new_centers - centers)
if shift < epsilon:
print(f"第 {i+1} 次迭代后收敛,中心移动量 {shift:.6f}")
break
centers = new_centers
return centers, labels
if __name__ == "__main__":
# 生成二维数据
data, _ = make_blobs(n_samples=200, centers=3, n_features=2, random_state=42)
centers, labels = Kmean(data, K=3)
print("最终聚类中心:\n", centers)
# ======================
# 可视化
# ======================
plt.figure(figsize=(8, 6))
# 绘制每个簇的样本点
for k in range(3):
plt.scatter(data[labels == k, 0], data[labels == k, 1], label=f'Cluster {k}', alpha=0.6)
# 绘制中心点
plt.scatter(centers[:, 0], centers[:, 1], c='black', s=200, marker='X', label='Centers')
plt.title("K-Means Clustering Result")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.legend()
plt.grid(True)
plt.show()
|
2301_82233644/machine-learning-course
|
assignment3/2班70.py
|
Python
|
mit
| 1,862
|
import math
import numpy as np
from collections import Counter
from operator import itemgetter
class KNN:
def __init__(self, k=3, task='classification'):
"""
初始化 KNN 模型
参数:
k: 近邻数量
task: 任务类型,'classification' 或 'regression'
"""
self.k = k
self.task = task
self.X_train = None
self.y_train = None
def fit(self, X, y):
"""
训练模型,存储训练数据
参数:
X: 训练特征,形状为 (n_samples, n_features)
y: 训练标签,形状为 (n_samples,)
"""
self.X_train = X
self.y_train = y
def _euclidean_distance(self, a, b):
"""
计算两个向量之间的欧氏距离
"""
return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))
def _get_k_neighbors(self, x):
"""
获取距离目标样本最近的 k 个邻居
返回:
neighbors: 最近的 k 个邻居的索引和距离
"""
distances = []
# 计算与所有训练样本的距离
for i, train_sample in enumerate(self.X_train):
dist = self._euclidean_distance(x, train_sample)
distances.append((i, dist))
# 按距离排序并取前 k 个
distances.sort(key=itemgetter(1))
neighbors = distances[:self.k]
return neighbors
def predict(self, X):
"""
预测新样本的标签
参数:
X: 测试特征,形状为 (n_samples, n_features)
返回:
predictions: 预测结果
"""
predictions = []
for sample in X:
# 获取 k 个最近邻居
neighbors = self._get_k_neighbors(sample)
if self.task == 'classification':
# 分类任务:多数投票
neighbor_labels = [self.y_train[idx] for idx, _ in neighbors]
most_common = Counter(neighbor_labels).most_common(1)
predictions.append(most_common[0][0])
elif self.task == 'regression':
# 回归任务:平均值
neighbor_labels = [self.y_train[idx] for idx, _ in neighbors]
predictions.append(sum(neighbor_labels) / len(neighbor_labels))
return predictions
def predict_proba(self, X):
"""
分类任务中返回每个类别的概率(仅适用于分类任务)
参数:
X: 测试特征,形状为 (n_samples, n_features)
返回:
probabilities: 每个样本属于每个类别的概率
"""
if self.task != 'classification':
raise ValueError("predict_proba 仅适用于分类任务")
probabilities = []
for sample in X:
# 获取 k 个最近邻居
neighbors = self._get_k_neighbors(sample)
# 统计每个类别的数量
neighbor_labels = [self.y_train[idx] for idx, _ in neighbors]
label_counts = Counter(neighbor_labels)
# 计算概率
prob_dict = {}
total = len(neighbors)
for label in set(self.y_train):
prob_dict[label] = label_counts.get(label, 0) / total
probabilities.append(prob_dict)
return probabilities
|
2301_82233644/machine-learning-course
|
assignment4/1班01.py
|
Python
|
mit
| 3,396
|
import math
from collections import Counter
def euclidean_distance(x1, x2):
if len(x1) != len(x2):
raise ValueError("两个样本的维度必须一致")
squared_diff_sum = sum((a - b) ** 2 for a, b in zip(x1, x2))
return math.sqrt(squared_diff_sum)
def KNN(X_train, y_train, X_test, k=5, task="classification", distance_func=euclidean_distance):
# 1. 输入参数校验
if len(X_train) != len(y_train):
raise ValueError("训练样本特征与标签数量必须一致")
if k < 1 or k > len(X_train):
raise ValueError(f"k值必须满足 1 ≤ k ≤ 训练样本数(当前训练样本数:{len(X_train)})")
if task not in ["classification", "regression"]:
raise ValueError('task必须为 "classification" 或 "regression"')
is_single_test = not isinstance(X_test[0], (list, tuple))
if is_single_test:
X_test = [X_test]
# 2. 验证所有样本维度一致
n_features = len(X_train[0]) if X_train else 0
for sample in X_train + X_test:
if len(sample) != n_features:
raise ValueError("所有训练样本和测试样本必须具有相同的维度")
# 3. 对每个测试样本执行预测
predictions = []
for test_sample in X_test:
distances = []
for train_sample, train_label in zip(X_train, y_train):
dist = distance_func(test_sample, train_sample)
distances.append((dist, train_label))
distances.sort(key=lambda x: x[0])
k_neighbors = distances[:k]
k_neighbor_labels = [label for (dist, label) in k_neighbors]
if task == "classification":
vote_result = Counter(k_neighbor_labels).most_common(1)[0][0]
predictions.append(vote_result)
else:
regression_result = sum(k_neighbor_labels) / len(k_neighbor_labels)
predictions.append(regression_result)
return predictions[0] if is_single_test else predictions
|
2301_82233644/machine-learning-course
|
assignment4/1班13.py
|
Python
|
mit
| 1,966
|
import math
def euclidean_distance(point1, point2):
"""手动计算欧几里得距离"""
if len(point1) != len(point2):
raise ValueError("点的维度不一致")
squared_sum = 0
for i in range(len(point1)):
squared_sum += (point1[i] - point2[i]) ** 2
return math.sqrt(squared_sum)
class KNN:
def __init__(self, k, label_num):
self.k = k
self.label_num = label_num
def fit(self, x_train, y_train):
self.x_train = x_train
self.y_train = y_train
def get_knn_indices(self, x):
"""手动实现获取K近邻索引"""
# 计算所有距离
distances = []
for i, train_point in enumerate(self.x_train):
dist = euclidean_distance(train_point, x)
distances.append((dist, i))
# 手动排序(冒泡排序)
for i in range(len(distances)):
for j in range(i + 1, len(distances)):
if distances[j][0] < distances[i][0]:
distances[i], distances[j] = distances[j], distances[i]
# 取前k个索引
knn_indices = [idx for _, idx in distances[:self.k]]
return knn_indices
def get_label(self, x):
"""手动实现类别预测"""
knn_indices = self.get_knn_indices(x)
# 手动统计类别
label_statistic = [0] * self.label_num
for index in knn_indices:
label = self.y_train[index]
label_statistic[label] += 1
# 手动找最大值
max_count = -1
best_label = -1
for label, count in enumerate(label_statistic):
if count > max_count:
max_count = count
best_label = label
return best_label
def predict(self, x_test):
"""手动实现批量预测"""
predicted_labels = []
for x in x_test:
predicted_labels.append(self.get_label(x))
return predicted_labels
def score(self, x_test, y_test):
"""手动计算准确率"""
predictions = self.predict(x_test)
correct = 0
for pred, true in zip(predictions, y_test):
if pred == true:
correct += 1
return correct / len(y_test)
|
2301_82233644/machine-learning-course
|
assignment4/1班23.py
|
Python
|
mit
| 2,293
|
import math
def euclidean_distance(x1, x2):
"""
计算两个数据点之间的欧氏距离
参数:
x1, x2: 数据点(列表或元组)
返回:
欧氏距离
"""
return math.sqrt(sum((x1[i] - x2[i]) ** 2 for i in range(len(x1))))
def find_k_nearest_neighbors(x, X_train, k):
"""
找到数据点x的k个最近邻
参数:
x: 待查询的数据点
X_train: 训练数据点列表
k: 近邻数量
返回:
k个最近邻的索引列表
"""
distances = [(i, euclidean_distance(x, X_train[i])) for i in range(len(X_train))]
distances.sort(key=lambda item: item[1])
return [idx for idx, _ in distances[:k]]
def KNN_predict(x, X_train, y_train, k):
"""
K近邻分类预测
参数:
x: 待预测的数据点
X_train: 训练数据点列表
y_train: 训练标签列表
k: 近邻数量
返回:
预测的类别
"""
neighbors_idx = find_k_nearest_neighbors(x, X_train, k)
neighbor_labels = [y_train[i] for i in neighbors_idx]
# 投票决定类别
label_counts = {}
for label in neighbor_labels:
label_counts[label] = label_counts.get(label, 0) + 1
# 返回出现次数最多的类别
return max(label_counts, key=label_counts.get)
def KNN_predict_regression(x, X_train, y_train, k):
"""
K近邻回归预测
参数:
x: 待预测的数据点
X_train: 训练数据点列表
y_train: 训练值列表
k: 近邻数量
返回:
预测值(k个近邻的平均值)
"""
neighbors_idx = find_k_nearest_neighbors(x, X_train, k)
neighbor_values = [y_train[i] for i in neighbors_idx]
return sum(neighbor_values) / len(neighbor_values)
# 测试示例
if __name__ == "__main__":
# 分类示例
print("=== KNN分类示例 ===")
X_train = [
[1, 1], [1, 2], [2, 1], [2, 2],
[5, 5], [5, 6], [6, 5], [6, 6],
[9, 9], [9, 10], [10, 9], [10, 10]
]
y_train = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
test_point = [3, 3]
k = 3
prediction = KNN_predict(test_point, X_train, y_train, k)
print(f"测试点 {test_point} 的预测类别: {prediction}")
# 回归示例
print("\n=== KNN回归示例 ===")
X_train_reg = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
y_train_reg = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
test_point_reg = [5.5]
k_reg = 3
prediction_reg = KNN_predict_regression(test_point_reg, X_train_reg, y_train_reg, k_reg)
print(f"测试点 {test_point_reg} 的预测值: {prediction_reg}")
|
2301_82233644/machine-learning-course
|
assignment4/2班50.py
|
Python
|
mit
| 2,698
|
__version__ = "1.2.0"
|
2302_79757062/print_designer
|
print_designer/__init__.py
|
Python
|
agpl-3.0
| 22
|
CUSTOM_FIELDS = {
"Print Format": [
{
"default": "0",
"fieldname": "print_designer",
"fieldtype": "Check",
"hidden": 1,
"label": "Print Designer",
},
{
"fieldname": "print_designer_print_format",
"fieldtype": "JSON",
"hidden": 1,
"label": "Print Designer Print Format",
"description": "This has json object that is used by main.html jinja template to render the print format.",
},
{
"fieldname": "print_designer_header",
"fieldtype": "JSON",
"hidden": 1,
"label": "Print Designer Header",
},
{
"fieldname": "print_designer_body",
"fieldtype": "JSON",
"hidden": 1,
"label": "Print Designer Body",
},
{
"fieldname": "print_designer_after_table",
"fieldtype": "JSON",
"hidden": 1,
"label": "Print Designer After Table",
},
{
"fieldname": "print_designer_footer",
"fieldtype": "JSON",
"hidden": 1,
"label": "Print Designer Footer",
},
{
"fieldname": "print_designer_settings",
"hidden": 1,
"fieldtype": "JSON",
"label": "Print Designer Settings",
},
{
"fieldname": "print_designer_preview_img",
"hidden": 1,
"fieldtype": "Attach Image",
"label": "Print Designer Preview Image",
},
{
"depends_on": "eval:doc.print_designer && doc.standard == 'Yes'",
"fieldname": "print_designer_template_app",
"fieldtype": "Select",
"label": "Print Designer Template Location",
"default": "print_designer",
"insert_after": "standard",
},
]
}
|
2302_79757062/print_designer
|
print_designer/custom_fields.py
|
Python
|
agpl-3.0
| 1,479
|
import os
import shutil
from pathlib import Path
import frappe
from frappe.modules.import_file import import_file_by_path
from frappe.utils import get_files_path
"""
features:
- Print Designer App can have default formats for all installed apps.
- Any Custom/Standard App can have default formats for any installed apps
( This will only install formats if print_designer is installed ).
- This will be useful when we have standalone formats that can be used without print designer app.
when print_designer app is installed
- get hooks from all installed apps including pd and load default formats from defined folders.
when any new app is installed
- if exists in print_designer/default_templates, load default formats for newly installed app.
- get hooks from new app and load default formats for all installed apps from app's format dir.
"""
# TODO: handle override of default formats from different apps or even Custom Formats with same name.
# add default formats for all installed apps.
def on_print_designer_install():
for app in frappe.get_installed_apps():
install_default_formats(app=app, load_pd_formats=False)
def get_preview_image_folder_path(print_format):
app = frappe.scrub(frappe.get_doctype_app(print_format.doc_type))
pd_folder = frappe.get_hooks(
"pd_standard_format_folder", app_name=print_format.print_designer_template_app
)
if len(pd_folder) == 0:
pd_folder = ["default_templates"]
return os.path.join(
frappe.get_app_path(print_format.print_designer_template_app), os.path.join(pd_folder[0], app)
)
def update_preview_img(file):
print_format = frappe.get_doc(file.attached_to_doctype, file.attached_to_name)
folder = get_preview_image_folder_path(print_format)
file_name = print_format.print_designer_preview_img.split("/")[-1]
org_path = os.path.join(folder, file_name)
target_path = get_files_path(file_name, is_private=1)
shutil.copy2(org_path, target_path)
# called after install of any new app.
def install_default_formats(app, filter_by="", load_pd_formats=True):
if load_pd_formats:
# load formats from print_designer app if some new app is installed and have default formats
install_default_formats(app="print_designer", filter_by=app, load_pd_formats=False)
# get dir path and load formats from installed app
pd_folder = frappe.get_hooks("pd_standard_format_folder", app_name=app)
if len(pd_folder) == 0:
return
print_formats = get_filtered_formats_by_app(
app=app, templates_folder=pd_folder[0], filter_by=filter_by
)
# preview_files = [f for f in print_formats if f.name.endswith("-preview.json")]
print_formats = [f for f in print_formats if not f.name.endswith("-preview.json")]
for json_file_path in print_formats:
import_file_by_path(path=json_file_path)
frappe.db.commit()
# TODO: enable this after this is released in v15 https://github.com/frappe/frappe/pull/25779
# for json_file_path in preview_files:
# import_file_by_path(path=json_file_path, pre_process=update_preview_img)
# frappe.db.commit()
# for pf in frappe.db.get_all("Print Format", filters={"standard": "Yes", "print_designer": 1}):
# updated_url = frappe.db.get_value(
# "File",
# {
# "attached_to_doctype": "Print Format",
# "attached_to_name": pf.name,
# "attached_to_field": "print_designer_preview_img",
# },
# "file_url",
# )
# if updated_url:
# frappe.set_value("Print Format", pf.name, "print_designer_preview_img", updated_url)
def get_filtered_formats_by_app(app, templates_folder, filter_by=""):
app_path = frappe.get_app_path(app)
if filter_by == "":
folders = Path(os.path.join(app_path, templates_folder))
return get_formats_from_folders(folders=folders)
else:
folder = Path(os.path.join(app_path, templates_folder, filter_by))
return get_json_files(folder)
def get_formats_from_folders(folders):
formats = set()
if not folders.exists():
return formats
for folder in folders.iterdir():
if folder.is_dir() and folder.name in frappe.get_installed_apps():
formats.update(get_json_files(folder))
return formats
def get_json_files(folder):
formats = set()
for json_file in folder.glob("*.json"):
formats.add(json_file)
return formats
|
2302_79757062/print_designer
|
print_designer/default_formats.py
|
Python
|
agpl-3.0
| 4,190
|
from . import __version__ as app_version
app_name = "print_designer"
app_title = "Print Designer"
app_publisher = "Frappe Technologies Pvt Ltd."
app_description = "Frappe App to Design Print Formats using interactive UI."
app_email = "hello@frappe.io"
app_license = "AGPLv3"
# Includes in <head>
# ------------------
# include js, css files in header of desk.html
# app_include_js = ""
# include js, css files in header of web template
# web_include_css = "/assets/print_designer/css/print_designer.css"
# web_include_js = "/assets/print_designer/js/print_designer.js"
# include custom scss in every website theme (without file extension ".scss")
# website_theme_scss = "print_designer/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 = {
"print": "print_designer/client_scripts/print.js",
"point-of-sale": "print_designer/client_scripts/point_of_sale.js",
}
# include js in doctype views
doctype_js = {"Print Format": "print_designer/client_scripts/print_format.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 = "login"
# 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": [
"print_designer.print_designer.page.print_designer.print_designer.render_user_text",
"print_designer.print_designer.page.print_designer.print_designer.convert_css",
"print_designer.print_designer.page.print_designer.print_designer.convert_uom",
"print_designer.print_designer.page.print_designer.print_designer.get_barcode",
]
}
# Installation
# ------------
before_install = "print_designer.install.before_install"
after_install = "print_designer.install.after_install"
after_app_install = "print_designer.install.after_app_install"
# Uninstallation
# ------------
before_uninstall = "print_designer.uninstall.before_uninstall"
# after_uninstall = "print_designer.uninstall.after_uninstall"
# ------------
# PDF
# ------------
pdf_header_html = "print_designer.pdf.pdf_header_footer_html"
pdf_body_html = "print_designer.pdf.pdf_body_html"
pdf_footer_html = "print_designer.pdf.pdf_header_footer_html"
get_print_format_template = "print_designer.pdf.get_print_format_template"
# Desk Notifications
# ------------------
# See frappe.core.notifications.get_notification_config
# notification_config = "print_designer.notifications.get_notification_config"
# Permissions
# -----------
# Permissions evaluated in scripted ways
# permission_query_conditions = {
# "Event": "frappe.desk.doctype.event.event.get_permission_query_conditions",
# }
#
# has_permission = {
# "Event": "frappe.desk.doctype.event.event.has_permission",
# }
# DocType Class
# ---------------
# Override standard doctype classes
override_doctype_class = {
"Print Format": "print_designer.print_designer.overrides.print_format.PDPrintFormat",
}
# Path Relative to the app folder where default templates should be stored
pd_standard_format_folder = "default_templates"
# Document Events
# ---------------
# Hook on document methods and events
# doc_events = {
# "*": {
# "on_update": "method",
# "on_cancel": "method",
# "on_trash": "method"
# }
# }
# Scheduled Tasks
# ---------------
# scheduler_events = {
# "all": [
# "print_designer.tasks.all"
# ],
# "daily": [
# "print_designer.tasks.daily"
# ],
# "hourly": [
# "print_designer.tasks.hourly"
# ],
# "weekly": [
# "print_designer.tasks.weekly"
# ],
# "monthly": [
# "print_designer.tasks.monthly"
# ],
# }
# Testing
# -------
# before_tests = "print_designer.install.before_tests"
# Overriding Methods
# ------------------------------
#
# override_whitelisted_methods = {
# "frappe.desk.doctype.event.event.get_events": "print_designer.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": "print_designer.task.get_dashboard_data"
# }
# exempt linked doctypes from being automatically cancelled
#
# auto_cancel_exempted_doctypes = ["Auto Repeat"]
# Ignore links to specified DocTypes when deleting documents
# -----------------------------------------------------------
# ignore_links_on_delete = ["Communication", "ToDo"]
# Request Events
# ----------------
# before_request = ["print_designer.utils.before_request"]
# after_request = ["print_designer.utils.after_request"]
# Job Events
# ----------
# before_job = ["print_designer.utils.before_job"]
# after_job = ["print_designer.utils.after_job"]
# 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 = [
# "print_designer.auth.validate"
# ]
|
2302_79757062/print_designer
|
print_designer/hooks.py
|
Python
|
agpl-3.0
| 5,666
|
import click
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
from print_designer.custom_fields import CUSTOM_FIELDS
from print_designer.default_formats import install_default_formats, on_print_designer_install
def check_frappe_version():
def major_version(v: str) -> str:
return v.split(".")[0]
frappe_version = major_version(frappe.__version__)
if int(frappe_version) >= 15:
return
click.secho(
f"You're attempting to install Print Designer with Frappe version {frappe_version}. "
"This is not supported and will result in broken install. Please install it using Version 15 or Develop branch.",
fg="red",
)
raise SystemExit(1)
def before_install():
check_frappe_version()
def after_install():
create_custom_fields(CUSTOM_FIELDS, ignore_validate=True)
on_print_designer_install()
def after_app_install(app):
if app != "print_designer":
install_default_formats(app)
|
2302_79757062/print_designer
|
print_designer/install.py
|
Python
|
agpl-3.0
| 945
|
import frappe
from print_designer.patches.patch_utils import patch_formats
def execute():
"""changing isDynamicHeight property to heightType property in text and table elements"""
def element_callback(el):
if el.get("type") == "text" and not (el.get("isDynamic") or el.get("parseJinja")):
return
if not "isDynamicHeight" in el:
el["isDynamicHeight"] = False
if el["isDynamicHeight"]:
el["heightType"] = "auto"
else:
el["heightType"] = "fixed"
patch_formats(
{"element": element_callback},
types=["text", "table"],
)
|
2302_79757062/print_designer
|
print_designer/patches/change_dynamic_height_variable.py
|
Python
|
agpl-3.0
| 551
|
import frappe
from print_designer.pdf import is_older_schema
def patch_format():
print_formats = frappe.get_all(
"Print Format",
filters={"print_designer": 1},
fields=[
"name",
"print_designer_print_format",
"print_designer_settings",
],
)
for pf in print_formats:
settings = frappe.json.loads(pf.print_designer_settings or "{}")
if not is_older_schema(settings=settings, current_version="1.1.0") and is_older_schema(
settings=settings, current_version="1.3.0"
):
pf_print_format = frappe.json.loads(pf.print_designer_print_format or "{}")
if pf_print_format.get("header", False):
if type(pf_print_format["header"]) == list:
# issue #285
pf_print_format["header"] = {
"firstPage": pf_print_format["header"],
"oddPage": pf_print_format["header"],
"evenPage": pf_print_format["header"],
"lastPage": pf_print_format["header"],
}
for headerType in ["firstPage", "oddPage", "evenPage", "lastPage"]:
for row in pf_print_format["header"][headerType]:
row["layoutType"] = "row"
for column in row["childrens"]:
column["layoutType"] = "column"
if pf_print_format.get("footer", False):
if type(pf_print_format["footer"]) == list:
# issue #285
pf_print_format["footer"] = {
"firstPage": pf_print_format["footer"],
"oddPage": pf_print_format["footer"],
"evenPage": pf_print_format["footer"],
"lastPage": pf_print_format["footer"],
}
for footerType in ["firstPage", "oddPage", "evenPage", "lastPage"]:
for row in pf_print_format["footer"][footerType]:
row["layoutType"] = "row"
for column in row["childrens"]:
column["layoutType"] = "column"
if pf_print_format.get("body", False):
for row in pf_print_format["body"]:
row["layoutType"] = "row"
for column in row["childrens"]:
column["layoutType"] = "column"
# body elements should be inside page object forgot to add it in patch move_header_footers_to_new_schema
pf_print_format["body"] = [
{
"index": 0,
"type": "page",
"childrens": pf_print_format["body"],
"isDropZone": True,
}
]
frappe.set_value(
"Print Format",
pf.name,
{"print_designer_print_format": frappe.json.dumps(pf_print_format)},
)
return print_formats
def execute():
"""add layoutType to rows and columns in old print formats."""
patch_format()
|
2302_79757062/print_designer
|
print_designer/patches/convert_formats_for_recursive_container.py
|
Python
|
agpl-3.0
| 2,426
|
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
from print_designer.custom_fields import CUSTOM_FIELDS
def custom_field_patch():
create_custom_fields(CUSTOM_FIELDS, ignore_validate=True)
|
2302_79757062/print_designer
|
print_designer/patches/create_custom_fields.py
|
Python
|
agpl-3.0
| 224
|
import frappe
def execute():
"""Adds globalStyles for barcode for all print formats that uses print designer"""
print_formats = frappe.get_all(
"Print Format",
filters={"print_designer": 1},
fields=["name", "print_designer_settings"],
as_list=1,
)
for pf in print_formats:
settings = frappe.parse_json(pf[1])
if settings:
gs = settings["globalStyles"]
gs["barcode"] = {
"isGlobalStyle": True,
"barcodeFormat": "qrcode",
"styleEditMode": "main",
"type": "barcode",
"isDynamic": False,
"mainRuleSelector": ".barcode",
"style": {
"display": "block",
"border": "none",
"borderWidth": "0px",
"borderColor": "#000000",
"borderStyle": "solid",
"borderRadius": 0,
"backgroundColor": "",
"paddingTop": "0px",
"paddingBottom": "0px",
"paddingLeft": "0px",
"paddingRight": "0px",
"margin": "0px",
"minWidth": "0px",
"minHeight": "0px",
"boxShadow": "none",
"whiteSpace": "normal",
"userSelect": "none",
"opacity": 1,
},
}
frappe.db.set_value("Print Format", pf[0], "print_designer_settings", frappe.as_json(settings))
|
2302_79757062/print_designer
|
print_designer/patches/introduce_barcode.py
|
Python
|
agpl-3.0
| 1,159
|
import frappe
from print_designer.patches.patch_utils import patch_formats
def execute():
"""Modify Formats to work with New Column Style Feature"""
def element_callback(el):
el["selectedColumn"] = None
for col in el["columns"]:
col["style"] = {}
col["applyStyleToHeader"] = False
patch_formats(
{"element": element_callback},
types=["table"],
)
|
2302_79757062/print_designer
|
print_designer/patches/introduce_column_style.py
|
Python
|
agpl-3.0
| 369
|
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
def execute():
"""Add print_designer_print_format field for Print Format."""
CUSTOM_FIELDS = {
"Print Format": [
{
"fieldname": "print_designer_print_format",
"fieldtype": "JSON",
"hidden": 1,
"label": "Print Designer Print Format",
"description": "This has json object that is used by jinja template to render the print format.",
}
]
}
create_custom_fields(CUSTOM_FIELDS, ignore_validate=True)
|
2302_79757062/print_designer
|
print_designer/patches/introduce_dynamic_containers.py
|
Python
|
agpl-3.0
| 526
|
import frappe
from print_designer.patches.patch_utils import patch_formats
def execute():
"""Updating Table and Dynamic Text Elements to have property isDynamicHeight with default value as True"""
def element_callback(el):
if el.get("type") == "text" and not el.get("isDynamic"):
return
if not "isDynamicHeight" in el:
el["isDynamicHeight"] = False
patch_formats(
{"element": element_callback},
types=["text", "table"],
)
|
2302_79757062/print_designer
|
print_designer/patches/introduce_dynamic_height.py
|
Python
|
agpl-3.0
| 446
|
import frappe
from print_designer.patches.patch_utils import patch_formats
def execute():
"""Add parseJinja property in DynamicFields (Static) and staticText"""
def element_callback(el):
if el.get("type") == "text" and not el.get("isDynamic"):
el["parseJinja"] = False
def dynamic_content_callback(el):
if el.get("is_static", False):
el["parseJinja"] = False
patch_formats(
{"element": element_callback, "dynamic_content": dynamic_content_callback},
types=["text", "table", "barcode"],
)
|
2302_79757062/print_designer
|
print_designer/patches/introduce_jinja.py
|
Python
|
agpl-3.0
| 513
|
import frappe
def execute():
"""Adds Schema Versioning for Print Designer inside Print Format Settings to handle changes that are not patchable and needs to be handled in the code"""
print_formats = frappe.get_all(
"Print Format",
filters={"print_designer": 1},
fields=["name", "print_designer_settings"],
as_list=1,
)
for pf in print_formats:
settings = frappe.parse_json(pf[1])
if settings:
settings["schema_version"] = "1.0.0"
frappe.db.set_value("Print Format", pf[0], "print_designer_settings", frappe.as_json(settings))
|
2302_79757062/print_designer
|
print_designer/patches/introduce_schema_versioning.py
|
Python
|
agpl-3.0
| 550
|
import frappe
from print_designer.patches.patch_utils import patch_formats
def execute():
"""Introduce suffix to dynamic content elements"""
def dynamic_content_callback(el):
if not el.get("is_static", True):
if not "suffix" in el:
el["suffix"] = None
patch_formats(
{"dynamic_content": dynamic_content_callback},
types=["text", "table"],
)
|
2302_79757062/print_designer
|
print_designer/patches/introduce_suffix_dynamic_content.py
|
Python
|
agpl-3.0
| 363
|
import frappe
from print_designer.patches.patch_utils import patch_formats
def execute():
"""Add altStyle object for alternate rows in table elements and in globalStyles of print formats that uses print designer"""
print_formats = frappe.get_all(
"Print Format",
filters={"print_designer": 1},
fields=["name", "print_designer_settings"],
as_list=1,
)
for pf in print_formats:
settings = frappe.parse_json(pf[1])
if settings:
# If globalStyles is not present, skip
if not (gs := settings.get("globalStyles")):
continue
gs["table"]["altStyle"] = {}
frappe.db.set_value("Print Format", pf[0], "print_designer_settings", frappe.as_json(settings))
def element_callback(el):
el["altStyle"] = {}
patch_formats(
{"element": element_callback},
types=["table"],
)
|
2302_79757062/print_designer
|
print_designer/patches/introduce_table_alt_row_styles.py
|
Python
|
agpl-3.0
| 801
|
import frappe
from print_designer.patches.patch_utils import patch_formats
def execute():
"""Updating all style objects to have zIndex 0 in print formats that uses print designer"""
def style(style):
style["zIndex"] = 0
patch_formats(
{"style": style},
)
|
2302_79757062/print_designer
|
print_designer/patches/introduce_z_index.py
|
Python
|
agpl-3.0
| 268
|
import frappe
from print_designer.pdf import is_older_schema
def patch_format():
print_formats = frappe.get_all(
"Print Format",
filters={"print_designer": 1},
fields=[
"name",
"print_designer_header",
"print_designer_body",
"print_designer_after_table",
"print_designer_footer",
"print_designer_print_format",
"print_designer_settings",
],
)
for pf in print_formats:
settings = frappe.json.loads(pf.print_designer_settings or "{}")
header_childrens = frappe.json.loads(pf.print_designer_header or "[]")
header_data = [
{
"type": "page",
"childrens": header_childrens,
"firstPage": True,
"oddPage": True,
"evenPage": True,
"lastPage": True,
}
]
footer_childrens = frappe.json.loads(pf.print_designer_footer or "[]")
footer_data = [
{
"type": "page",
"childrens": footer_childrens,
"firstPage": True,
"oddPage": True,
"evenPage": True,
"lastPage": True,
}
]
for child in footer_childrens:
child["startY"] -= (
settings["page"].get("height", 0)
- settings["page"].get("marginTop", 0)
- settings["page"].get("footerHeight", 0)
)
childrens = frappe.json.loads(pf.print_designer_body or "[]")
bodyPage = [
{
"index": 0,
"type": "page",
"childrens": childrens,
"isDropZone": True,
}
]
object_to_save = {
"print_designer_header": frappe.json.dumps(header_data),
"print_designer_body": frappe.json.dumps(bodyPage),
"print_designer_footer": frappe.json.dumps(footer_data),
"print_designer_settings": frappe.json.dumps(settings),
}
if not is_older_schema(settings=settings, current_version="1.1.0"):
pf_print_format = frappe.json.loads(pf.print_designer_print_format)
if "header" in pf_print_format:
pf_print_format["header"] = {
"firstPage": pf_print_format["header"],
"oddPage": pf_print_format["header"],
"evenPage": pf_print_format["header"],
"lastPage": pf_print_format["header"],
}
if "footer" in pf_print_format:
pf_print_format["footer"] = {
"firstPage": pf_print_format["footer"],
"oddPage": pf_print_format["footer"],
"evenPage": pf_print_format["footer"],
"lastPage": pf_print_format["footer"],
}
object_to_save["print_designer_print_format"] = frappe.json.dumps(pf_print_format)
frappe.set_value(
"Print Format",
pf.name,
object_to_save,
)
return print_formats
def execute():
"""Moved header and footer to new schema."""
patch_format()
|
2302_79757062/print_designer
|
print_designer/patches/move_header_footers_to_new_schema.py
|
Python
|
agpl-3.0
| 2,503
|
# Print Designer's entire schema is in JSON and have some predefined schema,
# This file contains Functions that can be used on almost all patches that needs to manipulate element data structure.
# Go through the code once to understand how it works before using it.
from typing import Callable, Dict, List, Optional, Union
import frappe
from print_designer.pdf import is_older_schema
"""
Example Callback Functions used to Demonstrate Data Structure.
Example functions are just printing the values of the object passed to them.
Warning: Creating another object and returning it will not work. you need to update the existing object.
"""
# The 'element' callback is executed on every element object that is included in the 'types' list.
def element(element):
print("*" * 80, "-" * 32 + " Element Object " + "-" * 32, element, "*" * 80, sep="\n")
# The 'dynamic_content' callback is executed on every 'dynamicContent' field within an element object that is included in the 'types' list.
# The 'dynamicContent' is currently used in text with 'isDynamic', barcode, and inside table columns.
def dynamic_content(element):
print("*" * 80, "-" * 28 + " Dynamic Content Object " + "-" * 28, element, "*" * 80, sep="\n")
# The 'style' callback is executed on every style object from all element objects that are included in the 'types' list.
def style(style):
print("*" * 80, "-" * 33 + " Style Object " + "-" * 33, style, "*" * 80, sep="\n")
# 'dynamic_content_style' callback is executed on every style object from the 'dynamicContent' field within an element object that is included in the 'types' list.
def dynamic_content_style(style):
print("*" * 80, "-" * 25 + " Dynamic Content Style Object " + "-" * 25, style, "*" * 80, sep="\n")
"""
Example callbacks object that should be passed to patch_formats function
You don't need to pass all the callbacks, you can pass only the callbacks that you need.
"""
callbacks = {
"element": element,
"dynamic_content": dynamic_content,
"style": style,
"dynamic_content_style": dynamic_content_style,
}
"""
See how it works
you need print designer print formats with actual elements to see the output of this function.
1. Open Console
bench --site your-site-name console --autorelod
2. run this command to see the structure and how it works
from print_designer.patches.patch_utils import *
patch_formats(callbacks)
If you want to run callback on specific Element Type just pass types to function
e.g. callbacks will only run on elements that are text, barcode and table
patch_formats(callbacks, types=["text", "barcode", "table"])
While developing patches, pass save=False to function so that it will not save the changes to database.
patch_formats(callbacks, save=False)
"""
def patch_formats(
callbacks: Union[Callable[[Dict], None], Dict[str, Callable[[Dict], None]]],
types: Optional[List[str]] = None,
update_print_json: bool = False,
save: bool = True,
) -> None:
"""
This function applies the given callbacks to all of the print formats that are created using print designer.
:param callbacks: A single callback function or a dictionary of callback functions.
If a dictionary is provided, it should contain keys
`element, dynamic_content, style, dynamic_content_style` each with a function as its value.
Each callback function should take a dictionary as an argument and can modify it and return nothing.
The dictionary passed to the callback function represents a element or style object.
:param update_print_json: If True, the function will update the generated print format json that is used by jinja template.
:param types: A list of print format types to which the callback function should be applied.
If not provided, it defaults to ["text", "image", "barcode", "rectangle", "table"].
"""
if not types:
types = ["text", "image", "barcode", "rectangle", "table"]
print_formats = frappe.get_all(
"Print Format",
filters={"print_designer": 1},
fields=[
"name",
"print_designer_header",
"print_designer_body",
"print_designer_after_table",
"print_designer_footer",
"print_designer_print_format",
"print_designer_settings",
],
as_list=1,
)
for pf in print_formats:
print_json = pf[5] or "{}"
# print_designer_print_format was introduced in schema version 1.1.0 so running this on older version is not required
pf_doc = frappe.get_doc("Print Format", pf[0])
if update_print_json and not is_older_schema(
settings=frappe.json.loads(pf[6] or "{}"), current_version="1.1.0"
):
print_json = frappe.json.loads(print_json)
if print_json.get("header", None):
print_json["header"] = patch_elements(print_json["header"], callbacks, types)
if print_json.get("body", None):
print_json["body"] = patch_elements(print_json["body"], callbacks, types)
if print_json.get("footer", None):
print_json["footer"] = patch_elements(print_json["footer"], callbacks, types)
print_json = frappe.json.dumps(print_json)
pf_doc.update({"print_designer_print_format": print_json})
pf_doc.update(
{
"print_designer_header": frappe.json.dumps(
patch_elements(frappe.json.loads(pf[1] or "[]"), callbacks, types)
),
"print_designer_body": frappe.json.dumps(
patch_elements(frappe.json.loads(pf[2] or "[]"), callbacks, types)
),
"print_designer_after_table": frappe.json.dumps(
patch_elements(frappe.json.loads(pf[3] or "[]"), callbacks, types)
),
"print_designer_footer": frappe.json.dumps(
patch_elements(frappe.json.loads(pf[4] or "[]"), callbacks, types)
),
}
)
if save:
pf_doc.save(ignore_permissions=True, ignore_version=False)
def patch_elements(
data: List[Dict],
callbacks: Union[Callable[[Dict], None], Dict[str, Callable[[Dict], None]]],
types: Optional[List[str]] = None,
) -> List[Dict]:
"""
This function iterates over a list of elements, applying a callback function to each element of a specified type.
:param data: A list of elements where each element is a dictionary.
:param callbacks: A callback function or a dictionary of callback functions to be applied to each element of the specified types.
If a dictionary is provided, it should contain keys `element, dynamic_content, style, dynamic_content_style` each with a function as its value.
:param types: A list of element types to which the callback function should be applied.
Defaults to ["text", "image", "barcode", "rectangle", "table"].
return: The original data list, with the callback function applied to each element of the specified types.
"""
if not types:
types = ["text", "image", "barcode", "rectangle", "table"]
if isinstance(callbacks, dict):
callback = callbacks.get("element", None)
dynamic_content_callback = callbacks.get("dynamic_content", None)
style_callback = callbacks.get("style", None)
dynamic_content_style_callback = callbacks.get("dynamic_content_style", None)
else:
callback = callbacks
for element in data:
if element.get("type") not in types:
if element.get("type") == "rectangle":
childrens = (
frappe.json.loads(element.get("childrens", "[]"))
if isinstance(element.get("childrens"), str)
else element.get("childrens")
)
if len(childrens) > 0:
element["childrens"] = patch_elements(data=childrens, callbacks=callbacks, types=types)
continue
if callback:
callback(element)
if dynamic_content_callback:
if "dynamicContent" in element:
for dy in element.get("dynamicContent"):
dynamic_content_callback(dy)
if dynamic_content_style_callback:
dynamic_content_style_callback(dy.get("style"))
elif "columns" in element:
for col in element.get("columns"):
if "dynamicContent" in col:
for dy in col.get("dynamicContent"):
dynamic_content_callback(dy)
if dynamic_content_style_callback:
dynamic_content_style_callback(dy.get("style"))
if style_callback and "style" in element:
style_callback(element.get("style"))
if element.get("type") == "rectangle":
childrens = (
frappe.json.loads(element.get("childrens", "[]"))
if isinstance(element.get("childrens"), str)
else element.get("childrens")
)
if len(childrens) > 0:
element["childrens"] = patch_elements(data=childrens, callbacks=callbacks, types=types)
return data
|
2302_79757062/print_designer
|
print_designer/patches/patch_utils.py
|
Python
|
agpl-3.0
| 8,504
|
import frappe
def execute():
"""Remove unused style properties in globalStyles for rectangle of print formats that uses print designer"""
print_formats = frappe.get_all(
"Print Format",
filters={"print_designer": 1},
fields=["name", "print_designer_settings"],
as_list=1,
)
for pf in print_formats:
settings = frappe.parse_json(pf[1])
if settings:
# If globalStyles is not present, skip
if not (gs := settings.get("globalStyles")):
continue
for key in ["display", "justifyContent", "alignItems", "alignContent", "flex"]:
if gs["rectangle"]["style"].get(key, False):
del gs["rectangle"]["style"][key]
frappe.db.set_value("Print Format", pf[0], "print_designer_settings", frappe.as_json(settings))
|
2302_79757062/print_designer
|
print_designer/patches/remove_unused_rectangle_gs_properties.py
|
Python
|
agpl-3.0
| 741
|
import frappe
from print_designer.patches.patch_utils import patch_formats
def execute():
"""Rerun patch due to bug in patch utils"""
def element_callback(el):
if el.get("type") == "text" and not el.get("isDynamic"):
if not "parseJinja" in el:
el["parseJinja"] = False
def dynamic_content_callback(el):
if el.get("is_static", False):
if not "parseJinja" in el:
el["parseJinja"] = False
patch_formats(
{"element": element_callback, "dynamic_content": dynamic_content_callback},
types=["text", "table", "barcode"],
)
|
2302_79757062/print_designer
|
print_designer/patches/rerun_introduce_jinja.py
|
Python
|
agpl-3.0
| 548
|
import frappe
def execute():
"""Updates white-space style property in globalStyles of print formats that uses print designer"""
print_formats = frappe.get_all(
"Print Format",
filters={"print_designer": 1},
fields=["name", "print_designer_settings"],
as_list=1,
)
for pf in print_formats:
settings = frappe.parse_json(pf[1])
if settings:
gs = settings["globalStyles"]
for type in ["staticText", "dynamicText", "rectangle", "image", "table"]:
if gs.get(type).get("style"):
gs[type]["style"]["whiteSpace"] = "normal"
if gs.get(type).get("labelStyle"):
gs[type]["labelStyle"]["whiteSpace"] = "normal"
if gs.get(type).get("headerStyle"):
gs[type]["headerStyle"]["whiteSpace"] = "normal"
frappe.db.set_value("Print Format", pf[0], "print_designer_settings", frappe.as_json(settings))
|
2302_79757062/print_designer
|
print_designer/patches/update_white_space_property.py
|
Python
|
agpl-3.0
| 833
|
import hashlib
import html
import json
import frappe
from frappe.monitor import add_data_to_monitor
from frappe.utils.error import log_error
from frappe.utils.jinja_globals import is_rtl
from frappe.utils.pdf import pdf_body_html as fw_pdf_body_html
def pdf_header_footer_html(soup, head, content, styles, html_id, css):
if soup.find(id="__print_designer"):
try:
return frappe.render_template(
"print_designer/page/print_designer/jinja/header_footer.html",
{
"head": head,
"content": content,
"styles": styles,
"html_id": html_id,
"css": css,
"headerFonts": soup.find(id="headerFontsLinkTag"),
"footerFonts": soup.find(id="footerFontsLinkTag"),
"lang": frappe.local.lang,
"layout_direction": "rtl" if is_rtl() else "ltr",
},
)
except Exception as e:
error = log_error(title=e, reference_doctype="Print Format")
frappe.throw(
msg=f"Something went wrong ( Error ) : If you don't know what just happened, and wish to file a ticket or issue on github, please copy the error from <b>Error Log {error.name}</b> or ask Administrator.",
exc=e,
)
else:
from frappe.utils.pdf import pdf_footer_html, pdf_header_html
if html_id == "header-html":
return pdf_header_html(
soup=soup, head=head, content=content, styles=styles, html_id=html_id, css=css
)
elif html_id == "footer-html":
return pdf_footer_html(
soup=soup, head=head, content=content, styles=styles, html_id=html_id, css=css
)
def pdf_body_html(print_format, jenv, args, template):
if print_format and print_format.print_designer and print_format.print_designer_body:
print_format_name = hashlib.md5(print_format.name.encode(), usedforsecurity=False).hexdigest()
add_data_to_monitor(print_designer=print_format_name, print_designer_action="download_pdf")
# DEPRECATED: remove this in few months added for backward compatibility incase user didn't update frappe framework.
if not frappe.get_hooks("get_print_format_template"):
template = get_print_format_template(jenv, print_format)
settings = json.loads(print_format.print_designer_settings)
args.update(
{
"headerElement": json.loads(print_format.print_designer_header),
"bodyElement": json.loads(print_format.print_designer_body),
"footerElement": json.loads(print_format.print_designer_footer),
"settings": settings,
}
)
if not is_older_schema(settings=settings, current_version="1.1.0"):
args.update({"pd_format": json.loads(print_format.print_designer_print_format)})
else:
args.update({"afterTableElement": json.loads(print_format.print_designer_after_table or "[]")})
# replace placeholder comment with user provided jinja code
template_source = template.replace(
"<!-- user_generated_jinja_code -->", args["settings"].get("userProvidedJinja", "")
)
try:
template = jenv.from_string(template_source)
return template.render(args, filters={"len": len})
except Exception as e:
error = log_error(title=e, reference_doctype="Print Format", reference_name=print_format.name)
if frappe.conf.developer_mode:
return f"<h1><b>Something went wrong while rendering the print format.</b> <hr/> If you don't know what just happened, and wish to file a ticket or issue on Github <hr /> Please copy the error from <code>Error Log {error.name}</code> or ask Administrator.<hr /><h3>Error rendering print format: {error.reference_name}</h3><h4>{error.method}</h4><pre>{html.escape(error.error)}</pre>"
else:
return f"<h1><b>Something went wrong while rendering the print format.</b> <hr/> If you don't know what just happened, and wish to file a ticket or issue on Github <hr /> Please copy the error from <code>Error Log {error.name}</code> or ask Administrator.</h1>"
return fw_pdf_body_html(template, args)
def is_older_schema(settings, current_version):
format_version = settings.get("schema_version", "1.0.0")
format_version = format_version.split(".")
current_version = current_version.split(".")
if int(format_version[0]) < int(current_version[0]):
return True
elif int(format_version[0]) == int(current_version[0]) and int(format_version[1]) < int(
current_version[1]
):
return True
elif (
int(format_version[0]) == int(current_version[0])
and int(format_version[1]) == int(current_version[1])
and int(format_version[2]) < int(current_version[2])
):
return True
else:
return False
def get_print_format_template(jenv, print_format):
# if print format is created using print designer, then use print designer template
if print_format and print_format.print_designer and print_format.print_designer_body:
settings = json.loads(print_format.print_designer_settings)
if is_older_schema(settings, "1.1.0"):
return jenv.loader.get_source(
jenv, "print_designer/page/print_designer/jinja/old_print_format.html"
)[0]
else:
return jenv.loader.get_source(
jenv, "print_designer/page/print_designer/jinja/print_format.html"
)[0]
|
2302_79757062/print_designer
|
print_designer/pdf.py
|
Python
|
agpl-3.0
| 4,981
|
// overrides the print util function that is used in the point of sale page.
// we should ideally change util function in framework to extend it. this is workaround until that.
const original_util = frappe.utils.print;
frappe.utils.print = (doctype, docname, print_format, letterhead, lang_code) => {
if (frappe.model.get_value("Print Format", print_format, "print_designer")) {
let w = window.open(
frappe.urllib.get_full_url(
"/app/print/" +
encodeURIComponent(doctype) +
"/" +
encodeURIComponent(docname) +
"?format=" +
encodeURIComponent(print_format) +
"&no_letterhead=0" +
"&trigger_print=1" +
(lang_code ? "&_lang=" + lang_code : "")
)
);
if (!w) {
frappe.msgprint(__("Please enable pop-ups"));
return;
}
} else {
original_util(doctype, docname, print_format, letterhead, lang_code);
}
};
|
2302_79757062/print_designer
|
print_designer/print_designer/client_scripts/point_of_sale.js
|
JavaScript
|
agpl-3.0
| 865
|
// TODO: revisit and properly implement this client script
frappe.pages["print"].on_page_load = function (wrapper) {
frappe.require(["pdfjs.bundle.css", "print_designer.bundle.css"]);
frappe.ui.make_app_page({
parent: wrapper,
});
let print_view = new frappe.ui.form.PrintView(wrapper);
$(wrapper).bind("show", () => {
const route = frappe.get_route();
const doctype = route[1];
const docname = route.slice(2).join("/");
if (!frappe.route_options || !frappe.route_options.frm) {
frappe.model.with_doc(doctype, docname, () => {
let frm = { doctype: doctype, docname: docname };
frm.doc = frappe.get_doc(doctype, docname);
frappe.model.with_doctype(doctype, () => {
frm.meta = frappe.get_meta(route[1]);
print_view.show(frm);
});
});
} else {
print_view.frm = frappe.route_options.frm.doctype
? frappe.route_options.frm
: frappe.route_options.frm.frm;
frappe.route_options.frm = null;
print_view.show(print_view.frm);
}
});
};
frappe.ui.form.PrintView = class PrintView extends frappe.ui.form.PrintView {
constructor(wrapper) {
super(wrapper);
this.pdfDoc = null;
this.pdfDocumentTask = null;
}
make() {
super.make();
this.print_wrapper = this.page.main.append(
`<div class="print-designer-wrapper">
<div id="preview-container" class="preview-container"
style="background-color: white; position: relative;">
${frappe.render_template("print_skeleton_loading")}
</div>
</div>`
);
this.header_prepend_container = $(
`<div class="print_selectors flex col align-items-center"></div>`
).prependTo(this.page.page_actions);
this.toolbar_print_format_selector = frappe.ui.form.make_control({
df: {
fieldtype: "Link",
fieldname: "print_format",
options: "Print Format",
placeholder: __("Print Format"),
get_query: () => {
return { filters: { doc_type: this.frm.doctype } };
},
change: () => {
if (
this.toolbar_print_format_selector.value ==
this.toolbar_print_format_selector.last_value
)
return;
this.print_format_item.set_value(this.toolbar_print_format_selector.value);
},
},
parent: this.header_prepend_container,
// only_input: true,
render_input: true,
});
this.toolbar_language_selector = frappe.ui.form.make_control({
df: {
fieldtype: "Link",
fieldname: "language",
placeholder: __("Language"),
options: "Language",
change: () => {
if (
this.toolbar_language_selector.value ==
this.toolbar_language_selector.last_value
)
return;
this.language_item.set_value(this.toolbar_language_selector.value);
},
},
parent: this.header_prepend_container,
only_input: true,
render_input: true,
});
this.toolbar_print_format_selector.$input_area.addClass("my-0 px-3 hidden-xs hidden-md");
this.toolbar_language_selector.$input_area.addClass("my-0 px-3 hidden-xs hidden-md");
this.sidebar_toggle = $(".page-head").find(".sidebar-toggle-btn");
$(document.body).on("toggleSidebar", () => {
if (this.sidebar.is(":hidden")) {
this.toolbar_print_format_selector.$wrapper.show();
this.toolbar_language_selector.$wrapper.show();
} else {
this.toolbar_print_format_selector.$wrapper.hide();
this.toolbar_language_selector.$wrapper.hide();
}
});
}
async designer_pdf(print_format) {
if (typeof pdfjsLib == "undefined") {
await frappe.require(
["assets/print_designer/js/pdf.min.js", "pdf.worker.bundle.js"],
() => {
pdfjsLib.GlobalWorkerOptions.workerSrc =
frappe.boot.assets_json["pdf.worker.bundle.js"];
}
);
}
let me = this;
let print_designer_settings = JSON.parse(print_format.print_designer_settings);
let page_settings = print_designer_settings.page;
let canvasContainer = document.getElementById("preview-container");
canvasContainer.style.minHeight = page_settings.height + "px";
canvasContainer.style.width = page_settings.width + "px";
canvasContainer.innerHTML = `${frappe.render_template("print_skeleton_loading")}`;
canvasContainer.style.backgroundColor = "white";
let params = new URLSearchParams({
doctype: this.frm.doc.doctype,
name: this.frm.doc.name,
format: this.selected_format(),
_lang: this.lang_code,
});
let url = `${
window.location.origin
}/api/method/frappe.utils.print_format.download_pdf?${params.toString()}`;
/**
* Asynchronously downloads PDF.
*/
try {
this.pdfDocumentTask && this.pdfDocumentTask.destroy();
this.pdfDocumentTask = await pdfjsLib.getDocument(url);
this.pdfDoc = await this.pdfDocumentTask.promise;
// Initial/first page rendering
canvasContainer.innerHTML = "";
canvasContainer.style.backgroundColor = "transparent";
for (let pageno = 1; pageno <= this.pdfDoc.numPages; pageno++) {
await renderPage(this.pdfDoc, pageno);
}
this.pdf_download_btn.prop("disabled", false);
if (frappe.route_options.trigger_print) {
this.printit();
}
this.print_btn.prop("disabled", false);
} catch (err) {
console.error(err);
frappe.msgprint({
title: __("Unable to generate PDF"),
message: `There was error while generating PDF. Please check the error log for more details.`,
indicator: "red",
primary_action: {
label: "Open Error Log",
action(values) {
frappe.set_route("List", "Error Log", {
doctype: "Error Log",
reference_doctype: "Print Format",
});
},
},
});
}
/**
* Get page info from document, resize canvas accordingly, and render page.
* @param num Page number.
*/
async function renderPage(pdfDoc, num) {
// Using promise to fetch the page
let page = await pdfDoc.getPage(num);
let canvasContainer = document.getElementById("preview-container");
let canvas = document.createElement("canvas");
let textLayer = document.createElement("div");
textLayer.classList.add("textLayer");
textLayer.style.position = "absolute";
textLayer.style.left = 0;
textLayer.style.top = 0;
textLayer.style.right = 0;
textLayer.style.bottom = 0;
textLayer.style.overflow = "hidden";
textLayer.style.opacity = 0.2;
textLayer.style.lineHeight = 1.0;
canvas.style.marginTop = "6px";
canvasContainer.appendChild(canvas);
canvasContainer.appendChild(textLayer);
let ctx = canvas.getContext("2d");
let viewport = page.getViewport({ scale: 1 });
let scale = (page_settings.width / viewport.width) * window.devicePixelRatio * 1.5;
document.documentElement.style.setProperty(
"--scale-factor",
page_settings.width / viewport.width
);
let scaledViewport = page.getViewport({ scale: scale });
canvas.style.height = page_settings.height + "px";
canvas.style.width = page_settings.width + "px";
canvas.height = scaledViewport.height;
canvas.width = scaledViewport.width;
// Render PDF page into canvas context
let renderContext = {
canvasContext: ctx,
viewport: scaledViewport,
intent: "print",
};
await page.render(renderContext);
let textContent = await page.getTextContent();
// Assign CSS to the textLayer element
textLayer.style.left = canvas.offsetLeft + "px";
textLayer.style.top = canvas.offsetTop + "px";
textLayer.style.height = canvas.offsetHeight + "px";
textLayer.style.width = canvas.offsetWidth + "px";
// Pass the data to the method for rendering of text over the pdf canvas.
pdfjsLib.renderTextLayer({
textContentSource: textContent,
container: textLayer,
viewport: scaledViewport,
textDivs: [],
});
}
}
printit() {
let me = this;
// Enable Network Printing
if (parseInt(this.print_settings.enable_print_server)) {
super.printit();
return;
}
if (this.get_print_format().print_designer) {
if (!this.pdfDoc) return;
this.pdfDoc.getData().then((arrBuff) => {
let file = new Blob([arrBuff], { type: "application/pdf" });
let fileUrl = URL.createObjectURL(file);
let iframe;
let iframeAvailable = document.getElementById("blob-print-iframe");
if (!iframeAvailable) {
iframe = document.createElement("iframe");
iframe.id = "blob-print-iframe";
iframe.style.display = "none";
iframe.src = fileUrl;
document.body.appendChild(iframe);
iframe.onload = () => {
setTimeout(() => {
iframe.focus();
iframe.contentWindow.print();
if (frappe.route_options.trigger_print) {
setTimeout(function () {
window.close();
}, 5000);
}
}, 1);
};
} else {
iframeAvailable.src = fileUrl;
}
// in case the Blob uses a lot of memory
setTimeout(() => URL.revokeObjectURL(fileUrl), 7000);
});
return;
}
super.printit();
}
show(frm) {
super.show(frm);
this.inner_msg = this.page.add_inner_message(`
<a style="line-height: 2.4" href="/app/print-designer?doctype=${this.frm.doctype}">
${__("Try the new Print Designer")}
</a>
`);
}
preview() {
let print_format = this.get_print_format();
if (print_format.print_designer && print_format.print_designer_body) {
this.inner_msg.hide();
this.print_wrapper.find(".print-preview-wrapper").hide();
this.print_wrapper.find(".preview-beta-wrapper").hide();
this.print_wrapper.find(".print-designer-wrapper").show();
this.designer_pdf(print_format);
this.full_page_btn.hide();
this.pdf_btn.hide();
this.pdf_download_btn.prop("disabled", true);
this.print_btn.prop("disabled", true);
this.pdf_download_btn.show();
this.letterhead_selector.hide();
this.sidebar_dynamic_section.hide();
this.sidebar.hide();
this.toolbar_print_format_selector.$wrapper.show();
this.toolbar_language_selector.$wrapper.show();
return;
}
this.pdfDocumentTask && this.pdfDocumentTask.destroy();
this.print_wrapper.find(".print-designer-wrapper").hide();
this.inner_msg.show();
this.full_page_btn.show();
this.pdf_btn.show();
this.pdf_download_btn.hide();
this.letterhead_selector.show();
this.sidebar_dynamic_section.show();
this.pdf_download_btn.prop("disabled", false);
this.print_btn.prop("disabled", false);
this.sidebar.show();
this.toolbar_print_format_selector.$wrapper.hide();
this.toolbar_language_selector.$wrapper.hide();
super.preview();
}
setup_toolbar() {
this.print_btn = this.page.set_primary_action(
__("Print"),
() => this.printit(),
"printer"
);
this.full_page_btn = this.page.add_button(
__("Full Page"),
() => this.render_page("/printview?"),
{
icon: "full-page",
}
);
this.pdf_btn = this.page.add_button(__("PDF"), () => this.render_pdf(), {
icon: "small-file",
});
this.refresh_btn = this.page.add_button(__("Refresh"), () => this.refresh_print_format(), {
icon: "refresh",
});
this.pdf_download_btn = this.page
.add_button(__("Download PDF"), () => this.download_pdf(), {
icon: "small-file",
})
.hide();
this.page.add_action_icon(
"file",
() => {
this.go_to_form_view();
},
"",
__("Form")
);
}
setup_sidebar() {
this.sidebar = this.page.sidebar.addClass("print-preview-sidebar");
this.print_format_item = this.add_sidebar_item({
fieldtype: "Link",
fieldname: "print_format",
options: "Print Format",
placeholder: __("Print Format"),
get_query: () => {
return { filters: { doc_type: this.frm.doctype } };
},
change: () => {
if (this.print_format_item.value == this.print_format_item.last_value) return;
this.toolbar_print_format_selector.set_value(this.print_format_item.value);
this.refresh_print_format();
},
});
this.print_format_selector = this.print_format_item.$input;
this.language_item = this.add_sidebar_item({
fieldtype: "Link",
fieldname: "language",
placeholder: __("Language"),
options: "Language",
change: () => {
if (this.language_item.value == this.language_item.last_value) return;
this.toolbar_language_selector.set_value(this.language_item.value);
this.set_user_lang();
this.preview();
},
});
this.language_selector = this.language_item.$input;
this.letterhead_selector = this.add_sidebar_item({
fieldtype: "Link",
fieldname: "letterhead",
options: "Letter Head",
placeholder: __("Letter Head"),
change: () => this.preview(),
}).$input;
this.sidebar_dynamic_section = $(`<div class="dynamic-settings"></div>`).appendTo(
this.sidebar
);
}
set_default_print_language() {
super.set_default_print_language();
this.toolbar_language_selector.$input.val(this.lang_code);
}
set_default_print_format() {
super.set_default_print_format();
if (
frappe.meta
.get_print_formats(this.frm.doctype)
.includes(this.toolbar_print_format_selector.$input.val())
)
return;
if (!this.frm.meta.default_print_format) {
let pd_print_format = "";
if (this.frm.doctype == "Sales Invoice") {
pd_print_format = "Sales Invoice PD Format v2";
} else if (this.frm.doctype == "Sales Order") {
pd_print_format = "Sales Order PD v2";
}
if (pd_print_format) {
this.print_format_selector.val(pd_print_format);
this.toolbar_print_format_selector.$input.val(pd_print_format);
}
return;
}
this.toolbar_print_format_selector.$input.empty();
this.toolbar_print_format_selector.$input.val(this.frm.meta.default_print_format);
}
download_pdf() {
this.pdfDoc.getData().then((arrBuff) => {
const downloadFile = (blob, fileName) => {
const link = document.createElement("a");
// create a blobURI pointing to our Blob
link.href = URL.createObjectURL(blob);
link.download = fileName;
// some browser needs the anchor to be in the doc
document.body.append(link);
link.click();
link.remove();
// in case the Blob uses a lot of memory
setTimeout(() => URL.revokeObjectURL(link.href), 7000);
};
downloadFile(
new Blob([arrBuff], { type: "application/pdf" }),
`${frappe.get_route().slice(2).join("/")}.pdf`
);
});
}
};
|
2302_79757062/print_designer
|
print_designer/print_designer/client_scripts/print.js
|
JavaScript
|
agpl-3.0
| 14,006
|
const set_template_app_options = (frm) => {
frappe.xcall("frappe.core.doctype.module_def.module_def.get_installed_apps").then((r) => {
frm.set_df_property("print_designer_template_app", "options", JSON.parse(r));
if (!frm.doc.print_designer_template_app) {
frm.set_value("print_designer_template_app", "print_designer");
}
});
};
frappe.ui.form.on("Print Format", {
refresh: function (frm) {
frm.trigger("render_buttons");
set_template_app_options(frm);
},
render_buttons: function (frm) {
frm.page.clear_inner_toolbar();
if (!frm.is_new()) {
if (!frm.doc.custom_format) {
frm.add_custom_button(__("Edit Format"), function () {
if (!frm.doc.doc_type) {
frappe.msgprint(__("Please select DocType first"));
return;
}
if (frm.doc.print_format_builder_beta) {
frappe.set_route("print-format-builder-beta", frm.doc.name);
} else if (frm.doc.print_designer) {
frappe.set_route("print-designer", frm.doc.name);
} else {
frappe.set_route("print-format-builder", frm.doc.name);
}
});
} else if (frm.doc.custom_format && !frm.doc.raw_printing) {
frm.set_df_property("html", "reqd", 1);
}
if (frappe.model.can_write("Customize Form")) {
frappe.model.with_doctype(frm.doc.doc_type, function () {
let current_format = frappe.get_meta(frm.doc.DocType)?.default_print_format;
if (current_format == frm.doc.name) {
return;
}
frm.add_custom_button(__("Set as Default"), function () {
frappe.call({
method: "frappe.printing.doctype.print_format.print_format.make_default",
args: {
name: frm.doc.name,
},
callback: function () {
frm.refresh();
},
});
});
});
}
}
},
});
|
2302_79757062/print_designer
|
print_designer/print_designer/client_scripts/print_format.js
|
JavaScript
|
agpl-3.0
| 1,767
|
import os
import shutil
import frappe
from frappe.modules.utils import scrub
from frappe.printing.doctype.print_format.print_format import PrintFormat
class PDPrintFormat(PrintFormat):
def export_doc(self):
if (
not self.standard == "Yes"
or not frappe.conf.developer_mode
or frappe.flags.in_patch
or frappe.flags.in_install
or frappe.flags.in_migrate
or frappe.flags.in_import
or frappe.flags.in_setup_wizard
):
return
if not self.print_designer:
return super().export_doc()
self.write_document_file()
def write_document_file(self):
doc = self
doc_export = doc.as_dict(no_nulls=True)
doc.run_method("before_export", doc_export)
# create folder
folder = self.create_folder(doc.doc_type, doc.name)
fname = scrub(doc.name)
# write the data file
path = os.path.join(folder, f"{fname}.json")
with open(path, "w+") as json_file:
json_file.write(frappe.as_json(doc_export))
print(f"Wrote document file for {doc.doctype} {doc.name} at {path}")
self.export_preview(folder=folder, fname=fname)
def create_folder(self, dt, dn):
app = scrub(frappe.get_doctype_app(dt))
dn = scrub(dn)
pd_folder = frappe.get_hooks(
"pd_standard_format_folder", app_name=self.print_designer_template_app
)
if len(pd_folder) == 0:
pd_folder = ["default_templates"]
folder = os.path.join(
frappe.get_app_path(self.print_designer_template_app), os.path.join(pd_folder[0], app)
)
frappe.create_folder(folder)
return folder
def export_preview(self, folder, fname):
if self.print_designer_preview_img:
try:
file = frappe.get_doc(
"File",
{
"file_url": self.print_designer_preview_img,
"attached_to_doctype": self.doctype,
"attached_to_name": self.name,
"attached_to_field": "print_designer_preview_img",
},
)
except frappe.DoesNotExistError:
file = None
if not file:
return
file_export = file.as_dict(no_nulls=True)
file.run_method("before_export", file_export)
org_path = file.get_full_path()
target_path = os.path.join(folder, org_path.split("/")[-1])
shutil.copy2(org_path, target_path)
print(f"Wrote preview file for {self.doctype} {self.name} at {target_path}")
# write the data file
path = os.path.join(folder, f"print_designer-{fname}-preview.json")
with open(path, "w+") as json_file:
json_file.write(frappe.as_json(file_export))
print(f"Wrote document file for {file.doctype} {file.name} at {path}")
|
2302_79757062/print_designer
|
print_designer/print_designer/overrides/print_format.py
|
Python
|
agpl-3.0
| 2,475
|
<!DOCTYPE html>
<html lang={{ lang }} dir={{ layout_direction }}>
<head>
<meta charset="utf-8">
<link rel="preconnect" href="https://fonts.gstatic.com" />
{% if html_id=="footer-html" %}
{# link tag does not work in footer in wkhtmltopdf,
so this is a workaround to include bootstrap and still have auto footer height working #}
<style>
{{ css }}
</style>
{% else %}
{% for tag in head -%}
{{ tag | string }}
{%- endfor %}
{% endif %}
<style>
body {
margin: 0 !important;
border: 0 !important;
box-sizing: border-box;
padding: 0mm !important;
}
/* Dont show explicit links for <a> tags */
@media print {
a[href]:after {
content: none;
}
}
</style>
<!-- from: http://wkhtmltopdf.org/usage/wkhtmltopdf.txt -->
<script>
function subst() {
var vars = {};
var x = window.location.search.substring(1).split('&');
for (var i in x) {
var z = x[i].split('=',2);
vars[z[0]] = unescape(z[1]);
}
var x = ['page','topage','time','date'];
for (var i in x) {
var y = document.getElementsByClassName("page_info_" + x[i]);
for (var j=0; j<y.length; ++j) {
y[j].textContent = vars[x[i]];
}
}
const headers = {
firstPage : document.getElementById("firstPageHeader"),
oddPage : document.getElementById("oddPageHeader"),
evenPage : document.getElementById("evenPageHeader"),
lastPage : document.getElementById("lastPageHeader"),
}
const footers = {
firstPage : document.getElementById("firstPageFooter"),
oddPage : document.getElementById("oddPageFooter"),
evenPage : document.getElementById("evenPageFooter"),
lastPage : document.getElementById("lastPageFooter"),
}
function displayHeaderFooter(elements, selectedElements) {
for (var key in elements) {
if (elements[key]) {
if (elements[key] === selectedElements) {
elements[key].style.display = "block";
} else {
elements[key].style.display = "none";
}
}
}
}
var page_no = parseInt(vars["page"]);
var total_page_no = parseInt(vars["topage"]);
if (page_no == 1) {
if (headers.firstPage) {
displayHeaderFooter(headers, headers.firstPage);
} else {
displayHeaderFooter(headers, headers.oddPage);
}
if (footers.firstPage) {
displayHeaderFooter(footers, footers.firstPage);
} else {
displayHeaderFooter(footers, footers.oddPage);
}
} else if (page_no == total_page_no) {
if (headers.lastPage) {
displayHeaderFooter(headers, headers.lastPage);
} else {
if (total_page_no % 2 == 0) {
displayHeaderFooter(headers, headers.evenPage);
} else {
displayHeaderFooter(headers, headers.oddPage);
}
}
if (footers.lastPage) {
displayHeaderFooter(footers, footers.lastPage);
} else {
if (total_page_no % 2 == 0) {
displayHeaderFooter(footers, footers.evenPage);
} else {
displayHeaderFooter(footers, footers.oddPage);
}
}
} else if (page_no % 2 == 0) {
displayHeaderFooter(headers, headers.evenPage);
displayHeaderFooter(footers, footers.evenPage);
} else {
displayHeaderFooter(headers, headers.oddPage);
displayHeaderFooter(footers, footers.oddPage);
}
}
</script>
{% for tag in styles -%}
{{ tag | string }}
{%- endfor %}
<link rel="preconnect" href="https://fonts.gstatic.com" />
{% if html_id=="header-html" %}
{% if headerFonts %}{{ headerFonts }}{%endif%}
{% else %}
{% if footerFonts %}{{ footerFonts }}{%endif%}
{% endif %}
</head>
<body onload="subst()">
{% for tag in content -%}
{{ tag | string }}
{%- endfor %}
</div>
</body>
</html>
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/header_footer.html
|
HTML
|
agpl-3.0
| 3,785
|
<div class="print-format-skeleton">
<div class="skeleton-header">
<div class="letter-head row skeleton-section">
<div class="col-xs-4">
<div class="skeleton-card dark large"></div>
</div>
</div>
<div class="print-heading skeleton-section">
<div class="row">
<div class="col-xs-5"><div class="skeleton-card dark large"></div></div>
</div>
<div class="row">
<div class="col-xs-3">
<small class="sub-heading">
<div class="skeleton-card light"></div>
</small>
</div>
</div>
</div>
</div>
<div class="skeleton-body">
<div class="row skeleton-section">
<div class="col-xs-6 column-break">
<div class="row">
<div class="col-xs-6">
<div class="skeleton-card dark"></div>
</div>
<div class="col-xs-6">
<div class="skeleton-card light"></div>
</div>
</div>
</div>
<div class="col-xs-6 column-break">
<div class="row">
<div class="col-xs-5">
<div class="skeleton-card light pull-right" style="width: 85%;"></div>
</div>
<div class="col-xs-7">
<div class="skeleton-card light pull-right" style="width: 75%;"></div>
</div>
</div>
</div>
</div>
<div class="skeleton-section">
<div class="skeleton-table">
<div class="skeleton-table-header">
<div class="skeleton-table-row">
<div class="skeleton-table-column" style="width: 3%;">
<div class="skeleton-card dark"></div>
</div>
<div class="skeleton-table-column" style="width: 17%;">
<div class="skeleton-card dark" style="width: 75%;"></div>
</div>
<div class="skeleton-table-column" style="width: 20%;">
<div class="skeleton-card dark" style="width: 75%;"></div>
</div>
<div class="skeleton-table-column" style="width: 28%;">
<div class="skeleton-card dark pull-right" style="width: 90%;"></div>
</div>
<div class="skeleton-table-column" style="width: 12%;">
<div class="skeleton-card dark pull-right" style="width: 100%;"></div>
</div>
<div class="skeleton-table-column" style="width: 20%;">
<div class="skeleton-card dark pull-right" style="width: 70%;"></div>
</div>
</div>
</div>
<div class="skeleton-table-body">
{% for (let i=0; i<4; i++) { %}
<div class="skeleton-table-row">
<div class="skeleton-table-column" style="width: 3%;">
<div class="skeleton-card light"></div>
</div>
<div class="skeleton-table-column" style="width: 17%;">
<div class="skeleton-card light" style="width: 75%;"></div>
</div>
<div class="skeleton-table-column" style="width: 20%;">
<div class="skeleton-card light" style="width: 100%;"></div>
</div>
<div class="skeleton-table-column" style="width: 28%;">
<div class="skeleton-card light pull-right" style="width: 50%;"></div>
</div>
<div class="skeleton-table-column" style="width: 12%;">
<div class="skeleton-card light pull-right" style="width: 80%;"></div>
</div>
<div class="skeleton-table-column" style="width: 20%;">
<div class="skeleton-card dark pull-right" style="width: 100%;"></div>
</div>
</div>
{% } %}
</div>
</div>
</div>
<div class="skeleton-section">
<div class="row">
<div class="col-xs-6"></div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-5">
<div class="skeleton-card light"></div>
</div>
<div class="col-xs-7">
<div class="skeleton-card dark pull-right" style="width: 80%;"></div>
</div>
</div>
<div class="row">
<div class="col-xs-5">
<div class="skeleton-card light" style="width: 80%;">
</div>
</div>
<div class="col-xs-7">
<div class="skeleton-card dark pull-right" style="width: 60%;">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-5">
<div class="skeleton-card light" style="width: 80%;"></div>
</div>
<div class="col-xs-7 text-right">
<div class="skeleton-card dark pull-right" style="width: 60%;">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="skeleton-section">
<div class="row">
<div class="col-xs-6"></div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-5">
<div class="skeleton-card light"></div>
</div>
<div class="col-xs-7">
<div class="skeleton-card dark pull-right" style="width: 80%;"></div>
</div>
</div>
<div class="row">
<div class="col-xs-5">
<div class="skeleton-card light" style="width: 90%;">
</div>
</div>
<div class="col-xs-7">
<div class="skeleton-card dark pull-right" style="width: 60%;">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="skeleton-footer">
<div class="skeleton-card dark large" style="width: 45%;"></div>
<div class="skeleton-card light" style="width: 60%;"></div>
<div class="skeleton-card light" style="width: 35%;"></div>
<div class="skeleton-card light" style="width: 35%;"></div>
</div>
</div>
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/loading.html
|
HTML
|
agpl-3.0
| 5,191
|
{% macro barcode(element, send_to_jinja) -%}
{%- set field = element.dynamicContent[0] -%}
{%- if field.is_static -%}
{% if field.parseJinja %}
{%- set value = render_user_text(field.value, doc, {}, send_to_jinja).get("message", "") -%}
{% else %}
{%- set value = _(field.value) -%}
{% endif %}
{%- elif field.doctype -%}
{%- set value = frappe.db.get_value(field.doctype, doc[field.parentField], field.fieldname) -%}
{%- else -%}
{%- set value = doc.get_formatted(field.fieldname) -%}
{%- endif -%}
<div
style="position: absolute; top:{{ element.startY }}px; left:{{ element.startX }}px;width:{{ element.width }}px;height:{{ element.height }}px;
{{convert_css(element.style)}}"
class="{{ element.classes | join(' ') }}"
>
<div
style="width:100%;height:100%; {{convert_css(element.style)}}"
class="barcode {{ element.classes | join(' ') }}"
>
{% if value %}{{get_barcode(element.barcodeFormat, value|string, {
"module_color": element.barcodeColor or "#000000",
"foreground": element.barcodeColor or "#ffffff",
"background": element.barcodeBackgroundColor or "#ffffff",
"quiet_zone": 1,
}).value}}{% endif %}
</div>
</div>
{%- endmacro %}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/macros/barcode.html
|
HTML
|
agpl-3.0
| 1,391
|
{% from 'print_designer/page/print_designer/jinja/macros/spantag.html' import span_tag with context %}
{% macro dynamictext(element, send_to_jinja, heightType) -%}
<div style="position:{%- if heightType != 'fixed' -%}relative{% else %}absolute{%- endif -%}; {%- if heightType == 'fixed' -%}top: {%- else -%}margin-top: {%- endif -%}{{ element.startY }}px; left:{{ element.startX }}px;{% if element.isFixedSize %}width:{{ element.width }}px; {%- if heightType == 'fixed' -%}height:{{ element.height }}px; {%- endif -%} {% else %} width:fit-content; height:fit-content; white-space:nowrap; max-width: {{ (settings.page.width - settings.page.marginLeft - settings.page.marginRight - element.startX) + 2 }}px;{%endif%}" class="
{{ element.classes | join(' ') }}">
<div style="{% if element.isFixedSize %}width:{{ element.width }}px; {%- if heightType == 'fixed' -%}height:{{ element.height }}px; {%- endif -%}{% else %}width:fit-content; height:fit-content; white-space:nowrap; max-width: {{ (settings.page.width - settings.page.marginLeft - settings.page.marginRight - element.startX) + 2 }}px;{%endif%} {{convert_css(element.style)}}"
class="dynamicText {{ element.classes | join(' ') }}">
{% for field in element.dynamicContent %}
<!-- third Arg is row which is not sent outside table -->
{{ span_tag(field, element, {}, send_to_jinja)}}
{% endfor %}
</div>
</div>
{%- endmacro %}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/macros/dynamictext.html
|
HTML
|
agpl-3.0
| 1,462
|
{% macro image(element) -%}
{%- if element.image.file_url -%}
{%- set value = element.image.file_url -%}
{%- elif element.image.fieldname -%}
{%- if element.image.parent == doc.doctype -%}
{%- set value = doc.get(element.image.fieldname) -%}
{%- else -%}
{%- set value = frappe.db.get_value(element.image.doctype, doc[element.image.parentField], element.image.fieldname) -%}
{%- endif -%}
{%- else -%}
{%- set value = "" -%}
{%- endif -%}
{%- if value -%}
<div
style="position: absolute; top:{{ element.startY }}px; left:{{ element.startX }}px;width:{{ element.width }}px;height:{{ element.height }}px;
{{convert_css(element.style)}}"
class="image {{ element.classes | join(' ') }}"
>
<div
style="width:100%; height:100%; background-image: url('{{frappe.get_url()}}{{value}}');"
class="image {{ element.classes | join(' ') }}"
></div>
</div>
{%- endif -%}
{%- endmacro %}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/macros/image.html
|
HTML
|
agpl-3.0
| 932
|
{% macro rectangle(element, render_element, send_to_jinja, heightType) -%}
{%- set heightType = element.get("heightType") -%}
{%- if settings.get("schema_version") == "1.1.0" or heightType == None -%}
{%- set heightType = "auto" if element.get("isDynamicHeight", False) else "fixed" -%}
{%- endif -%}
<div id="{{ element.id }}" style="position:{%- if heightType and heightType != 'fixed' -%}relative{% else %}absolute{%- endif -%}; {%- if heightType == 'fixed' -%}top: {%- else -%}margin-top: {%- endif -%}{{ element.startY }}px; left:{{ element.startX }}px; width:{{ element.width }}px; {%- if heightType != 'auto' -%} {%- if heightType == 'auto-min-height' -%}min-{%- endif -%}height:{{ element.height }}px; {%- endif -%} {{convert_css(element.style)}}"
class="rectangle {{ element.classes | join(' ') }}">
{% if element.childrens %}
{% for object in element.childrens %}
{{ render_element(object, send_to_jinja, heightType) }}
{% endfor %}
{% endif %}
</div>
{%- endmacro %}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/macros/rectangle.html
|
HTML
|
agpl-3.0
| 1,064
|
{% from 'print_designer/page/print_designer/jinja/macros/render_element.html' import render_element with context %}
{% macro relative_columns(element, send_to_jinja) -%}
{%- set heightType = element.get("heightType") -%}
{%- if settings.get("schema_version") == "1.1.0" -%}
{%- set heightType = "auto" if element.get("isDynamicHeight", False) else "fixed" -%}
{%- endif -%}
<div style="position:relative; top: 0px; {%- if element.rectangleContainer -%}margin-top:{{element.startY}}px; margin-left:{{element.startX}}px;{%- endif -%} width:{{ element.width }}px; {%- if heightType != 'auto' -%}{%- if heightType == 'auto-min-height' -%}min-{%- endif -%}height:{{ element.height }}px; {%- endif -%} {{convert_css(element.style)}}"
class="rectangle {{ element.classes | join(' ') }}">
{% if element.childrens %}
{% for object in element.childrens %}
{%- if object.layoutType == "row" -%}
{{ relative_containers(object, send_to_jinja) }}
{%- elif object.layoutType == "column" -%}
{{ relative_columns(object, send_to_jinja) }}
{%- else -%}
{{ render_element(object, send_to_jinja, heightType) }}
{%- endif -%}
{% endfor %}
{% endif %}
</div>
{%- endmacro %}
{% macro relative_containers(element, send_to_jinja) -%}
{%- set heightType = element.get("heightType") -%}
{%- if settings.get("schema_version") == "1.1.0" -%}
{%- set heightType = "auto" if element.get("isDynamicHeight", False) else "fixed" -%}
{%- endif -%}
<div style="position:relative; left:{{ element.startX }}px; {%- if heightType != 'auto' -%}{%- if heightType == 'auto-min-height' -%}min-{%- endif -%}height:{{ element.height }}px; {%- endif -%} {{convert_css(element.style)}}"
class="rectangle relative-row {{ element.classes | join(' ') }}">
{% if element.childrens %}
{% for object in element.childrens %}
{%- if object.layoutType == "column" -%}
{{ relative_columns(object, send_to_jinja) }}
{%- elif object.layoutType == "row" -%}
{{ relative_containers(object, send_to_jinja) }}
{%- else -%}
{{ render_element(object, send_to_jinja, heightType) }}
{%- endif -%}
{% endfor %}
{% endif %}
</div>
{%- endmacro %}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/macros/relative_containers.html
|
HTML
|
agpl-3.0
| 2,473
|
{% from 'print_designer/page/print_designer/jinja/macros/relative_containers.html' import relative_containers with context %}
{% macro render(elements, send_to_jinja) -%}
{% if element is iterable and (element is not string and element is not mapping) %}
{% for object in elements %}
{{ relative_containers(object, send_to_jinja) }}
{% endfor %}
{% endif %}
{%- endmacro %}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/macros/render.html
|
HTML
|
agpl-3.0
| 422
|
{% from 'print_designer/page/print_designer/jinja/macros/statictext.html' import statictext with context %}
{% from 'print_designer/page/print_designer/jinja/macros/dynamictext.html' import dynamictext with context %}
{% from 'print_designer/page/print_designer/jinja/macros/spantag.html' import span_tag with context %}
{% from 'print_designer/page/print_designer/jinja/macros/image.html' import image with context %}
{% from 'print_designer/page/print_designer/jinja/macros/barcode.html' import barcode with context %}
{% from 'print_designer/page/print_designer/jinja/macros/rectangle.html' import rectangle with context %}
{% from 'print_designer/page/print_designer/jinja/macros/table.html' import table with context %}
{% macro render_element(element, send_to_jinja, heightType = 'fixed') -%}
{% if element.type == "rectangle" %}
{{ rectangle(element, render_element, send_to_jinja, heightType) }}
{% elif element.type == "image" %}
{{image(element)}}
{% elif element.type == "table" %}
{{table(element, send_to_jinja, heightType)}}
{% elif element.type == "text" %}
{% if element.isDynamic %}
{{dynamictext(element, send_to_jinja, heightType)}}
{% else%}
{{statictext(element, send_to_jinja, heightType)}}
{% endif %}
{% elif element.type == "barcode" %}
{{barcode(element, send_to_jinja)}}
{% endif %}
{%- endmacro %}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/macros/render_element.html
|
HTML
|
agpl-3.0
| 1,431
|
{% macro getFontStyles(fonts) -%}{%for key, value in fonts.items()%}{{key ~ ':ital,wght@'}}{%for index, size in enumerate(value.weight)%}{%if index > 0%};{%endif%}0,{{size}}{%endfor%}{%for index, size in enumerate(value.italic)%}{%if index > 0 or value.weight|length != 0 %};{%endif%}1,{{size}}{%endfor%}{% if not loop.last %}{{'&display=swap&family='}}{%endif%}{%endfor%}{%- endmacro %}
{% macro render_google_fonts(settings) %}
<link rel="preconnect" href="https://fonts.gstatic.com" />
{% if settings.printHeaderFonts %}
<link
href="https://fonts.googleapis.com/css2?family={{getFontStyles(settings.printHeaderFonts)}}"
rel="stylesheet"
id="headerFontsLinkTag"
/>
{%endif%}
{% if settings.printBodyFonts %}
<link
href="https://fonts.googleapis.com/css2?family={{getFontStyles(settings.printBodyFonts)}}"
rel="stylesheet"
id="bodyFontsLinkTag"
/>
{%endif%}
{% if settings.printFooterFonts %}
<link
href="https://fonts.googleapis.com/css2?family={{getFontStyles(settings.printFooterFonts)}}"
rel="stylesheet"
id="footerFontsLinkTag"
/>
{%endif%}
{% endmacro %}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/macros/render_google_fonts.html
|
HTML
|
agpl-3.0
| 1,246
|
{% macro page_class(field) %}
{% if field.fieldname in ['page', 'topage', 'time', 'date'] %}
page_info_{{ field.fieldname }}
{% endif %}
{% endmacro %}
{%- macro spanvalue(field, element, row, send_to_jinja) -%}
{%- if field.is_static -%}
{% if field.parseJinja %}
{{ render_user_text(field.value, doc, row, send_to_jinja).get("message", "") }}
{% else %}
{{ _(field.value) }}
{% endif %}
{%- elif field.doctype -%}
{%- set value = _(frappe.db.get_value(field.doctype, doc[field.parentField], field.fieldname)) -%}
{{ frappe.format(value, {'fieldtype': field.fieldtype, 'options': field.options}) }}
{%- elif row -%}
{%- if field.fieldtype == "Image" and row.get(field['options']) -%}
<img class="print-item-image" src="{{ row.get(field['options']) }}" alt="">
{%- elif field.fieldtype == "Signature" -%}
{%- if doc.get_formatted(field.fieldname) != "/assets/frappe/images/signature-placeholder.png" -%}
<img class="print-item-image" src="{{doc.get_formatted(field.fieldname)}}" alt="">
{%- endif -%}
{%- else -%}
{{row.get_formatted(field.fieldname)}}
{%- endif -%}
{%- else -%}
{%- if field.fieldtype == "Image" and doc.get(field['options']) -%}
<img class="print-item-image" src="{{ doc.get(field['options']) }}" alt="">
{%- elif field.fieldtype == "Signature" -%}
{%- if doc.get_formatted(field.fieldname) != "/assets/frappe/images/signature-placeholder.png" -%}
<img class="print-item-image" src="{{doc.get_formatted(field.fieldname)}}" alt="">
{%- endif -%}
{%- else -%}
{{doc.get_formatted(field.fieldname)}}
{%- endif -%}
{%- endif -%}
{%- endmacro -%}
<!-- third Arg is row which is not sent outside table -->
{% macro span_tag(field, element, row = {}, send_to_jinja = {}) -%}
{% set span_value = spanvalue(field, element, row, send_to_jinja) %}
{%- if span_value or field.fieldname in ['page', 'topage', 'time', 'date'] -%}
<span class="{% if not field.is_static and field.is_labelled %}baseSpanTag{% endif %}">
{% if not field.is_static and field.is_labelled%}
<span class="{% if row %}printTable{% else %}dynamicText{% endif %} label-text labelSpanTag" style="user-select:auto; {%if element.labelStyle %}{{convert_css(element.labelStyle)}}{%endif%}{%if field.labelStyle %}{{convert_css(field.labelStyle)}}{%endif%} white-space:nowrap; ">
{{ _(field.label) }}
</span>
{% endif %}
<span class="dynamic-span {% if not field.is_static and field.is_labelled %}valueSpanTag{%endif%} {{page_class(field)}}"
style="{%- if element.style.get('color') -%}{{ convert_css({'color': element.style.get('color')})}}{%- endif -%} {{convert_css(field.style)}} user-select:auto;">
{{ span_value }}
</span>
{% if field.suffix %}
<span class="dynamic-span"
style="{%- if element.style.get('color') -%}{{ convert_css({'color': element.style.get('color')})}}{%- endif -%} {{convert_css(field.style)}} user-select:auto;">
{{ _(field.suffix) }}
</span>
{% endif %}
{% if field.nextLine %}
<br/>
{% endif %}
</span>
{% endif %}
{%- endmacro %}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/macros/spantag.html
|
HTML
|
agpl-3.0
| 3,524
|
<!-- third Arg in render_user_text is row which is not sent outside table -->
{% macro statictext(element, send_to_jinja, heightType) -%}
<div style="position:{%- if heightType != 'fixed' -%}relative{% else %}absolute{%- endif -%}; {%- if heightType == 'fixed' -%}top: {%- else -%}margin-top: {%- endif -%}{{ element.startY }}px; left:{{ element.startX }}px;{% if element.isFixedSize %}width:{{ element.width }}px;{%- if heightType == 'fixed' -%}height:{{ element.height }}px; {%- endif -%}{% else %}width:fit-content; height:fit-content; max-width: {{ (settings.page.width - settings.page.marginLeft - settings.page.marginRight - element.startX) + 2 }}px; white-space:nowrap; {%endif%}" class="
{{ element.classes | join(' ') }}">
<p style="{% if element.isFixedSize %}width:{{ element.width }}px; {%- if heightType == 'fixed' -%}height:{{ element.height }}px; {%- endif -%}{% else %}width:fit-content; height:fit-content; max-width: {{ (settings.page.width - settings.page.marginLeft - settings.page.marginRight - element.startX ) + 2 }}px; white-space:nowrap;{%endif%} {{convert_css(element.style)}}"
class="staticText {{ element.classes | join(' ') }}">
{% if element.parseJinja %}
{{ render_user_text(element.content, doc, {}, send_to_jinja).get("message", "") }}
{% else %}
{{_(element.content)}}
{% endif %}
</p>
</div>
{%- endmacro %}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/macros/statictext.html
|
HTML
|
agpl-3.0
| 1,410
|
{% macro render_styles(settings) %}
<style>
.print-format {
box-sizing: border-box;
padding: 0in;
max-width: {{convert_uom(number=settings.page.width, to_uom="mm")}} !important;
dpi: {{settings.PDFPrintDPI or 96}}mm;
page-width: {{convert_uom(number=settings.page.width, to_uom="mm")}};
page-height: {{convert_uom(number=settings.page.height, to_uom="mm")}};
margin-top:{{convert_uom(number=settings.page.headerHeightWithMargin or settings.page.marginTop, to_uom='mm')}};
margin-bottom:{{convert_uom(number=settings.page.footerHeightWithMargin or settings.page.marginBottom, to_uom='mm')}};
margin-left:{{convert_uom(number=settings.page.marginLeft, to_uom='mm')}};
margin-right:{{convert_uom(number=settings.page.marginRight, to_uom='mm')}};
}
@media screen {
#__print_designer {
position: relative;
margin-top:{{convert_uom(number=settings.page.marginTop, to_uom='px')}};
margin-bottom:{{convert_uom(number=settings.page.marginBottom, to_uom='px')}};
margin-left:{{convert_uom(number=settings.page.marginLeft, to_uom='px')}};
margin-right:{{convert_uom(number=settings.page.marginRight, to_uom='px')}};
}
.print-format {
margin: auto !important;
}
}
/* set margin to 0 for print (Ctrl + p) on client browsers
and remove margin container that was added for screen ( viewing ) */
@media print {
.print-format {
margin: 0 !important;
}
.printview-header-margin {
display: none;
}
}
.print-designer-container {
position: absolute;
}
.table {
margin: 0;
}
.print-format p {
margin: 0 !important;
}
tr:first-child th {
border-top-style: solid !important;
}
tr th:first-child {
border-left-style: solid !important;
}
tr th:last-child {
border-right-style: solid !important;
}
tr:last-child td {
border-bottom-style: solid !important;
}
tr td:first-child {
border-left-style: solid !important;
}
tr td:last-child {
border-right-style: solid !important;
}
.flexDynamicText .baseSpanTag {
display: block;
}
.flexDynamicText .baseSpanTag .labelSpanTag {
display: inline-block;
vertical-align: top;
}
.flexDynamicText .baseSpanTag .valueSpanTag {
display: inline-block;
vertical-align: top;
}
.flexDirectionColumn .baseSpanTag {
display: block;
}
.flexDirectionColumn .baseSpanTag .labelSpanTag {
display: block;
}
.flexDirectionColumn .baseSpanTag .valueSpanTag {
display: block;
}
/* https://github.com/wkhtmltopdf/wkhtmltopdf/issues/1522 */
.relative-row {
display: -webkit-box;
display: -webkit-flex;
display: flex;
border-width: 0 !important;
flex: auto;
}
.relative-column {
border-width: 0px !important;
border-color: transparent !important;
flex-direction: column;
flex: auto;
}
* {
-webkit-box-sizing: border-box;
}
</style>
{% endmacro %}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/macros/styles.html
|
HTML
|
agpl-3.0
| 3,260
|
{% macro table(element, send_to_jinja, heightType) -%}
{%- set heightType = element.get("heightType") -%}
{%- if settings.get("schema_version") == "1.1.0" -%}
{%- set heightType = "auto" if element.get("isDynamicHeight", False) else "fixed" -%}
{%- endif -%}
<table style="position:{%- if heightType != 'fixed' -%}relative{% else %}absolute{%- endif -%}; {%- if heightType == 'fixed' -%}top: {%- else -%}margin-top: {%- endif -%}{{ element.startY }}px; left:{{ element.startX }}px; width:{{ element.width }}px;{%- if heightType != 'fixed' and heightType != 'auto' -%}{%- if heightType == 'auto-min-height' -%}min-{%- endif -%}height:{{ element.height }}px;{%- endif -%} max-width:{{ element.width }}px;" class="table-container printTable {{ element.classes | join(' ') }}">
<thead>
{% if element.columns %}
<tr>
{% for column in element.columns%}
<th style="{% if column.width %}width: {{column.width}}%; max-width: {{column.width}}%;{%endif%} {{convert_css(element.headerStyle)}}border-top-style: solid !important;border-bottom-style: solid !important;{%if loop.first%}border-left-style: solid !important;{%elif loop.last%}border-right-style: solid !important;{%endif%}{%- if column.applyStyleToHeader and column.style -%}{{convert_css(column.style)}}{%- endif -%}">
{{ _(column.label) }}
</th>
{% endfor %}
</tr>
{% endif %}
</thead>
<tbody>
{% if element.columns %}
{% for row in doc.get(element.table.fieldname)%}
<tr>
{% set isLastRow = loop.last %}
{% for column in element.columns%}
<td style="{{convert_css(element.style)}}{%if row.idx % 2 == 0 %}{{convert_css(element.altStyle)}}{%endif%}{%if isLastRow%}border-bottom-style: solid !important;{%endif%}{%if loop.first%}border-left-style: solid !important;{%elif loop.last%}border-right-style: solid !important;{%endif%}{%- if column.style -%}{{convert_css(column.style)}}{%- endif -%}">
{% if column is mapping %}
{% for field in column.dynamicContent%}
{{ span_tag(field, element, row, send_to_jinja) }}
{% endfor %}
{% endif %}
</td>
{% endfor %}
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
{%- endmacro %}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/macros/table.html
|
HTML
|
agpl-3.0
| 2,555
|
{% macro render_statictext(element, send_to_jinja) -%}
<div style="position: absolute; top:{% if 'printY' in element %}{{ element.printY }}{% else %}{{ element.startY }}{% endif %}px; left:{% if 'printX' in element %}{{ element.printX }}{% else %}{{ element.startX }}{% endif %}px;{% if element.isFixedSize %}width:{{ element.width }}px;height:{{ element.height }}px;{% else %}width:fit-content; height:fit-content; max-width: {{ (settings.page.width - settings.page.marginLeft - settings.page.marginRight - element.startX) + 2 }}px; white-space:nowrap; {%endif%}" class="
{{ element.classes | join(' ') }}">
<p style="{% if element.isFixedSize %}width:{{ element.width }}px;height:{{ element.height }}px;{% else %}width:fit-content; height:fit-content; max-width: {{ (settings.page.width - settings.page.marginLeft - settings.page.marginRight - element.startX ) + 2 }}px; white-space:nowrap;{%endif%} {{convert_css(element.style)}}"
class="staticText {{ element.classes | join(' ') }}">
{% if element.parseJinja %}
<!-- third Arg is row which is not sent outside table -->
{{ render_user_text(element.content, doc, {}, send_to_jinja).get("message", "") }}
{% else %}
{{_(element.content)}}
{% endif %}
</p>
</div>
{%- endmacro %}
{% macro page_class(field) %}
{% if field.fieldname in ['page', 'topage', 'time', 'date'] %}
page_info_{{ field.fieldname }}
{% endif %}
{% endmacro %}
{% macro render_dynamictext(element, send_to_jinja) -%}
<div style="position: absolute; top:{% if 'printY' in element %}{{ element.printY }}{% else %}{{ element.startY }}{% endif %}px; left:{% if 'printX' in element %}{{ element.printX }}{% else %}{{ element.startX }}{% endif %}px;{% if element.isFixedSize %}width:{{ element.width }}px;height:{{ element.height }}px;{% else %}width:fit-content; height:fit-content; white-space:nowrap; max-width: {{ (settings.page.width - settings.page.marginLeft - settings.page.marginRight - element.startX) + 2 }}px;{%endif%}" class="
{{ element.classes | join(' ') }}">
<div style="{% if element.isFixedSize %}width:{{ element.width }}px;height:{{ element.height }}px;{% else %}width:fit-content; height:fit-content; white-space:nowrap; max-width: {{ (settings.page.width - settings.page.marginLeft - settings.page.marginRight - element.startX) + 2 }}px;{%endif%} {{convert_css(element.style)}}"
class="dynamicText {{ element.classes | join(' ') }}">
{% for field in element.dynamicContent %}
<!-- third Arg is row which is not sent outside table -->
{{ render_spantag(field, element, {}, send_to_jinja)}}
{% endfor %}
</div>
</div>
{%- endmacro %}
{% macro render_rectangle(element, send_to_jinja) -%}
<div id="{{ element.id }}" style="position: absolute; top:{% if 'printY' in element %}{{ element.printY }}{% else %}{{ element.startY }}{% endif %}px; left:{% if 'printX' in element %}{{ element.printX }}{% else %}{{ element.startX }}{% endif %}px; width:{{ element.width }}px;height:{{ element.height }}px; {{convert_css(element.style)}}"
class="rectangle {{ element.classes | join(' ') }}">
{% if element.childrens %}
{% for object in element.childrens %}
{{ render_element(object, send_to_jinja)}}
{% endfor %}
{% endif %}
</div>
{%- endmacro %}
{% macro render_image(element) -%}
{%- if element.image.file_url -%}
{%- set value = element.image.file_url -%}
{%- elif element.image.fieldname -%}
{%- if element.image.parent == doc.doctype -%}
{%- set value = doc.get(element.image.fieldname) -%}
{%- else -%}
{%- set value = frappe.db.get_value(element.image.doctype, doc[element.image.parentField], element.image.fieldname) -%}
{%- endif -%}
{%- else -%}
{%- set value = "" -%}
{%- endif -%}
{%- if value -%}
<div
style="position: absolute; top:{% if 'printY' in element %}{{ element.printY }}{% else %}{{ element.startY }}{% endif %}px; left:{% if 'printX' in element %}{{ element.printX }}{% else %}{{ element.startX }}{% endif %}px;width:{{ element.width }}px;height:{{ element.height }}px;
{{convert_css(element.style)}}"
class="image {{ element.classes | join(' ') }}"
>
<div
style="width:100%;height:100%;
background-image: url('{{frappe.get_url()}}{{value}}');
"
class="image {{ element.classes | join(' ') }}"
></div>
</div>
{%- endif -%}
{%- endmacro %}
{% macro render_barcode(element, send_to_jinja) -%}
{%- set field = element.dynamicContent[0] -%}
{%- if field.is_static -%}
{% if field.parseJinja %}
{%- set value = render_user_text(field.value, doc, {}, send_to_jinja).get("message", "") -%}
{% else %}
{%- set value = _(field.value) -%}
{% endif %}
{%- elif field.doctype -%}
{%- set value = frappe.db.get_value(field.doctype, doc[field.parentField], field.fieldname) -%}
{%- else -%}
{%- set value = doc.get_formatted(field.fieldname) -%}
{%- endif -%}
<div
style="position: absolute; top:{% if 'printY' in element %}{{ element.printY }}{% else %}{{ element.startY }}{% endif %}px; left:{% if 'printX' in element %}{{ element.printX }}{% else %}{{ element.startX }}{% endif %}px;width:{{ element.width }}px;height:{{ element.height }}px;
{{convert_css(element.style)}}"
class="{{ element.classes | join(' ') }}"
>
<div
style="width:100%;height:100%; {{convert_css(element.style)}}"
class="barcode {{ element.classes | join(' ') }}"
>{% if value %}{{get_barcode(element.barcodeFormat, value|string, {
"module_color": element.barcodeColor or "#000000",
"foreground": element.barcodeColor or "#ffffff",
"background": element.barcodeBackgroundColor or "#ffffff",
"quiet_zone": 1,
}).value}}{% endif %}</div>
</div>
{%- endmacro %}
{% macro render_table(element, send_to_jinja) -%}
<div style="position: absolute; top:{% if 'printY' in element %}{{ element.printY }}{% else %}{{ element.startY }}{% endif %}px; left:{% if 'printX' in element %}{{ element.printX }}{% else %}{{ element.startX }}{% endif %}px;width:{{ element.width }}px;height:{{ element.height }}px;" class="
table-container {{ element.classes | join(' ') }}">
<table class="printTable" style="position: relative; width:100%; max-width:{{ element.width }}px;">
<thead>
{% if element.columns %}
<tr>
{% for column in element.columns%}
<th style="{% if column.width %}width: {{column.width}}%; max-width: {{column.width}}%;{%endif%} {{convert_css(element.headerStyle)}}border-top-style: solid !important;border-bottom-style: solid !important;{%if loop.first%}border-left-style: solid !important;{%elif loop.last%}border-right-style: solid !important;{%endif%}{%- if column.applyStyleToHeader and column.style -%}{{convert_css(column.style)}}{%- endif -%}">
{{ _(column.label) }}
</th>
{% endfor %}
</tr>
{% endif %}
</thead>
<tbody>
{% if element.columns %}
{% for row in doc.get(element.table.fieldname)%}
<tr>
{% set isLastRow = loop.last %}
{% for column in element.columns%}
<td style="{{convert_css(element.style)}}{%if row.idx % 2 == 0 %}{{convert_css(element.altStyle)}}{%endif%}{%if isLastRow%}border-bottom-style: solid !important;{%endif%}{%if loop.first%}border-left-style: solid !important;{%elif loop.last%}border-right-style: solid !important;{%endif%}{%- if column.style -%}{{convert_css(column.style)}}{%- endif -%}">
{% if column is mapping %}
{% for field in column.dynamicContent%}
{{ render_spantag(field, element, row, send_to_jinja) }}
{% endfor %}
{% endif %}
</td>
{% endfor %}
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
{% if element.get("isPrimaryTable", false) or settings.get("schema_version") == "1.0.0" %}
{% set renderAfterTableElement = render_element(afterTableElement, send_to_jinja) %}
{% if renderAfterTableElement %}<div style="position: relative; top:0px; left: 0px;">{{ renderAfterTableElement }}</div>{% endif %}
{% endif %}
</div>
{%- endmacro %}
{%- macro render_spanvalue(field, element, row, send_to_jinja) -%}
{%- if field.is_static -%}
{% if field.parseJinja %}
{{ render_user_text(field.value, doc, row, send_to_jinja).get("message", "") }}
{% else %}
{{ _(field.value) }}
{% endif %}
{%- elif field.doctype -%}
{%- set value = _(frappe.db.get_value(field.doctype, doc[field.parentField], field.fieldname)) -%}
{{ frappe.format(value, {'fieldtype': field.fieldtype, 'options': field.options}) }}
{%- elif row -%}
{{row.get_formatted(field.fieldname)}}
{%- else -%}
{{doc.get_formatted(field.fieldname)}}
{%- endif -%}{%- endmacro -%}
<!-- third Arg is row which is not sent outside table -->
{% macro render_spantag(field, element, row = {}, send_to_jinja = {}) -%}
{% set span_value = render_spanvalue(field, element, row, send_to_jinja) %}
{%- if span_value or field.fieldname in ['page', 'topage', 'time', 'date'] -%}
<span class="{% if not field.is_static and field.is_labelled %}baseSpanTag{% endif %}">
{% if not field.is_static and field.is_labelled %}
<span class="{% if row %}printTable{% else %}dynamicText{% endif %} label-text labelSpanTag" style="user-select:auto; {%if element.labelStyle %}{{convert_css(element.labelStyle)}}{%endif%}{%if field.labelStyle %}{{convert_css(field.labelStyle)}}{%endif%} white-space:nowrap; ">
{{ _(field.label) }}
</span>
{% endif %}
<span class="dynamic-span {% if not field.is_static and field.is_labelled %}valueSpanTag{%endif%} {{page_class(field)}} }}"
style="{%- if element.style.get('color') -%}{{ convert_css({'color': element.style.get('color')})}}{%- endif -%} {{convert_css(field.style)}} user-select:auto;">
{{ span_value }}
</span>
{% if field.suffix %}
<span class="dynamic-span"
style="{%- if element.style.get('color') -%}{{ convert_css({'color': element.style.get('color')})}}{%- endif -%} {{convert_css(field.style)}} user-select:auto;">
{{ _(field.suffix) }}
</span>
{% endif %}
{% if field.nextLine %}
<br/>
{% endif %}
</span>
{% endif %}
{%- endmacro %}
{% macro render_element(element, send_to_jinja) -%}
{% if element is iterable and (element is not string and element is not mapping) %}
{% for object in element %}
{{ render_element(object, send_to_jinja)}}
{% endfor %}
{% elif element.type == "rectangle" %}
{{ render_rectangle(element, send_to_jinja) }}
{% elif element.type == "image" %}
{{render_image(element)}}
{% elif element.type == "table" %}
{{render_table(element, send_to_jinja)}}
{% elif element.type == "text" %}
{% if element.isDynamic %}
{{render_dynamictext(element, send_to_jinja)}}
{% else%}
{{render_statictext(element, send_to_jinja)}}
{% endif %}
{% elif element.type == "barcode" %}
{{render_barcode(element, send_to_jinja)}}
{% endif %}
{%- endmacro %}
{% macro getFontStyles(fonts) -%}{%for key, value in fonts.items()%}{{key ~ ':ital,wght@'}}{%for index, size in enumerate(value.weight)%}{%if index > 0%};{%endif%}0,{{size}}{%endfor%}{%for index, size in enumerate(value.italic)%}{%if index > 0%};{%endif%}1,{{size}}{%endfor%}{% if not loop.last %}{{'&display=swap&family='}}{%endif%}{%endfor%}{%- endmacro %}
<!-- Don't remove this. user_generated_jinja_code tag is used as placeholder which we replace with user provided jinja template -->
<!-- user_generated_jinja_code -->
<!-- end of user generated code -->
{% set renderHeader = render_element(headerElement[0].childrens, send_to_jinja) %}
{% set renderBody = render_element(bodyElement[0].childrens, send_to_jinja) %}
{% set renderFooter = render_element(footerElement[0].childrens, send_to_jinja) %}
<link rel="preconnect" href="https://fonts.gstatic.com" />
{% if settings.printHeaderFonts %}
{% set printHeaderFonts = getFontStyles(settings.printHeaderFonts) %}
<link
href="https://fonts.googleapis.com/css2?family={{printHeaderFonts}}"
rel="stylesheet"
id="headerFontsLinkTag"
/>
{%endif%}
{% if settings.printFooterFonts %}
{% set printFooterFonts = getFontStyles(settings.printFooterFonts) %}
<link
href="https://fonts.googleapis.com/css2?family={{printFooterFonts}}"
rel="stylesheet"
id="footerFontsLinkTag"
/>
{%endif%}
{% if settings.printBodyFonts %}
{% set printBodyFonts = getFontStyles(settings.printBodyFonts) %}
<link
href="https://fonts.googleapis.com/css2?family={{printBodyFonts}}"
rel="stylesheet"
/>
{%endif%}
<div id="__print_designer">
<div id="header-html">
<div style="position: relative; top:0px; left: 0px; width: 100%; height:{{ settings.page.headerHeightWithMargin }}px;">{% if headerElement %}{{ renderHeader }}{%endif%}</div>
</div>
{% if bodyElement %}{{ renderBody }}{%endif%}
<div id="footer-html">
<div style="width: 100%; position: relative; top:0px; left: 0px; height:{{ settings.page.footerHeightWithMargin }}px; ">{% if footerElement %}{{ renderFooter }}{%endif%}</div>
</div>
</div>
<style>
.print-format {
box-sizing: border-box;
padding: 0in;
dpi: {{settings.PDFPrintDPI or 96}}mm;
page-width: {{convert_uom(number=settings.page.width, to_uom="mm")}};
page-height:{{convert_uom(number=settings.page.height, to_uom="mm")}};
margin-top:{{convert_uom(number=settings.page.headerHeightWithMargin or settings.page.marginTop, to_uom='mm')}};
margin-bottom:{{convert_uom(number=settings.page.footerHeightWithMargin or settings.page.marginBottom, to_uom='mm')}};
margin-left:{{convert_uom(number=settings.page.marginLeft, to_uom='mm')}};
margin-right:{{convert_uom(number=settings.page.marginRight, to_uom='mm')}};
}
.print-designer-container {
position: absolute;
}
.print-format p {
margin: 0 !important;
}
tr:first-child th {
border-top-style: solid !important;
}
tr th:first-child {
border-left-style: solid !important;
}
tr th:last-child {
border-right-style: solid !important;
}
tr:last-child td {
border-bottom-style: solid !important;
}
tr td:first-child {
border-left-style: solid !important;
}
tr td:last-child {
border-right-style: solid !important;
}
.flexDynamicText .baseSpanTag {
display: block;
}
.flexDynamicText .baseSpanTag .labelSpanTag {
display: inline-block;
vertical-align: top;
}
.flexDynamicText .baseSpanTag .valueSpanTag {
display: inline-block;
vertical-align: top;
}
.flexDirectionColumn .baseSpanTag {
display: block;
}
.flexDirectionColumn .baseSpanTag .labelSpanTag {
display: block;
}
.flexDirectionColumn .baseSpanTag .valueSpanTag {
display: block;
}
</style>
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/old_print_format.html
|
HTML
|
agpl-3.0
| 15,302
|
{% from 'print_designer/page/print_designer/jinja/macros/render.html' import render with context %}
{% from 'print_designer/page/print_designer/jinja/macros/render_google_fonts.html' import render_google_fonts with context %}
{% from 'print_designer/page/print_designer/jinja/macros/styles.html' import render_styles with context %}
{{ render_google_fonts(settings) }}
<!-- Don't remove this. user_generated_jinja_code tag is used as placeholder which we replace with user provided jinja template -->
<!-- user_generated_jinja_code -->
<!-- end of user generated code -->
<div id="__print_designer">
<div id="header-html">
<div style="position: relative; top:0px; left: 0px; width: 100%; height:{{ settings.page.headerHeightWithMargin }}px; overflow: hidden;" id="header-render-container">
<div class="visible-pdf" style="height: {{ settings.page.marginTop }}px;"></div>
<div class="hidden-pdf printview-header-margin" style="height: {{ settings.page.marginTop }}px;"></div>
<div class="hidden-pdf">{% if pd_format.header.firstPage %}{{ render(pd_format.header.firstPage, send_to_jinja) }}{%endif%}</div>
<div id="firstPageHeader" style="display: none;">{% if pd_format.header.firstPage %}{{ render(pd_format.header.firstPage, send_to_jinja) }}{%endif%}</div>
<div id="oddPageHeader" style="display: none;">{% if pd_format.header.oddPage %}{{ render(pd_format.header.oddPage, send_to_jinja) }}{%endif%}</div>
<div id="evenPageHeader" style="display: none;">{% if pd_format.header.evenPage %}{{ render(pd_format.header.evenPage, send_to_jinja) }}{%endif%}</div>
<div id="lastPageHeader" style="display: none;">{% if pd_format.header.lastPage %}{{ render(pd_format.header.lastPage, send_to_jinja) }}{%endif%}</div>
</div>
</div>
{%- for body in pd_format.body -%}
{{ render(body.childrens, send_to_jinja) }}
{%- endfor -%}
<div id="footer-html">
<div style="width: 100%; position: relative; top:0px; left: 0px; height:{{ settings.page.footerHeightWithMargin }}px;">
<div class="hidden-pdf">{% if pd_format.footer.firstPage %}{{ render(pd_format.footer.firstPage, send_to_jinja) }}{%endif%}</div>
<div id="firstPageFooter" style="display: none;">{% if pd_format.footer.firstPage %}{{ render(pd_format.footer.firstPage, send_to_jinja) }}{%endif%}</div>
<div id="oddPageFooter" style="display: none;">{% if pd_format.footer.oddPage %}{{ render(pd_format.footer.oddPage, send_to_jinja) }}{%endif%}</div>
<div id="evenPageFooter" style="display: none;">{% if pd_format.footer.evenPage %}{{ render(pd_format.footer.evenPage, send_to_jinja) }}{%endif%}</div>
<div id="lastPageFooter" style="display: none;">{% if pd_format.footer.lastPage %}{{ render(pd_format.footer.lastPage, send_to_jinja) }}{%endif%}</div>
</div>
</div>
</div>
{{ render_styles(settings) }}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/jinja/print_format.html
|
HTML
|
agpl-3.0
| 2,965
|
frappe.pages["print-designer"].on_page_load = function (wrapper) {
// hot reload in development
if (frappe.boot.developer_mode) {
frappe.hot_update = frappe.hot_update || [];
frappe.hot_update.push(() => load_print_designer(wrapper));
}
};
frappe.pages["print-designer"].on_page_show = function (wrapper) {
load_print_designer(wrapper);
};
const printDesignerDialog = () => {
let d = new frappe.ui.Dialog({
title: __("Create or Edit Print Format"),
fields: [
{
label: __("Action"),
fieldname: "action",
fieldtype: "Select",
options: [
{ label: __("Create New"), value: "Create" },
{ label: __("Edit Existing"), value: "Edit" },
],
change() {
let action = d.get_value("action");
d.get_primary_btn().text(action === "Create" ? __("Create") : __("Edit"));
},
},
{
label: __("Select Document Type"),
fieldname: "doctype",
fieldtype: "Link",
options: "DocType",
filters: {
istable: 0,
},
reqd: 1,
default: frappe.route_options ? frappe.route_options.doctype : null,
},
{
label: __("Print Format Name"),
fieldname: "print_format_name",
fieldtype: "Data",
depends_on: (doc) => doc.action === "Create",
mandatory_depends_on: (doc) => doc.action === "Create",
},
{
label: __("Select Print Format"),
fieldname: "print_format",
fieldtype: "Link",
options: "Print Format",
only_select: 1,
depends_on: (doc) => doc.action === "Edit",
get_query() {
return {
filters: {
doc_type: d.get_value("doctype"),
print_designer: 1,
},
};
},
mandatory_depends_on: (doc) => doc.action === "Edit",
},
],
static: true,
primary_action_label: __("Edit"),
primary_action({ action, doctype, print_format, print_format_name }) {
if (action === "Edit") {
frappe.set_route("print-designer", print_format);
} else if (action === "Create") {
d.get_primary_btn().prop("disabled", true);
frappe.db
.insert({
doctype: "Print Format",
name: print_format_name,
doc_type: doctype,
print_designer: 1,
print_designer_header: JSON.stringify([
{
type: "page",
childrens: [],
firstPage: true,
oddPage: true,
evenPage: true,
lastPage: true,
DOMRef: null,
},
]),
print_designer_body: JSON.stringify([
{
type: "page",
index: 0,
DOMRef: null,
isDropZone: true,
childrens: [],
},
]),
print_designer_footer: JSON.stringify([
{
type: "page",
childrens: [],
firstPage: true,
oddPage: true,
evenPage: true,
lastPage: true,
DOMRef: null,
},
]),
})
.then((doc) => {
// Incase Route is Same, set_route() is needed to refresh.
set_current_doc(doc.name).then(() => {
frappe.set_route("print-designer", doc.name);
});
})
.finally(() => {
d.get_primary_btn().prop("disabled", false);
});
}
},
secondary_action_label: __("Exit"),
secondary_action() {
let prev_route = frappe.get_prev_route();
prev_route.length ? frappe.set_route(...prev_route) : frappe.set_route();
},
});
return d;
};
const set_current_doc = async (format_name) => {
let currentDoc = null;
let doctype = await frappe.db.get_value("Print Format", format_name, "doc_type");
doctype = doctype.message?.doc_type;
let route_history = [
...frappe.route_history.filter(
(r) => ["print", "Form"].indexOf(r[0]) != -1 && r[1] == doctype
),
].reverse();
if (route_history.length) {
currentDoc = route_history[0][2];
}
if (!currentDoc) return;
let isdocvalid = await frappe.db.exists(doctype, currentDoc);
if (!isdocvalid) return;
let settings = await frappe.db.get_value(
"Print Format",
format_name,
"print_designer_settings"
);
if (!settings.message?.print_designer_settings) return;
settings = JSON.parse(settings.message.print_designer_settings);
settings["currentDoc"] = currentDoc;
await frappe.db.set_value(
"Print Format",
format_name,
"print_designer_settings",
JSON.stringify(settings)
);
};
const load_print_designer = async (wrapper) => {
let route = frappe.get_route();
let $parent = $(wrapper);
let is_print_format;
let message = `Print Format <b>${route[1]}</b> not found. <hr/> Would you like to Create or Edit other Print Format?`;
if (route.length > 1 && route[1].length) {
is_print_format = await frappe.db.get_value("Print Format", route[1], "print_designer");
if (typeof is_print_format.message.print_designer == "number") {
is_print_format = is_print_format.message.print_designer;
message = `Print Format <b>${route[1]}</b> is not made using Print Designer. <hr/> Would you like to Create or Edit other Print Format?`;
} else {
is_print_format = false;
}
}
if (route.length > 1 && route[1].length) {
if (is_print_format) {
await set_current_doc(route[1]);
await frappe.require("print_designer.bundle.js");
frappe.print_designer = new frappe.ui.PrintDesigner({
wrapper: $parent,
print_format: route[1],
});
} else {
frappe.confirm(
message,
() => {
let d = printDesignerDialog();
if (typeof is_print_format == "number") {
d.set_value("action", "Create");
} else {
d.set_value("action", "Edit");
}
},
() => {
let prev_route = frappe.get_prev_route();
prev_route.length ? frappe.set_route(...prev_route) : frappe.set_route();
}
);
}
} else {
let d = printDesignerDialog();
d.set_value("action", "Create");
}
};
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/print_designer.js
|
JavaScript
|
agpl-3.0
| 5,667
|
from typing import Literal
import frappe
from frappe.model.document import BaseDocument
from frappe.utils.jinja import get_jenv
@frappe.whitelist(allow_guest=False)
def render_user_text_withdoc(string, doctype, docname=None, row=None, send_to_jinja=None):
if not row:
row = {}
if not send_to_jinja:
send_to_jinja = {}
if not docname or docname == "":
return render_user_text(string=string, doc={}, row=row, send_to_jinja=send_to_jinja)
doc = frappe.get_cached_doc(doctype, docname)
doc.check_permission()
return render_user_text(string=string, doc=doc, row=row, send_to_jinja=send_to_jinja)
@frappe.whitelist(allow_guest=False)
def get_meta(doctype):
return frappe.get_meta(doctype).as_dict()
@frappe.whitelist(allow_guest=False)
def render_user_text(string, doc, row=None, send_to_jinja=None):
if not row:
row = {}
if not send_to_jinja:
send_to_jinja = {}
jinja_vars = {}
if isinstance(send_to_jinja, dict):
jinja_vars = send_to_jinja
elif send_to_jinja != "" and isinstance(send_to_jinja, str):
try:
jinja_vars = frappe.parse_json(send_to_jinja)
except Exception:
pass
if not (isinstance(row, dict) or issubclass(row.__class__, BaseDocument)):
if isinstance(row, str):
try:
row = frappe.parse_json(row)
except Exception:
raise TypeError("row must be a dict")
else:
raise TypeError("row must be a dict")
if not issubclass(doc.__class__, BaseDocument):
# This is when we send doc from client side as a json string
if isinstance(doc, str):
try:
doc = frappe.parse_json(doc)
except Exception:
raise TypeError("doc must be a dict or subclass of BaseDocument")
jenv = get_jenv()
result = {}
try:
result["success"] = 1
result["message"] = jenv.from_string(string).render({"doc": doc, "row": row, **jinja_vars})
except Exception as e:
"""
string is provided by user and there is no way to know if it is correct or not so log the error from client side
"""
result["success"] = 0
result["error"] = e
return result
@frappe.whitelist(allow_guest=False)
def get_data_from_main_template(string, doctype, docname=None, settings=None):
if not settings:
settings = {}
result = {}
if string.find("send_to_jinja") == -1:
result["success"] = 1
result["message"] = ""
return result
string = string + "{{ send_to_jinja|tojson }}"
if not isinstance(settings, dict):
if isinstance(settings, str):
try:
settings = frappe.parse_json(settings)
except Exception:
raise TypeError("settings must be a dict")
else:
raise TypeError("settings must be a dict")
if not docname or docname == "":
doc = {}
else:
doc = frappe.get_cached_doc(doctype, docname)
jenv = get_jenv()
try:
result["success"] = 1
result["message"] = jenv.from_string(string).render({"doc": doc, "settings": settings}).strip()
except Exception as e:
"""
string is provided by user and there is no way to know if it is correct or not
also doc is required if used in string else it is not required so there is no way
for us to decide whether to run this or not if doc is not available
"""
result["success"] = 0
result["error"] = e
return result
@frappe.whitelist(allow_guest=False)
def get_image_docfields():
docfield = frappe.qb.DocType("DocField")
image_docfields = (
frappe.qb.from_(docfield)
.select(
docfield.name,
docfield.parent,
docfield.fieldname,
docfield.fieldtype,
docfield.label,
docfield.options,
)
.where((docfield.fieldtype == "Image") | (docfield.fieldtype == "Attach Image"))
.orderby(docfield.parent)
).run(as_dict=True)
return image_docfields
@frappe.whitelist()
def convert_css(css_obj):
string_css = ""
if css_obj:
for item in css_obj.items():
string_css += (
"".join(["-" + i.lower() if i.isupper() else i for i in item[0]]).lstrip("-")
+ ":"
+ str(item[1] if item[1] != "" or item[0] != "backgroundColor" else "transparent")
+ "!important;"
)
string_css += "user-select: all;"
return string_css
@frappe.whitelist()
def convert_uom(
number: float,
from_uom: Literal["px", "mm", "cm", "in"] = "px",
to_uom: Literal["px", "mm", "cm", "in"] = "px",
) -> float:
unit_values = {
"px": 1,
"mm": 3.7795275591,
"cm": 37.795275591,
"in": 96,
}
from_px = (
{
"to_px": 1,
"to_mm": unit_values["px"] / unit_values["mm"],
"to_cm": unit_values["px"] / unit_values["cm"],
"to_in": unit_values["px"] / unit_values["in"],
},
)
from_mm = (
{
"to_mm": 1,
"to_px": unit_values["mm"] / unit_values["px"],
"to_cm": unit_values["mm"] / unit_values["cm"],
"to_in": unit_values["mm"] / unit_values["in"],
},
)
from_cm = (
{
"to_cm": 1,
"to_px": unit_values["cm"] / unit_values["px"],
"to_mm": unit_values["cm"] / unit_values["mm"],
"to_in": unit_values["cm"] / unit_values["in"],
},
)
from_in = {
"to_in": 1,
"to_px": unit_values["in"] / unit_values["px"],
"to_mm": unit_values["in"] / unit_values["mm"],
"to_cm": unit_values["in"] / unit_values["cm"],
}
converstion_factor = (
{"from_px": from_px, "from_mm": from_mm, "from_cm": from_cm, "from_in": from_in},
)
return (
f"{round(number * converstion_factor[0][f'from_{from_uom}'][0][f'to_{to_uom}'], 3)}{to_uom}"
)
@frappe.whitelist()
def get_barcode(
barcode_format, barcode_value, options=None, width=None, height=None, png_base64=False
):
if not options:
options = {}
options = frappe.parse_json(options)
if isinstance(barcode_value, str) and barcode_value.startswith("<svg"):
import re
barcode_value = re.search(r'data-barcode-value="(.*?)">', barcode_value).group(1)
if barcode_value == "":
fallback_html_string = """
<div class="fallback-barcode">
<div class="content">
<span>No Value was Provided to Barcode</span>
</div>
</div>
"""
return {"type": "svg", "value": fallback_html_string}
if barcode_format == "qrcode":
return get_qrcode(barcode_value, options, png_base64)
from io import BytesIO
import barcode
from barcode.writer import ImageWriter, SVGWriter
class PDSVGWriter(SVGWriter):
def __init__(self):
SVGWriter.__init__(self)
def calculate_viewbox(self, code):
vw, vh = self.calculate_size(len(code[0]), len(code))
return vw, vh
def _init(self, code):
SVGWriter._init(self, code)
vw, vh = self.calculate_viewbox(code)
if not width:
self._root.removeAttribute("width")
else:
self._root.setAttribute("width", f"{width * 3.7795275591}")
if not height:
self._root.removeAttribute("height")
else:
print(height)
self._root.setAttribute("height", height)
self._root.setAttribute("viewBox", f"0 0 {vw * 3.7795275591} {vh * 3.7795275591}")
if barcode_format not in barcode.PROVIDED_BARCODES:
return (
f"Barcode format {barcode_format} not supported. Valid formats are: {barcode.PROVIDED_BARCODES}"
)
writer = ImageWriter() if png_base64 else PDSVGWriter()
barcode_class = barcode.get_barcode_class(barcode_format)
try:
barcode = barcode_class(barcode_value, writer)
except Exception:
frappe.msgprint(
f"Invalid barcode value <b>{barcode_value}</b> for format <b>{barcode_format}</b>",
raise_exception=True,
alert=True,
indicator="red",
)
stream = BytesIO()
barcode.write(stream, options)
barcode_value = stream.getvalue().decode("utf-8")
stream.close()
if png_base64:
import base64
barcode_value = base64.b64encode(barcode_value)
return {"type": "png_base64" if png_base64 else "svg", "value": barcode_value}
def get_qrcode(barcode_value, options=None, png_base64=False):
from io import BytesIO
import pyqrcode
if not options:
options = {}
options = frappe.parse_json(options)
options = {
"scale": options.get("scale", 5),
"module_color": options.get("module_color", "#000000"),
"background": options.get("background", "#ffffff"),
"quiet_zone": options.get("quiet_zone", 1),
}
qr = pyqrcode.create(barcode_value)
stream = BytesIO()
if png_base64:
qrcode_svg = qr.png_as_base64_str(**options)
else:
options.update(
{"svgclass": "print-qrcode", "lineclass": "print-qrcode-path", "omithw": True, "xmldecl": False}
)
qr.svg(stream, **options)
qrcode_svg = stream.getvalue().decode("utf-8")
stream.close()
return {"type": "png_base64" if png_base64 else "svg", "value": qrcode_svg}
|
2302_79757062/print_designer
|
print_designer/print_designer/page/print_designer/print_designer.py
|
Python
|
agpl-3.0
| 8,292
|
/* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
:root {
--highlight-bg-color: rgb(0, 111, 180);
--highlight-selected-bg-color: rgba(0, 100, 0, 1);
}
@media screen and (forced-colors: active) {
:root {
--highlight-bg-color: Highlight;
--highlight-selected-bg-color: ButtonText;
}
}
.textLayer {
position: absolute;
text-align: initial;
left: 0;
top: 0;
right: 0;
bottom: 0;
overflow: hidden;
opacity: 0.25;
line-height: 1;
-webkit-text-size-adjust: none;
-moz-text-size-adjust: none;
text-size-adjust: none;
forced-color-adjust: none;
transform-origin: 0 0;
z-index: 2;
}
.textLayer span,
.textLayer br {
color: transparent;
position: absolute;
white-space: pre;
cursor: text;
transform-origin: 0% 0%;
}
/* Only necessary in Google Chrome, see issue 14205, and most unfortunately
* the problem doesn't show up in "text" reference tests. */
.textLayer span.markedContent {
top: 0;
height: 0;
}
.textLayer .highlight {
margin: -1px;
padding: 1px;
background-color: var(--highlight-bg-color);
border-radius: 4px;
}
.textLayer .highlight.appended {
position: initial;
}
.textLayer .highlight.begin {
border-radius: 4px 0 0 4px;
}
.textLayer .highlight.end {
border-radius: 0 4px 4px 0;
}
.textLayer .highlight.middle {
border-radius: 0;
}
.textLayer .highlight.selected {
background-color: var(--highlight-selected-bg-color);
}
.textLayer ::-moz-selection {
background: rgb(0, 140, 255);
background: AccentColor;
}
.textLayer ::selection {
background: rgb(0, 140, 255);
background: AccentColor;
}
/* Avoids https://github.com/mozilla/pdf.js/issues/13840 in Chrome */
.textLayer br::-moz-selection {
background: transparent;
}
.textLayer br::selection {
background: transparent;
}
.textLayer .endOfContent {
display: block;
position: absolute;
left: 0;
top: 100%;
right: 0;
bottom: 0;
z-index: -1;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
.textLayer .endOfContent.active {
top: 0;
}
:root {
--annotation-unfocused-field-background: url("data:image/svg+xml;charset=UTF-8,<svg width='1px' height='1px' xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' style='fill:rgba(0, 54, 255, 0.13);'/></svg>");
--input-focus-border-color: Highlight;
--input-focus-outline: 1px solid Canvas;
--input-unfocused-border-color: transparent;
--input-disabled-border-color: transparent;
--input-hover-border-color: black;
--link-outline: none;
}
@media screen and (forced-colors: active) {
:root {
--input-focus-border-color: CanvasText;
--input-unfocused-border-color: ActiveText;
--input-disabled-border-color: GrayText;
--input-hover-border-color: Highlight;
--link-outline: 1.5px solid LinkText;
}
.annotationLayer .textWidgetAnnotation input:required,
.annotationLayer .textWidgetAnnotation textarea:required,
.annotationLayer .choiceWidgetAnnotation select:required,
.annotationLayer .buttonWidgetAnnotation.checkBox input:required,
.annotationLayer .buttonWidgetAnnotation.radioButton input:required {
outline: 1.5px solid selectedItem;
}
.annotationLayer .linkAnnotation:hover {
-webkit-backdrop-filter: invert(100%);
backdrop-filter: invert(100%);
}
}
.annotationLayer {
position: absolute;
top: 0;
left: 0;
pointer-events: none;
transform-origin: 0 0;
z-index: 3;
}
.annotationLayer section {
position: absolute;
text-align: initial;
pointer-events: auto;
box-sizing: border-box;
transform-origin: 0 0;
}
.annotationLayer .linkAnnotation {
outline: var(--link-outline);
}
.annotationLayer .linkAnnotation > a,
.annotationLayer .buttonWidgetAnnotation.pushButton > a {
position: absolute;
font-size: 1em;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.annotationLayer .buttonWidgetAnnotation.pushButton > canvas {
width: 100%;
height: 100%;
}
.annotationLayer .linkAnnotation > a:hover,
.annotationLayer .buttonWidgetAnnotation.pushButton > a:hover {
opacity: 0.2;
background: rgba(255, 255, 0, 1);
box-shadow: 0 2px 10px rgba(255, 255, 0, 1);
}
.annotationLayer .textAnnotation img {
position: absolute;
cursor: pointer;
width: 100%;
height: 100%;
}
.annotationLayer .textWidgetAnnotation input,
.annotationLayer .textWidgetAnnotation textarea,
.annotationLayer .choiceWidgetAnnotation select,
.annotationLayer .buttonWidgetAnnotation.checkBox input,
.annotationLayer .buttonWidgetAnnotation.radioButton input {
background-image: var(--annotation-unfocused-field-background);
border: 2px solid var(--input-unfocused-border-color);
box-sizing: border-box;
font: calc(9px * var(--scale-factor)) sans-serif;
height: 100%;
margin: 0;
vertical-align: top;
width: 100%;
}
.annotationLayer .textWidgetAnnotation input:required,
.annotationLayer .textWidgetAnnotation textarea:required,
.annotationLayer .choiceWidgetAnnotation select:required,
.annotationLayer .buttonWidgetAnnotation.checkBox input:required,
.annotationLayer .buttonWidgetAnnotation.radioButton input:required {
outline: 1.5px solid red;
}
.annotationLayer .choiceWidgetAnnotation select option {
padding: 0;
}
.annotationLayer .buttonWidgetAnnotation.radioButton input {
border-radius: 50%;
}
.annotationLayer .textWidgetAnnotation textarea {
resize: none;
}
.annotationLayer .textWidgetAnnotation input[disabled],
.annotationLayer .textWidgetAnnotation textarea[disabled],
.annotationLayer .choiceWidgetAnnotation select[disabled],
.annotationLayer .buttonWidgetAnnotation.checkBox input[disabled],
.annotationLayer .buttonWidgetAnnotation.radioButton input[disabled] {
background: none;
border: 2px solid var(--input-disabled-border-color);
cursor: not-allowed;
}
.annotationLayer .textWidgetAnnotation input:hover,
.annotationLayer .textWidgetAnnotation textarea:hover,
.annotationLayer .choiceWidgetAnnotation select:hover,
.annotationLayer .buttonWidgetAnnotation.checkBox input:hover,
.annotationLayer .buttonWidgetAnnotation.radioButton input:hover {
border: 2px solid var(--input-hover-border-color);
}
.annotationLayer .textWidgetAnnotation input:hover,
.annotationLayer .textWidgetAnnotation textarea:hover,
.annotationLayer .choiceWidgetAnnotation select:hover,
.annotationLayer .buttonWidgetAnnotation.checkBox input:hover {
border-radius: 2px;
}
.annotationLayer .textWidgetAnnotation input:focus,
.annotationLayer .textWidgetAnnotation textarea:focus,
.annotationLayer .choiceWidgetAnnotation select:focus {
background: none;
border: 2px solid var(--input-focus-border-color);
border-radius: 2px;
outline: var(--input-focus-outline);
}
.annotationLayer .buttonWidgetAnnotation.checkBox :focus,
.annotationLayer .buttonWidgetAnnotation.radioButton :focus {
background-image: none;
background-color: transparent;
}
.annotationLayer .buttonWidgetAnnotation.checkBox :focus {
border: 2px solid var(--input-focus-border-color);
border-radius: 2px;
outline: var(--input-focus-outline);
}
.annotationLayer .buttonWidgetAnnotation.radioButton :focus {
border: 2px solid var(--input-focus-border-color);
outline: var(--input-focus-outline);
}
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked:before,
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked:after,
.annotationLayer .buttonWidgetAnnotation.radioButton input:checked:before {
background-color: CanvasText;
content: "";
display: block;
position: absolute;
}
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked:before,
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked:after {
height: 80%;
left: 45%;
width: 1px;
}
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked:before {
transform: rotate(45deg);
}
.annotationLayer .buttonWidgetAnnotation.checkBox input:checked:after {
transform: rotate(-45deg);
}
.annotationLayer .buttonWidgetAnnotation.radioButton input:checked:before {
border-radius: 50%;
height: 50%;
left: 30%;
top: 20%;
width: 50%;
}
.annotationLayer .textWidgetAnnotation input.comb {
font-family: monospace;
padding-left: 2px;
padding-right: 0;
}
.annotationLayer .textWidgetAnnotation input.comb:focus {
/*
* Letter spacing is placed on the right side of each character. Hence, the
* letter spacing of the last character may be placed outside the visible
* area, causing horizontal scrolling. We avoid this by extending the width
* when the element has focus and revert this when it loses focus.
*/
width: 103%;
}
.annotationLayer .buttonWidgetAnnotation.checkBox input,
.annotationLayer .buttonWidgetAnnotation.radioButton input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.annotationLayer .popupTriggerArea {
height: 100%;
width: 100%;
}
.annotationLayer .popupWrapper {
position: absolute;
font-size: calc(9px * var(--scale-factor));
width: 100%;
min-width: calc(180px * var(--scale-factor));
pointer-events: none;
}
.annotationLayer .popup {
position: absolute;
max-width: calc(180px * var(--scale-factor));
background-color: rgba(255, 255, 153, 1);
box-shadow: 0 calc(2px * var(--scale-factor)) calc(5px * var(--scale-factor))
rgba(136, 136, 136, 1);
border-radius: calc(2px * var(--scale-factor));
padding: calc(6px * var(--scale-factor));
margin-left: calc(5px * var(--scale-factor));
cursor: pointer;
font: message-box;
white-space: normal;
word-wrap: break-word;
pointer-events: auto;
}
.annotationLayer .popup > * {
font-size: calc(9px * var(--scale-factor));
}
.annotationLayer .popup h1 {
display: inline-block;
}
.annotationLayer .popupDate {
display: inline-block;
margin-left: calc(5px * var(--scale-factor));
}
.annotationLayer .popupContent {
border-top: 1px solid rgba(51, 51, 51, 1);
margin-top: calc(2px * var(--scale-factor));
padding-top: calc(2px * var(--scale-factor));
}
.annotationLayer .richText > * {
white-space: pre-wrap;
font-size: calc(9px * var(--scale-factor));
}
.annotationLayer .highlightAnnotation,
.annotationLayer .underlineAnnotation,
.annotationLayer .squigglyAnnotation,
.annotationLayer .strikeoutAnnotation,
.annotationLayer .freeTextAnnotation,
.annotationLayer .lineAnnotation svg line,
.annotationLayer .squareAnnotation svg rect,
.annotationLayer .circleAnnotation svg ellipse,
.annotationLayer .polylineAnnotation svg polyline,
.annotationLayer .polygonAnnotation svg polygon,
.annotationLayer .caretAnnotation,
.annotationLayer .inkAnnotation svg polyline,
.annotationLayer .stampAnnotation,
.annotationLayer .fileAttachmentAnnotation {
cursor: pointer;
}
.annotationLayer section svg {
position: absolute;
width: 100%;
height: 100%;
}
.annotationLayer .annotationTextContent {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
color: transparent;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
pointer-events: none;
}
.annotationLayer .annotationTextContent span {
width: 100%;
display: inline-block;
}
:root {
--xfa-unfocused-field-background: url("data:image/svg+xml;charset=UTF-8,<svg width='1px' height='1px' xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' style='fill:rgba(0, 54, 255, 0.13);'/></svg>");
--xfa-focus-outline: auto;
}
@media screen and (forced-colors: active) {
:root {
--xfa-focus-outline: 2px solid CanvasText;
}
.xfaLayer *:required {
outline: 1.5px solid selectedItem;
}
}
.xfaLayer {
background-color: transparent;
}
.xfaLayer .highlight {
margin: -1px;
padding: 1px;
background-color: rgb(136, 212, 240);
border-radius: 4px;
}
.xfaLayer .highlight.appended {
position: initial;
}
.xfaLayer .highlight.begin {
border-radius: 4px 0 0 4px;
}
.xfaLayer .highlight.end {
border-radius: 0 4px 4px 0;
}
.xfaLayer .highlight.middle {
border-radius: 0;
}
.xfaLayer .highlight.selected {
background-color: rgba(203, 223, 203, 1);
}
.xfaPage {
overflow: hidden;
position: relative;
}
.xfaContentarea {
position: absolute;
}
.xfaPrintOnly {
display: none;
}
.xfaLayer {
position: absolute;
text-align: initial;
top: 0;
left: 0;
transform-origin: 0 0;
line-height: 1.2;
}
.xfaLayer * {
color: inherit;
font: inherit;
font-style: inherit;
font-weight: inherit;
font-kerning: inherit;
letter-spacing: -0.01px;
text-align: inherit;
text-decoration: inherit;
box-sizing: border-box;
background-color: transparent;
padding: 0;
margin: 0;
pointer-events: auto;
line-height: inherit;
}
.xfaLayer *:required {
outline: 1.5px solid red;
}
.xfaLayer div {
pointer-events: none;
}
.xfaLayer svg {
pointer-events: none;
}
.xfaLayer svg * {
pointer-events: none;
}
.xfaLayer a {
color: blue;
}
.xfaRich li {
margin-left: 3em;
}
.xfaFont {
color: black;
font-weight: normal;
font-kerning: none;
font-size: 10px;
font-style: normal;
letter-spacing: 0;
text-decoration: none;
vertical-align: 0;
}
.xfaCaption {
overflow: hidden;
flex: 0 0 auto;
}
.xfaCaptionForCheckButton {
overflow: hidden;
flex: 1 1 auto;
}
.xfaLabel {
height: 100%;
width: 100%;
}
.xfaLeft {
display: flex;
flex-direction: row;
align-items: center;
}
.xfaRight {
display: flex;
flex-direction: row-reverse;
align-items: center;
}
.xfaLeft > .xfaCaption,
.xfaLeft > .xfaCaptionForCheckButton,
.xfaRight > .xfaCaption,
.xfaRight > .xfaCaptionForCheckButton {
max-height: 100%;
}
.xfaTop {
display: flex;
flex-direction: column;
align-items: flex-start;
}
.xfaBottom {
display: flex;
flex-direction: column-reverse;
align-items: flex-start;
}
.xfaTop > .xfaCaption,
.xfaTop > .xfaCaptionForCheckButton,
.xfaBottom > .xfaCaption,
.xfaBottom > .xfaCaptionForCheckButton {
width: 100%;
}
.xfaBorder {
background-color: transparent;
position: absolute;
pointer-events: none;
}
.xfaWrapped {
width: 100%;
height: 100%;
}
.xfaTextfield:focus,
.xfaSelect:focus {
background-image: none;
background-color: transparent;
outline: var(--xfa-focus-outline);
outline-offset: -1px;
}
.xfaCheckbox:focus,
.xfaRadio:focus {
outline: var(--xfa-focus-outline);
}
.xfaTextfield,
.xfaSelect {
height: 100%;
width: 100%;
flex: 1 1 auto;
border: none;
resize: none;
background-image: var(--xfa-unfocused-field-background);
}
.xfaSelect {
padding-inline: 2px;
}
.xfaTop > .xfaTextfield,
.xfaTop > .xfaSelect,
.xfaBottom > .xfaTextfield,
.xfaBottom > .xfaSelect {
flex: 0 1 auto;
}
.xfaButton {
cursor: pointer;
width: 100%;
height: 100%;
border: none;
text-align: center;
}
.xfaLink {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
}
.xfaCheckbox,
.xfaRadio {
width: 100%;
height: 100%;
flex: 0 0 auto;
border: none;
}
.xfaRich {
white-space: pre-wrap;
width: 100%;
height: 100%;
}
.xfaImage {
-o-object-position: left top;
object-position: left top;
-o-object-fit: contain;
object-fit: contain;
width: 100%;
height: 100%;
}
.xfaLrTb,
.xfaRlTb,
.xfaTb {
display: flex;
flex-direction: column;
align-items: stretch;
}
.xfaLr {
display: flex;
flex-direction: row;
align-items: stretch;
}
.xfaRl {
display: flex;
flex-direction: row-reverse;
align-items: stretch;
}
.xfaTb > div {
justify-content: left;
}
.xfaPosition {
position: relative;
}
.xfaArea {
position: relative;
}
.xfaValignMiddle {
display: flex;
align-items: center;
}
.xfaTable {
display: flex;
flex-direction: column;
align-items: stretch;
}
.xfaTable .xfaRow {
display: flex;
flex-direction: row;
align-items: stretch;
}
.xfaTable .xfaRlRow {
display: flex;
flex-direction: row-reverse;
align-items: stretch;
flex: 1;
}
.xfaTable .xfaRlRow > div {
flex: 1;
}
.xfaNonInteractive input,
.xfaNonInteractive textarea,
.xfaDisabled input,
.xfaDisabled textarea,
.xfaReadOnly input,
.xfaReadOnly textarea {
background: initial;
}
@media print {
.xfaTextfield,
.xfaSelect {
background: transparent;
}
.xfaSelect {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
text-indent: 1px;
text-overflow: "";
}
}
:root {
--focus-outline: solid 2px blue;
--hover-outline: dashed 2px blue;
--freetext-line-height: 1.35;
--freetext-padding: 2px;
--editorFreeText-editing-cursor: text;
--editorInk-editing-cursor: pointer;
}
@media (-webkit-min-device-pixel-ratio: 1.1), (min-resolution: 1.1dppx) {
:root {
}
}
@media screen and (forced-colors: active) {
:root {
--focus-outline: solid 3px ButtonText;
--hover-outline: dashed 3px ButtonText;
}
}
[data-editor-rotation="90"] {
transform: rotate(90deg);
}
[data-editor-rotation="180"] {
transform: rotate(180deg);
}
[data-editor-rotation="270"] {
transform: rotate(270deg);
}
.annotationEditorLayer {
background: transparent;
position: absolute;
top: 0;
left: 0;
font-size: calc(100px * var(--scale-factor));
transform-origin: 0 0;
cursor: auto;
z-index: 4;
}
.annotationEditorLayer.freeTextEditing {
cursor: var(--editorFreeText-editing-cursor);
}
.annotationEditorLayer.inkEditing {
cursor: var(--editorInk-editing-cursor);
}
.annotationEditorLayer .selectedEditor {
outline: var(--focus-outline);
resize: none;
}
.annotationEditorLayer .freeTextEditor {
position: absolute;
background: transparent;
border-radius: 3px;
padding: calc(var(--freetext-padding) * var(--scale-factor));
resize: none;
width: auto;
height: auto;
z-index: 1;
transform-origin: 0 0;
touch-action: none;
cursor: auto;
}
.annotationEditorLayer .freeTextEditor .internal {
background: transparent;
border: none;
top: 0;
left: 0;
overflow: visible;
white-space: nowrap;
resize: none;
font: 10px sans-serif;
line-height: var(--freetext-line-height);
}
.annotationEditorLayer .freeTextEditor .overlay {
position: absolute;
display: none;
background: transparent;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.annotationEditorLayer .freeTextEditor .overlay.enabled {
display: block;
}
.annotationEditorLayer .freeTextEditor .internal:empty::before {
content: attr(default-content);
color: gray;
}
.annotationEditorLayer .freeTextEditor .internal:focus {
outline: none;
}
.annotationEditorLayer .inkEditor.disabled {
resize: none;
}
.annotationEditorLayer .inkEditor.disabled.selectedEditor {
resize: horizontal;
}
.annotationEditorLayer .freeTextEditor:hover:not(.selectedEditor),
.annotationEditorLayer .inkEditor:hover:not(.selectedEditor) {
outline: var(--hover-outline);
}
.annotationEditorLayer .inkEditor {
position: absolute;
background: transparent;
border-radius: 3px;
overflow: auto;
width: 100%;
height: 100%;
z-index: 1;
transform-origin: 0 0;
cursor: auto;
}
.annotationEditorLayer .inkEditor.editing {
resize: none;
cursor: inherit;
}
.annotationEditorLayer .inkEditor .inkEditorCanvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
touch-action: none;
}
:root {
--viewer-container-height: 0;
--pdfViewer-padding-bottom: 0;
--page-margin: 1px auto -8px;
--page-border: 9px solid transparent;
--spreadHorizontalWrapped-margin-LR: -3.5px;
--loading-icon-delay: 400ms;
}
@media screen and (forced-colors: active) {
:root {
--pdfViewer-padding-bottom: 9px;
--page-margin: 8px auto -1px;
--page-border: 1px solid CanvasText;
--spreadHorizontalWrapped-margin-LR: 3.5px;
}
}
[data-main-rotation="90"] {
transform: rotate(90deg) translateY(-100%);
}
[data-main-rotation="180"] {
transform: rotate(180deg) translate(-100%, -100%);
}
[data-main-rotation="270"] {
transform: rotate(270deg) translateX(-100%);
}
.pdfViewer {
/* Define this variable here and not in :root to avoid to reflow all the UI
when scaling (see #15929). */
--scale-factor: 1;
padding-bottom: var(--pdfViewer-padding-bottom);
}
.pdfViewer .canvasWrapper {
overflow: hidden;
width: 100%;
height: 100%;
z-index: 1;
}
.pdfViewer .page {
direction: ltr;
width: 816px;
height: 1056px;
margin: var(--page-margin);
position: relative;
overflow: visible;
border: var(--page-border);
background-clip: content-box;
background-color: rgba(255, 255, 255, 1);
}
.pdfViewer .dummyPage {
position: relative;
width: 0;
height: var(--viewer-container-height);
}
.pdfViewer.removePageBorders .page {
margin: 0 auto 10px;
border: none;
}
.pdfViewer.singlePageView {
display: inline-block;
}
.pdfViewer.singlePageView .page {
margin: 0;
border: none;
}
.pdfViewer.scrollHorizontal,
.pdfViewer.scrollWrapped,
.spread {
margin-left: 3.5px;
margin-right: 3.5px;
text-align: center;
}
.pdfViewer.scrollHorizontal,
.spread {
white-space: nowrap;
}
.pdfViewer.removePageBorders,
.pdfViewer.scrollHorizontal .spread,
.pdfViewer.scrollWrapped .spread {
margin-left: 0;
margin-right: 0;
}
.spread .page,
.spread .dummyPage,
.pdfViewer.scrollHorizontal .page,
.pdfViewer.scrollWrapped .page,
.pdfViewer.scrollHorizontal .spread,
.pdfViewer.scrollWrapped .spread {
display: inline-block;
vertical-align: middle;
}
.spread .page,
.pdfViewer.scrollHorizontal .page,
.pdfViewer.scrollWrapped .page {
margin-left: var(--spreadHorizontalWrapped-margin-LR);
margin-right: var(--spreadHorizontalWrapped-margin-LR);
}
.pdfViewer.removePageBorders .spread .page,
.pdfViewer.removePageBorders.scrollHorizontal .page,
.pdfViewer.removePageBorders.scrollWrapped .page {
margin-left: 5px;
margin-right: 5px;
}
.pdfViewer .page canvas {
margin: 0;
display: block;
}
.pdfViewer .page canvas .structTree {
contain: strict;
}
.pdfViewer .page canvas[hidden] {
display: none;
}
.pdfViewer .page canvas[zooming] {
width: 100%;
height: 100%;
}
.pdfViewer .page.loadingIcon:after {
position: absolute;
top: 0;
left: 0;
content: "";
width: 100%;
height: 100%;
display: none;
/* Using a delay with background-image doesn't work,
consequently we use the display. */
transition-property: display;
transition-delay: var(--loading-icon-delay);
z-index: 5;
contain: strict;
}
.pdfViewer .page.loading:after {
display: block;
}
.pdfViewer .page:not(.loading):after {
transition-property: none;
display: none;
}
.pdfViewer.enablePermissions .textLayer span {
-webkit-user-select: none !important;
-moz-user-select: none !important;
user-select: none !important;
cursor: not-allowed;
}
.pdfPresentationMode .pdfViewer {
padding-bottom: 0;
}
.pdfPresentationMode .spread {
margin: 0;
}
.pdfPresentationMode .pdfViewer .page {
margin: 0 auto;
border: 2px solid transparent;
}
|
2302_79757062/print_designer
|
print_designer/public/css/pdfjs.bundle.scss
|
SCSS
|
agpl-3.0
| 25,186
|
.print-designer-wrapper {
display:flex;
flex-direction:column;
overflow: auto;
padding: 40px 0;
background-color: var(--control-bg);
border-radius: var(--border-radius);
.preview-container {
margin: 0px 10px;
}
}
@media only screen and (min-width: 700px) {
.print-designer-wrapper {
padding: 80px 0;
align-items:center;
.preview-container {
margin: 0px;
}
}
}
|
2302_79757062/print_designer
|
print_designer/public/css/print_designer.bundle.scss
|
SCSS
|
agpl-3.0
| 452
|
import "./pdf.worker.min.js";
|
2302_79757062/print_designer
|
print_designer/public/js/pdf.worker.bundle.js
|
JavaScript
|
agpl-3.0
| 30
|
<template>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
v-for="currentFont in MainStore.currentFonts"
:key="currentFont"
:href="`https://fonts.googleapis.com/css2?family=${currentFont}:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap`"
rel="stylesheet"
/>
<link
rel="preload"
href="/assets/print_designer/images/mouse-pointer.svg"
as="image"
type="image/svg+xml"
/>
<link
rel="preload"
href="/assets/print_designer/images/add-text.svg"
as="image"
type="image/svg+xml"
/>
<link
rel="preload"
href="/assets/print_designer/images/add-image.svg"
as="image"
type="image/svg+xml"
/>
<link
rel="preload"
href="/assets/print_designer/images/add-table.svg"
as="image"
type="image/svg+xml"
/>
<link
rel="preload"
href="/assets/print_designer/images/add-rectangle.svg"
as="image"
type="image/svg+xml"
/>
<AppHeader :print_format_name="print_format_name" />
<div class="main-layout" id="main-layout">
<AppToolbar :class="toolbarClasses" />
<AppCanvas class="app-sections print-format-container" />
<AppPropertiesPanel class="app-sections properties-panel" />
</div>
</template>
<script setup>
import { computed, onMounted, watchEffect } from "vue";
import { useMainStore } from "./store/MainStore";
import AppHeader from "./components/layout/AppHeader.vue";
import AppToolbar from "./components/layout/AppToolbar.vue";
import AppCanvas from "./components/layout/AppCanvas.vue";
import AppPropertiesPanel from "./components/layout/AppPropertiesPanel.vue";
import { useAttachKeyBindings } from "./composables/AttachKeyBindings";
import { fetchMeta } from "./store/fetchMetaAndData";
const props = defineProps({
print_format_name: {
type: String,
required: true,
},
});
const MainStore = useMainStore();
const toolbarClasses = computed(() => {
return [
"app-sections",
"toolbar",
{ "toolbar-with-layer-panel": MainStore.isLayerPanelEnabled },
];
});
useAttachKeyBindings();
onMounted(() => {
MainStore.printDesignName = props.print_format_name;
fetchMeta();
const screen_stylesheet = document.createElement("style");
screen_stylesheet.title = "print-designer-stylesheet";
screen_stylesheet.rel = "stylesheet";
document.head.appendChild(screen_stylesheet);
const print_stylesheet = document.createElement("style");
print_stylesheet.title = "page-print-designer-stylesheet";
print_stylesheet.rel = "stylesheet";
print_stylesheet.media = "page";
document.head.appendChild(print_stylesheet);
for (let i = document.styleSheets.length - 1; i >= 0; i--) {
if (document.styleSheets[i].title == "print-designer-stylesheet") {
MainStore.screenStyleSheet = document.styleSheets[i];
} else if (document.styleSheets[i].title == "page-print-designer-stylesheet") {
MainStore.printStyleSheet = document.styleSheets[i];
}
}
});
watchEffect(() => {
if (MainStore.activeControl == "mouse-pointer") {
MainStore.isMarqueeActive = true;
MainStore.isDrawing = false;
} else if (["rectangle", "image", "table", "barcode"].includes(MainStore.activeControl)) {
MainStore.isMarqueeActive = false;
MainStore.isDrawing = true;
} else {
MainStore.isMarqueeActive = false;
MainStore.isDrawing = false;
}
});
</script>
<style deep lang="scss">
.main-layout {
display: flex;
justify-content: space-between;
margin: 0;
cursor: default;
--primary: #7b4b57;
--primary-color: #7b4b57;
.app-sections {
flex: 1;
height: calc(100vh - var(--navbar-height));
padding: 0;
margin-top: 0;
background-color: var(--card-bg);
box-shadow: var(--card-shadow);
}
.toolbar {
z-index: 1;
width: 44px;
max-width: 44px;
}
.toolbar-with-layer-panel {
width: 244px;
max-width: 244px;
box-shadow: unset;
}
.print-format-container {
overflow: auto;
display: flex;
position: relative;
flex-direction: column;
height: calc(100vh - var(--navbar-height));
background-color: var(--subtle-fg);
}
.properties-panel {
width: 250px;
max-width: 250px;
}
}
</style>
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/App.vue
|
Vue
|
agpl-3.0
| 4,071
|
import { useMainStore } from "./store/MainStore";
import { useElementStore } from "./store/ElementStore";
import { makeFeild } from "./frappeControl";
import { storeToRefs } from "pinia";
import {
parseFloatAndUnit,
handleAlignIconClick,
handleBorderIconClick,
getConditonalObject,
getParentPage,
} from "./utils";
export const createPropertiesPanel = () => {
const MainStore = useMainStore();
const ElementStore = useElementStore();
const iconControl = ({
name,
size,
padding,
margin,
onClick,
isActive,
onlyIcon = false,
parentBorderTop = false,
parentBorderBottom = false,
condtional = null,
...args
}) => {
const result = {
icon: { onlyIcon, name, size, padding, margin, onClick, isActive },
};
if (onlyIcon) {
result["name"] = name;
result["condtional"] = condtional;
result["parentBorderTop"] = parentBorderTop;
result["parentBorderBottom"] = parentBorderBottom;
if (Object.keys(args).length !== 0 && args.constructor === Object) {
Object.entries({ ...args })?.forEach((arg) => {
result[arg[0]] = arg[1];
});
}
}
return result;
};
const AlignIcons = (name) => {
return iconControl({
name,
size: 20,
padding: 3,
margin: 4,
onClick: () => handleAlignIconClick(name),
onlyIcon: true,
});
};
const textAlignIcons = (name) => {
const mapper = {
textAlignLeft: "left",
textAlignRight: "right",
textAlignCenter: "center",
textAlignJustify: "justify",
};
return iconControl({
name,
size: 20,
padding: 3,
margin: 5,
onClick: () =>
(getConditonalObject({
reactiveObject: () => MainStore.getCurrentElementsValues[0],
isStyle: true,
})["textAlign"] = mapper[name]),
isActive: () =>
getConditonalObject({
reactiveObject: () => MainStore.getCurrentElementsValues[0],
isStyle: true,
property: "textAlign",
}) == mapper[name],
onlyIcon: true,
parentBorderTop: true,
parentBorderBottom: true,
});
};
const borderWidthIcons = (name, { ...args }) => {
return iconControl({
name,
color: "var(--gray-500)",
size: 18,
padding: 2,
margin: 8,
condtional: () => {
return parseFloatAndUnit(
getConditonalObject({
reactiveObject: () => MainStore.getCurrentElementsValues[0],
isStyle: true,
property: "borderWidth",
})
).value;
},
onClick: () =>
handleBorderIconClick(
getConditonalObject({
reactiveObject: () => MainStore.getCurrentElementsValues[0],
isStyle: true,
}),
name
),
isActive: () => {
if (name === "borderAll") {
return [
"borderTopStyle",
"borderBottomStyle",
"borderLeftStyle",
"borderRightStyle",
].every(
(side) =>
getConditonalObject({
reactiveObject: () => MainStore.getCurrentElementsValues[0],
isStyle: true,
property: side,
}) != "hidden"
);
} else {
return (
getConditonalObject({
reactiveObject: () => MainStore.getCurrentElementsValues[0],
isStyle: true,
property: name,
}) != "hidden"
);
}
},
onlyIcon: true,
parentBorderTop: true,
parentBorderBottom: true,
...args,
});
};
const inputControl = ({
label,
name,
propertyName,
inputUnit,
labelDirection,
reactiveObject,
condtional = null,
...args
}) => {
const result = {
label,
name,
propertyName,
condtional,
labelDirection,
isLabelled: true,
inputUnit,
reactiveObject,
saveWithUom: false,
};
if (Object.keys(args).length !== 0 && args.constructor === Object) {
Object.entries({ ...args })?.forEach((arg) => {
result[arg[0]] = arg[1];
});
}
return result;
};
const pageInput = (label, name, propertyName, { ...args }) => {
return inputControl({
label,
name,
propertyName,
inputUnit: () => MainStore.page.UOM,
labelDirection: "column",
reactiveObject: () => MainStore.page,
...args,
});
};
const paddingInput = (label, name, propertyName) => {
return inputControl({
label,
name,
propertyName,
inputUnit: "px",
labelDirection: "column",
reactiveObject: () => MainStore.getCurrentElementsValues[0],
isStyle: true,
isFontStyle: true,
saveWithUom: true,
});
};
const transformInput = (label, name, propertyName) => {
return inputControl({
label,
name,
propertyName,
inputUnit: () => MainStore.page.UOM,
labelDirection: "row",
reactiveObject: () => MainStore.getCurrentElementsValues[0],
});
};
const inputWithIcon = ({
label,
name,
size,
padding,
margin,
inputUnit,
reactiveObject,
propertyName,
labelDirection = "row",
condtional = null,
isStyle = false,
saveWithUom = false,
...args
}) => {
const result = inputControl({
label,
name,
propertyName,
inputUnit,
isLabelled: false,
condtional,
reactiveObject,
labelDirection,
saveWithUom,
isStyle,
...args,
});
result["icon"] = iconControl({
name,
size,
padding,
margin,
}).icon;
return result;
};
const styleInputwithIcon = (
name,
size,
{ padding = 0, margin = 0, saveWithUom = false, isRaw = false, condtional = null, ...args }
) =>
inputWithIcon({
name,
propertyName: name,
size,
padding,
margin,
inputUnit: "px",
reactiveObject: () => MainStore.getCurrentElementsValues[0],
isStyle: true,
isRaw,
saveWithUom,
condtional,
...args,
});
const colorStyleFrappeControl = (
label,
name,
propertyName,
isFontStyle = false,
isStyle = true
) => {
return {
label,
name,
labelDirection: "column",
isLabelled: true,
frappeControl: (ref, name) => {
let styleClass = "table";
if (MainStore.activeControl == "text") {
if (MainStore.textControlType == "dynamic") {
styleClass = "dynamicText";
} else {
styleClass = "staticText";
}
}
makeFeild({
name,
ref,
fieldtype: "Color",
requiredData: [
MainStore.getCurrentElementsValues[0] ||
MainStore.globalStyles[styleClass],
],
reactiveObject: () => {
return (
MainStore.getCurrentElementsValues[0] ||
MainStore.globalStyles[styleClass]
);
},
propertyName,
isStyle,
isFontStyle,
});
},
};
};
MainStore.propertiesPanel.push({
sectionCondtional: () => !!MainStore.getCurrentElementsId.length,
fields: [
[
AlignIcons("alignLeft"),
AlignIcons("alignHorizontalCenter"),
AlignIcons("alignRight"),
AlignIcons("alignTop"),
AlignIcons("alignVerticalCenter"),
AlignIcons("alignBottom"),
],
],
});
MainStore.propertiesPanel.push({
title: "Page Settings",
sectionCondtional: () =>
!MainStore.getCurrentElementsId.length && MainStore.activeControl === "mouse-pointer",
fields: [
{
label: () => `Select ${MainStore.rawMeta?.name || "Document"}`,
isLabelled: true,
name: "documentName",
condtional: () => !!MainStore.currentDoc,
frappeControl: (ref, name) => {
const { doctype, currentDoc } = storeToRefs(MainStore);
makeFeild({
name: name,
ref: ref,
fieldtype: "Link",
requiredData: [doctype, currentDoc],
options: MainStore.doctype,
reactiveObject: MainStore,
propertyName: "currentDoc",
});
},
},
{
label: "Page Size",
name: "pageSize",
isLabelled: true,
condtional: null,
frappeControl: (ref, name) => {
const MainStore = useMainStore();
const { pageSizes } = storeToRefs(MainStore);
makeFeild({
name: name,
ref: ref,
fieldtype: "Autocomplete",
requiredData: pageSizes,
options: Object.keys(pageSizes.value),
reactiveObject: MainStore,
propertyName: "currentPageSize",
onChangeCallback: (value = null) => {
if (value && value != "CUSTOM") {
MainStore.currentPageSize = value;
MainStore.page.width = MainStore.convertToPX(
MainStore.pageSizes[value][0],
"mm"
);
MainStore.page.height = MainStore.convertToPX(
MainStore.pageSizes[value][1],
"mm"
);
} else {
MainStore.frappeControls[name].set_value(
MainStore.currentPageSize
);
}
},
});
},
},
{
label: "Page UOM",
name: "pageUom",
isLabelled: true,
condtional: null,
frappeControl: (ref, name) => {
const MainStore = useMainStore();
const { page } = storeToRefs(MainStore);
makeFeild({
name,
ref,
fieldtype: "Autocomplete",
requiredData: () => page.value.UOM,
options: () => [
{ label: "Pixels (px)", value: "px" },
{ label: "Milimeter (mm)", value: "mm" },
{ label: "Centimeter (cm)", value: "cm" },
{ label: "Inch (in)", value: "in" },
],
reactiveObject: page,
propertyName: "UOM",
});
},
},
[
pageInput("Height", "page_height", "height", {
parentBorderTop: true,
condtional: () => MainStore.mode == "editing",
}),
pageInput("Width", "page_width", "width", {
condtional: () => MainStore.mode == "editing",
}),
],
[
{
label: "Delete Page",
name: "deletePage",
isLabelled: true,
flex: "auto",
condtional: () => MainStore.activePage,
reactiveObject: () => MainStore.activePage,
button: {
label: "Delete Page",
size: "sm",
style: "secondary",
margin: 15,
onClick: (e, field) => {
if (MainStore.activePage?.childrens.length) {
let message = __("Are you sure you want to delete the page?");
frappe.confirm(message, () => {
ElementStore.Elements.splice(
ElementStore.Elements.indexOf(MainStore.activePage),
1
);
frappe.show_alert(
{
message: `Page Deleted Successfully`,
indicator: "green",
},
5
);
});
} else {
ElementStore.Elements.splice(
ElementStore.Elements.indexOf(MainStore.activePage),
1
);
frappe.show_alert(
{
message: `Page Deleted Successfully`,
indicator: "green",
},
5
);
}
e.target.blur();
},
},
},
],
],
});
MainStore.propertiesPanel.push({
title: "Page Margins",
sectionCondtional: () =>
!MainStore.getCurrentElementsId.length && MainStore.activeControl === "mouse-pointer",
fields: [
[
pageInput("Top", "page_top", "marginTop"),
pageInput("Bottom", "page_bottom", "marginBottom"),
],
[
pageInput("Left", "page_left", "marginLeft"),
pageInput("Right", "page_right", "marginRight"),
],
],
});
MainStore.propertiesPanel.push({
title: "Header / Footer",
sectionCondtional: () =>
!MainStore.getCurrentElementsId.length && MainStore.activeControl === "mouse-pointer",
fields: [
[
pageInput("Header", "page_header", "headerHeight"),
pageInput("Footer", "page_footer", "footerHeight"),
],
],
});
MainStore.propertiesPanel.push({
title: "Select Pages",
sectionCondtional: () =>
MainStore.mode != "editing" &&
MainStore.activePage &&
!MainStore.getCurrentElementsId.length &&
MainStore.activeControl === "mouse-pointer",
fields: [
[
{
label: "First",
name: "firstPage",
isLabelled: true,
condtional: () => MainStore.activePage,
reactiveObject: () => MainStore.activePage,
button: {
label: "First",
size: "sm",
style: () => (MainStore.activePage.firstPage ? "primary" : "secondary"),
margin: 15,
onClick: (e, field) => {
MainStore.activePage.firstPage = !MainStore.activePage.firstPage;
if (MainStore.activePage.firstPage) {
ElementStore.Elements.forEach((element) => {
if (element == MainStore.activePage) return;
element.firstPage = false;
});
}
e.target.blur();
},
},
},
{
label: "Odd",
name: "oddPages",
isLabelled: true,
condtional: () => MainStore.activePage,
reactiveObject: () => MainStore.activePage,
button: {
label: "Odd",
style: () => (MainStore.activePage.oddPage ? "primary" : "secondary"),
margin: 15,
size: "sm",
onClick: (e, field) => {
MainStore.activePage.oddPage = !MainStore.activePage.oddPage;
if (MainStore.activePage.oddPage) {
ElementStore.Elements.forEach((element) => {
if (element == MainStore.activePage) return;
element.oddPage = false;
});
}
e.target.blur();
},
},
},
{
label: "Even",
name: "evenPages",
isLabelled: true,
condtional: () => MainStore.activePage,
reactiveObject: () => MainStore.activePage,
button: {
label: "Even",
style: () => (MainStore.activePage.evenPage ? "primary" : "secondary"),
margin: 15,
size: "sm",
onClick: (e, field) => {
MainStore.activePage.evenPage = !MainStore.activePage.evenPage;
if (MainStore.activePage.evenPage) {
ElementStore.Elements.forEach((element) => {
if (element == MainStore.activePage) return;
element.evenPage = false;
});
}
e.target.blur();
},
},
},
{
label: "Last",
name: "lastPages",
isLabelled: true,
condtional: () => MainStore.activePage,
reactiveObject: () => MainStore.activePage,
button: {
label: "Last",
style: () => (MainStore.activePage.lastPage ? "primary" : "secondary"),
margin: 15,
size: "sm",
onClick: (e, field) => {
MainStore.activePage.lastPage = !MainStore.activePage.lastPage;
if (MainStore.activePage.lastPage) {
ElementStore.Elements.forEach((element) => {
if (element == MainStore.activePage) return;
element.lastPage = false;
});
}
e.target.blur();
},
},
},
],
],
});
MainStore.propertiesPanel.push({
title: "Transform",
sectionCondtional: () => MainStore.getCurrentElementsId.length === 1,
fields: [
[
transformInput("X", "transformStartX", "startX"),
transformInput("Y", "transformStartY", "startY"),
],
[
transformInput("H", "transformHeight", "height"),
transformInput("W", "transformWidth", "width"),
],
[
{
label: "Height",
name: "heightType",
isLabelled: true,
labelDirection: "column",
condtional: () => {
const currentEl = MainStore.getCurrentElementsValues[0];
if (
ElementStore.isElementOverlapping(
currentEl,
getParentPage(currentEl).childrens
)
) {
return false;
}
if (
currentEl?.type === "table" ||
(currentEl.type === "text" &&
(currentEl.isDynamic || currentEl.parseJinja))
) {
return true;
}
return false;
},
frappeControl: (ref, name) => {
const MainStore = useMainStore();
makeFeild({
name,
ref,
fieldtype: "Select",
requiredData: [MainStore.getCurrentElementsValues[0]],
reactiveObject: () => MainStore.getCurrentElementsValues[0],
propertyName: "heightType",
isStyle: false,
options: () => [
{ label: "Auto", value: "auto" },
{ label: "Auto ( min-height)", value: "auto-min-height" },
{ label: "Fixed", value: "fixed" },
],
});
},
flex: 1,
},
{
label: "Z Index",
name: "zIndex",
isLabelled: true,
labelDirection: "column",
condtional: () => MainStore.getCurrentElementsValues[0],
frappeControl: (ref, name) => {
const MainStore = useMainStore();
makeFeild({
name,
ref,
fieldtype: "Int",
requiredData: [MainStore.getCurrentElementsValues[0]],
reactiveObject: () => MainStore.getCurrentElementsValues[0],
propertyName: "zIndex",
isStyle: true,
formatValue: (object, property, isStyle) => {
if (!object) return;
return parseInt(object[property]) || 0;
},
});
},
flex: 1,
},
],
],
});
MainStore.propertiesPanel.push({
title: "Table Settings",
sectionCondtional: () =>
(MainStore.getCurrentElementsId.length === 1 &&
MainStore.getCurrentElementsValues[0]?.type == "table") ||
MainStore.activeControl == "table",
fields: [
[
{
label: "Current Table",
name: "table",
isLabelled: true,
labelDirection: "column",
flex: 3,
condtional: () => MainStore.getCurrentElementsValues[0]?.type == "table",
frappeControl: (ref, name) => {
const MainStore = useMainStore();
makeFeild({
name,
ref,
fieldtype: "Autocomplete",
requiredData: [MainStore.getTableMetaFields.length],
options: () => {
let tablefields = [];
MainStore.getTableMetaFields.map((field) =>
tablefields.push({
label: field.label || field.fieldname,
value: field.fieldname,
})
);
return tablefields;
},
reactiveObject: () => MainStore.getCurrentElementsValues[0],
propertyName: "table",
isStyle: false,
onChangeCallback: (value = null) => {
const currentEL = MainStore.getCurrentElementsValues[0];
const idx = {
fieldname: "idx",
fieldtype: "Int",
label: "No",
options: undefined,
tableName: currentEL["table"],
};
if (value && currentEL) {
currentEL["table"] = MainStore.metaFields.find(
(field) => field.fieldname == value
);
currentEL["table"].default_layout =
frappe.get_user_settings(MainStore.doctype, "GridView")[
currentEL["table"].options
] || {};
if (Object.keys(currentEL["table"].default_layout).length) {
df = { idx };
Object.values(currentEL["table"].default_layout).forEach(
(value) => {
key = value.fieldname;
df[key] = currentEL["table"].childfields.find(
(df) => df.fieldname == key
);
}
);
currentEL["table"].default_layout = df;
} else {
currentEL["table"].childfields.map((df) => {
currentEL["table"].default_layout["idx"] = idx;
if (
df.fieldname &&
df.in_list_view &&
!df.is_virtual &&
frappe.model.is_value_type(df) &&
df.fieldtype !== "Read Only" &&
!frappe.model.layout_fields.includes(df.fieldtype)
) {
currentEL["table"].default_layout[df.fieldname] =
df;
}
});
}
// fill columns with default fields if table is empty
if (
currentEL.columns &&
!currentEL.columns.some((c) => c.dynamicContent) &&
currentEL["table"].default_layout
) {
dlKeys = Object.keys(currentEL["table"].default_layout);
currentEL.columns
.slice(0, dlKeys.length)
.forEach((col, index) => {
col.dynamicContent = [
currentEL["table"].default_layout[
dlKeys[index]
],
];
col.dynamicContent.forEach((dc) => {
dc.tableName = currentEL["table"].fieldname;
});
col.label =
col.dynamicContent[0].label ||
col.dynamicContent[0].fieldname;
});
}
MainStore.frappeControls[name].$input.blur();
}
},
formatValue: (object, property, isStyle) => {
if (!object) return;
return object[property]?.fieldname || "";
},
});
},
},
{
label: "Rows",
name: "no_of_rows",
isLabelled: true,
labelDirection: "column",
condtional: () => MainStore.getCurrentElementsValues[0]?.table,
frappeControl: (ref, name) => {
const MainStore = useMainStore();
makeFeild({
name,
ref,
fieldtype: "Int",
requiredData: [MainStore.getCurrentElementsValues[0]],
reactiveObject: () => MainStore.getCurrentElementsValues[0],
propertyName: "PreviewRowNo",
isStyle: false,
onChangeCallback: (value = null) => {
if (
value &&
!Number.isInteger(MainStore.frappeControls["no_of_rows"].value)
) {
MainStore.frappeControls["no_of_rows"].set_value(
MainStore.frappeControls["no_of_rows"].last_value
);
}
},
});
},
flex: 1,
},
],
[
{
label: "Primary Table",
name: "isPrimaryTable",
isLabelled: true,
labelDirection: "column",
condtional: () => MainStore.getCurrentElementsValues[0]?.table,
frappeControl: (ref, name) => {
const MainStore = useMainStore();
const ElementStore = useElementStore();
makeFeild({
name,
ref,
fieldtype: "Select",
requiredData: [MainStore.getCurrentElementsValues[0]],
reactiveObject: () => MainStore.getCurrentElementsValues[0],
propertyName: "isPrimaryTable",
isStyle: false,
options: () => [
{ label: "Yes", value: "Yes" },
{ label: "No", value: "No" },
],
formatValue: (object, property, isStyle) => {
if (!object) return;
return object[property] ? "Yes" : "No";
},
onChangeCallback: (value = null) => {
if (value && MainStore.getCurrentElementsValues[0]) {
ElementStore.setPrimaryTable(
MainStore.getCurrentElementsValues[0],
value === "Yes"
);
MainStore.frappeControls[name].$input.blur();
}
},
});
},
flex: 1,
},
{
label: "Style Mode :",
isLabelled: true,
name: "tableStyleEditMode",
labelDirection: "column",
condtional: () =>
[
MainStore.getCurrentElementsValues[0]?.type,
MainStore.activeControl,
].indexOf("table") != -1,
frappeControl: (ref, name) => {
const MainStore = useMainStore();
makeFeild({
name: name,
ref: ref,
fieldtype: "Select",
requiredData: [MainStore],
options: () => {
return [
{ label: "Table Header", value: "header" },
{ label: "All Rows", value: "main" },
{ label: "Alternate Rows", value: "alt" },
{ label: "Field Labels", value: "label" },
];
},
reactiveObject: () => {
return (
MainStore.getCurrentElementsValues[0] ||
MainStore.globalStyles["table"]
);
},
onChangeCallback: (value) => {
if (MainStore.getCurrentElementsValues[0]?.selectedDynamicText) {
if (
MainStore.getCurrentElementsValues[0].styleEditMode ==
"label"
) {
MainStore.getCurrentElementsValues[0].selectedDynamicText.labelStyleEditing = true;
} else {
MainStore.getCurrentElementsValues[0].selectedDynamicText.labelStyleEditing = false;
if (
MainStore.getCurrentElementsValues[0].styleEditMode ==
"header"
) {
MainStore.getCurrentElementsValues[0].selectedDynamicText =
null;
}
}
}
if (
MainStore.getCurrentElementsValues[0]?.selectedColumn &&
value != "main"
) {
MainStore.getCurrentElementsValues[0].selectedColumn = null;
}
},
propertyName: "styleEditMode",
});
},
},
],
[
{
label: "Apply Style to Header",
name: "applyStyleToHeader",
isLabelled: true,
labelDirection: "column",
condtional: () =>
MainStore.getCurrentElementsValues[0]?.type == "table" &&
MainStore.getCurrentElementsValues[0].selectedColumn,
frappeControl: (ref, name) => {
const MainStore = useMainStore();
const ElementStore = useElementStore();
makeFeild({
name,
ref,
fieldtype: "Select",
requiredData: [MainStore.getCurrentElementsValues[0]],
reactiveObject: () =>
MainStore.getCurrentElementsValues[0].selectedColumn,
propertyName: "applyStyleToHeader",
isStyle: false,
options: () => [
{ label: "Yes", value: "Yes" },
{ label: "No", value: "No" },
],
formatValue: (object, property, isStyle) => {
if (!object) return;
return object[property] ? "Yes" : "No";
},
onChangeCallback: (value = null) => {
if (
value &&
MainStore.getCurrentElementsValues[0].selectedColumn
) {
MainStore.getCurrentElementsValues[0].selectedColumn.applyStyleToHeader =
value === "Yes";
MainStore.frappeControls[name].$input.blur();
}
},
});
},
flex: 1,
},
],
],
});
MainStore.propertiesPanel.push({
title: "Rectangle Settings",
sectionCondtional: () =>
MainStore.getCurrentElementsId.length === 1 &&
MainStore.getCurrentElementsValues[0]?.type == "rectangle",
fields: [
[colorStyleFrappeControl("Background", "rectangleBackgroundColor", "backgroundColor")],
],
});
MainStore.propertiesPanel.push({
title: "Enable Jinja Parsing",
sectionCondtional: () =>
MainStore.getCurrentElementsId.length === 1 &&
MainStore.getCurrentElementsValues[0].type === "text" &&
!MainStore.getCurrentElementsValues[0].isDynamic,
fields: [
[
{
label: "Render Jinja",
name: "parseJinja",
labelDirection: "column",
condtional: () =>
MainStore.getCurrentElementsId.length === 1 &&
MainStore.getCurrentElementsValues[0].type === "text" &&
!MainStore.getCurrentElementsValues[0].isDynamic,
frappeControl: (ref, name) => {
const MainStore = useMainStore();
makeFeild({
name: name,
ref: ref,
fieldtype: "Select",
requiredData: [MainStore.getCurrentElementsValues[0]],
options: () => [
{ label: "Yes", value: "Yes" },
{ label: "No", value: "No" },
],
formatValue: (object, property, isStyle) => {
if (!object) return;
return object[property] ? "Yes" : "No";
},
onChangeCallback: (value = null) => {
if (value && MainStore.getCurrentElementsValues[0]) {
MainStore.getCurrentElementsValues[0]["parseJinja"] =
value === "Yes";
MainStore.frappeControls[name].$input.blur();
}
},
reactiveObject: () => MainStore.getCurrentElementsValues[0],
propertyName: "parseJinja",
});
},
},
],
],
});
MainStore.propertiesPanel.push({
title: "Text Tool",
sectionCondtional: () => MainStore.activeControl === "text",
fields: [
[
{
label: "Text Control :",
name: "textControlType",
labelDirection: "column",
condtional: () => MainStore.activeControl === "text",
frappeControl: (ref, name) => {
const MainStore = useMainStore();
makeFeild({
name: name,
ref: ref,
fieldtype: "Select",
requiredData: [MainStore],
options: () => [
{ label: "Dynamic Text", value: "dynamic" },
{ label: "Static Text", value: "static" },
],
reactiveObject: MainStore,
propertyName: "textControlType",
});
},
},
],
],
});
MainStore.propertiesPanel.push({
title: "Font Settings",
sectionCondtional: () =>
(MainStore.getCurrentElementsId.length === 1 &&
["text", "table"].indexOf(MainStore.getCurrentElementsValues[0]?.type) != -1) ||
(["table", "text"].indexOf(MainStore.activeControl) != -1 &&
MainStore.getCurrentElementsId.length === 0),
fields: [
[
{
label: "Choose Element :",
name: "textStyleEditMode",
labelDirection: "column",
condtional: () =>
[
MainStore.getCurrentElementsValues[0]?.type,
MainStore.activeControl,
].indexOf("table") == -1,
frappeControl: (ref, name) => {
const MainStore = useMainStore();
makeFeild({
name: name,
ref: ref,
fieldtype: "Select",
requiredData: [MainStore],
options: () => {
if (
("text" == MainStore.getCurrentElementsValues[0]?.type &&
MainStore.getCurrentElementsValues[0]?.isDynamic) ||
("text" == MainStore.activeControl &&
MainStore.textControlType == "dynamic")
)
return [
{ label: "Label Element", value: "label" },
{ label: "Main Element", value: "main" },
];
return [{ label: "Main Element", value: "main" }];
},
reactiveObject: () => {
let styleClass = "staticText";
if (MainStore.textControlType == "dynamic") {
styleClass = "dynamicText";
}
return (
MainStore.getCurrentElementsValues[0] ||
MainStore.globalStyles[styleClass]
);
},
onChangeCallback: (value) => {
if (MainStore.getCurrentElementsValues[0]?.selectedDynamicText) {
if (
MainStore.getCurrentElementsValues[0].styleEditMode ==
"label"
) {
MainStore.getCurrentElementsValues[0].selectedDynamicText.labelStyleEditing = true;
} else {
MainStore.getCurrentElementsValues[0].selectedDynamicText.labelStyleEditing = false;
}
}
},
propertyName: "styleEditMode",
});
},
},
],
[
{
label: "Label Style :",
name: "labelDisplayOptions",
labelDirection: "column",
condtional: () => {
let styleClass = "table";
if (MainStore.activeControl == "text") {
if (MainStore.textControlType == "dynamic") {
styleClass = "dynamicText";
} else {
styleClass = "staticText";
}
}
let curObj =
MainStore.getCurrentElementsValues[0] ||
MainStore.globalStyles[styleClass];
if (
curObj.type == "table" ||
(curObj.type == "text" && curObj.isDynamic)
) {
return true;
}
return false;
},
frappeControl: (ref, name) => {
const MainStore = useMainStore();
makeFeild({
name: name,
ref: ref,
fieldtype: "Select",
requiredData: [MainStore],
options: () => {
return [
{ label: "Inline", value: "standard" },
{ label: "Row", value: "flexDynamicText" },
{ label: "Column", value: "flexDirectionColumn" },
];
},
reactiveObject: () => {
let styleClass = "table";
if (MainStore.activeControl == "text") {
if (MainStore.textControlType == "dynamic") {
styleClass = "dynamicText";
} else {
styleClass = "staticText";
}
}
return (
MainStore.getCurrentElementsValues[0] ||
MainStore.globalStyles[styleClass]
);
},
onChangeCallback: (value) => {
let object = MainStore.getCurrentElementsValues[0];
if (!object) return;
if (object.labelDisplayStyle == "standard") {
object.classes = object.classes.filter(
(cls) =>
["flexDynamicText", "flexDirectionColumn"].indexOf(
cls
) == -1
);
} else if (object.labelDisplayStyle == "flexDynamicText") {
if (object.classes.indexOf("flexDynamicText") == -1) {
object.classes.push("flexDynamicText");
}
object.classes = object.classes.filter(
(cls) => cls != "flexDirectionColumn"
);
} else if (object.labelDisplayStyle == "flexDirectionColumn") {
if (object.classes.indexOf("flexDynamicText") == -1) {
object.classes.push("flexDynamicText");
}
if (object.classes.indexOf("flexDirectionColumn") == -1) {
object.classes.push("flexDirectionColumn");
}
}
},
propertyName: "labelDisplayStyle",
});
},
},
],
[
{
label: "Font",
name: "googleFonts",
isLabelled: true,
labelDirection: "column",
condtional: null,
parentBorderBottom: true,
parentBorderTop: true,
frappeControl: (ref, name) => {
const MainStore = useMainStore();
makeFeild({
name: name,
ref: ref,
fieldtype: "Autocomplete",
requiredData: [MainStore.getGoogleFonts],
options: () => MainStore.getGoogleFonts,
reactiveObject: () => MainStore.getCurrentElementsValues[0],
propertyName: "fontFamily",
isStyle: true,
isFontStyle: true,
onChangeCallback: (value = null) => {
MainStore.currentFonts.indexOf(value) == -1 &&
MainStore.currentFonts.push(value);
if (!MainStore.frappeControls["fontWeight"]) return;
MainStore.frappeControls["fontWeight"].df.options =
MainStore.getGoogleFontWeights(MainStore.getStyleObject(true));
MainStore.frappeControls["fontWeight"].refresh();
if (
MainStore.frappeControls["fontWeight"].df.options.indexOf(
MainStore.frappeControls["fontWeight"].value
) == -1
) {
MainStore.frappeControls["fontWeight"].set_value(400);
MainStore.frappeControls["fontWeight"].refresh();
}
},
});
},
},
{
label: "Weight",
name: "fontWeight",
isLabelled: true,
labelDirection: "column",
condtional: null,
frappeControl: (ref, name) => {
const MainStore = useMainStore();
let styleClass = "table";
if (MainStore.activeControl == "text") {
if (MainStore.textControlType == "dynamic") {
styleClass = "dynamicText";
} else {
styleClass = "staticText";
}
}
makeFeild({
name: name,
ref: ref,
fieldtype: "Select",
requiredData: [
MainStore.getCurrentElementsValues[0] ||
MainStore.globalStyles[styleClass],
],
options: () => {
return MainStore.getGoogleFontWeights(
MainStore.getStyleObject(true)
);
},
reactiveObject: () => MainStore.getCurrentElementsValues[0],
propertyName: "fontWeight",
isStyle: true,
isFontStyle: true,
});
},
},
],
[
styleInputwithIcon("fontSize", 23, {
padding: 5,
saveWithUom: true,
isFontStyle: true,
}),
styleInputwithIcon("lineHeight", 23, {
padding: 5,
isRaw: true,
isFontStyle: true,
}),
],
[
iconControl({
name: "fontItalic",
size: 28,
padding: 8,
margin: 0,
parentBorderTop: true,
parentBorderBottom: true,
condtional: () => {
if (
!MainStore.frappeControls["googleFonts"] ||
!MainStore.frappeControls["fontWeight"]
)
return false;
let isItalicAvaiable =
MainStore.fonts[MainStore.getCurrentStyle("fontFamily")]?.[1].indexOf(
parseInt(MainStore.getCurrentStyle("fontWeight"))
) != -1;
if (
!isItalicAvaiable &&
MainStore.getCurrentStyle("fontStyle") == "italic"
) {
MainStore.getStyleObject(true)["fontStyle"] = "normal";
}
return isItalicAvaiable;
},
onClick: () => {
MainStore.getStyleObject(true)["fontStyle"] =
MainStore.getCurrentStyle("fontStyle") == "italic"
? "normal"
: "italic";
},
isActive: () => MainStore.getCurrentStyle("fontStyle") == "italic",
onlyIcon: true,
flex: "auto",
}),
iconControl({
name: "fontUnderLine",
size: 21,
padding: 4,
margin: 3.5,
parentBorderTop: true,
parentBorderBottom: true,
isActive: () => {
let field = {
reactiveObject: () => MainStore.getCurrentElementsValues[0],
isStyle: true,
isFontStyle: true,
};
return getConditonalObject(field)?.["textDecoration"] == "underline";
},
onClick: () => {
let field = {
reactiveObject: () => MainStore.getCurrentElementsValues[0],
isStyle: true,
isFontStyle: true,
};
getConditonalObject(field)["textDecoration"] =
getConditonalObject(field)?.["textDecoration"] == "underline"
? "none"
: "underline";
},
onlyIcon: true,
flex: "auto",
}),
styleInputwithIcon("letterSpacing", 31, {
padding: 7,
saveWithUom: true,
isFontStyle: true,
flex: 10,
}),
],
[
textAlignIcons("textAlignLeft"),
textAlignIcons("textAlignCenter"),
textAlignIcons("textAlignRight"),
textAlignIcons("textAlignJustify"),
],
[
colorStyleFrappeControl("Text", "textColor", "color", true),
colorStyleFrappeControl(
"Background",
"textBackgroundColor",
"backgroundColor",
true
),
],
],
});
MainStore.propertiesPanel.push({
title: "Border",
sectionCondtional: () => MainStore.getCurrentElementsId.length === 1,
fields: [
[
styleInputwithIcon("borderWidth", 24, {
padding: 6,
margin: 4,
saveWithUom: true,
}),
styleInputwithIcon("borderRadius", 24, {
padding: 7,
margin: 4,
saveWithUom: true,
}),
],
[
borderWidthIcons("borderAll"),
borderWidthIcons("borderLeftStyle"),
borderWidthIcons("borderRightStyle"),
borderWidthIcons("borderTopStyle"),
borderWidthIcons("borderBottomStyle"),
],
{
label: "Border Color",
name: "borderColor",
labelDirection: "column",
isLabelled: true,
condtional: () => {
return parseFloatAndUnit(
getConditonalObject({
reactiveObject: () => MainStore.getCurrentElementsValues[0],
isStyle: true,
property: "borderWidth",
})
).value;
},
frappeControl: (ref, name) => {
makeFeild({
name: name,
ref: ref,
fieldtype: "Color",
requiredData: [MainStore.getCurrentElementsValues[0]],
reactiveObject: () => MainStore.getCurrentElementsValues[0],
propertyName: "borderColor",
isStyle: true,
});
},
},
],
});
MainStore.propertiesPanel.push({
title: "Padding",
sectionCondtional: () =>
MainStore.getCurrentElementsId.length === 1 &&
["text", "image", "table"].indexOf(MainStore.getCurrentElementsValues[0].type) !== -1,
fields: [
[
paddingInput("Top", "paddingTop", "paddingTop"),
paddingInput("Bottom", "paddingBottom", "paddingBottom"),
],
[
paddingInput("Left", "paddingLeft", "paddingLeft"),
paddingInput("Right", "paddingRight", "paddingRight"),
],
],
});
MainStore.propertiesPanel.push({
title: "Barcode Settings",
sectionCondtional: () =>
(!MainStore.getCurrentElementsId.length && MainStore.activeControl === "barcode") ||
(MainStore.getCurrentElementsId.length === 1 &&
MainStore.getCurrentElementsValues[0].type === "barcode"),
fields: [
{
label: "Barcode Format",
name: "barcodeFormat",
isLabelled: true,
condtional: null,
frappeControl: (ref, name) => {
const MainStore = useMainStore();
const { barcodeFormats } = storeToRefs(MainStore);
makeFeild({
name: name,
ref: ref,
fieldtype: "Autocomplete",
requiredData: [
barcodeFormats,
MainStore.getCurrentElementsValues[0] ||
MainStore.globalStyles["barcode"],
],
options: () => barcodeFormats.value,
reactiveObject: () => {
return (
MainStore.getCurrentElementsValues[0] ||
MainStore.globalStyles["barcode"]
);
},
propertyName: "barcodeFormat",
});
},
},
[
colorStyleFrappeControl("Color", "barcodeColor", "barcodeColor", false, false),
colorStyleFrappeControl(
"Background",
"barcodeBackgroundColor",
"barcodeBackgroundColor",
false,
false
),
],
],
});
};
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/PropertiesPanelState.js
|
JavaScript
|
agpl-3.0
| 40,181
|
<template>
<div
:style="[
postionalStyles(startX, startY, width, height),
style.zIndex && { zIndex: style.zIndex },
]"
:ref="setElements(object, index)"
:class="[MainStore.getCurrentElementsId.includes(id) && 'active-elements']"
@mousedown.left="handleMouseDown($event, object)"
@dblclick.stop="handleDblClick($event, object)"
@mouseup="handleMouseUp($event, object)"
>
<div
v-if="barcodeSvg"
:style="[widthHeightStyle(width, height), style]"
:class="['barcode', classes]"
:key="id"
v-html="barcodeSvg"
></div>
<div class="fallback-image" v-else>
<div class="content">
<span v-if="width >= 100 || height >= 100"
>Please Double click to select Barcode</span
>
</div>
</div>
<BaseResizeHandles
v-if="
MainStore.activeControl == 'mouse-pointer' &&
MainStore.getCurrentElementsId.includes(id)
"
/>
</div>
</template>
<script setup>
import { useMainStore } from "../../store/MainStore";
import { toRefs, ref, watch } from "vue";
import { useElement } from "../../composables/Element";
import {
postionalStyles,
setCurrentElement,
lockAxis,
cloneElement,
deleteCurrentElements,
widthHeightStyle,
} from "../../utils";
import { useDraw } from "../../composables/Draw";
import BaseResizeHandles from "./BaseResizeHandles.vue";
const MainStore = useMainStore();
const props = defineProps({
object: {
type: Object,
required: true,
},
index: {
type: Number,
required: true,
},
});
const {
id,
value,
dynamicContent,
barcodeFormat,
barcodeColor,
barcodeBackgroundColor,
startX,
startY,
width,
height,
style,
classes,
} = toRefs(props.object);
const barcodeSvg = ref(null);
watch(
() => dynamicContent.value,
() => {
if (dynamicContent.value) {
value.value = dynamicContent.value[0]?.value || "";
}
},
{ deep: true, immediate: true }
);
const parseJinja = async () => {
if (Object.keys(MainStore.docData).length == 0 || !MainStore.currentDoc) return value.value;
try {
// call render_user_text_withdoc method using frappe.call and return the result
let result = await frappe.call({
method: "print_designer.print_designer.page.print_designer.print_designer.render_user_text_withdoc",
args: {
string: value.value,
doctype: MainStore.doctype,
docname: MainStore.currentDoc,
send_to_jinja: MainStore.mainParsedJinjaData || {},
},
});
result = result.message;
if (result.success) {
return result.message;
} else {
console.error("Error From User Provided Jinja String\n\n", result.error);
}
} catch (error) {
console.error("Error in Jinja Template\n", { value_string: content.value, error });
frappe.show_alert(
{
message: "Unable Render Jinja Template. Please Check Console",
indicator: "red",
},
5
);
return value.value;
}
};
watch(
() => [
value.value,
barcodeFormat.value,
barcodeColor.value,
barcodeBackgroundColor.value,
MainStore.docData,
MainStore.mainParsedJinjaData,
],
async () => {
if (!barcodeFormat.value) return;
try {
const options = {
background: barcodeBackgroundColor.value || "#ffffff",
quiet_zone: 1,
};
if (barcodeFormat.value == "qrcode") {
options["module_color"] = barcodeColor.value || "#000000";
} else {
options["foreground"] = barcodeColor.value || "#000000";
}
let finalValue = value.value;
if (finalValue != "") {
try {
finalValue = await parseJinja();
} catch (error) {
console.error("Error in Jinja Template\n", {
value_string: finalValue,
error,
});
frappe.show_alert(
{
message: "Unable Render Jinja Template. Please Check Console",
indicator: "red",
},
5
);
}
}
let barcode = await frappe.call(
"print_designer.print_designer.page.print_designer.print_designer.get_barcode",
{
barcode_format: barcodeFormat.value,
barcode_value: finalValue,
options,
}
);
barcodeSvg.value = barcode.message.value;
} catch (e) {
barcodeSvg.value = null;
}
},
{ immediate: true }
);
const { setElements } = useElement({
draggable: true,
resizable: true,
});
const { drawEventHandler, parameters } = useDraw();
const handleMouseDown = (e, element = null) => {
e.stopPropagation();
if (MainStore.openModal) return;
lockAxis(element, e.shiftKey);
MainStore.isMoveStart = true;
if (MainStore.activeControl == "mouse-pointer" && e.altKey) {
element && setCurrentElement(e, element);
cloneElement();
} else {
element && setCurrentElement(e, element);
}
MainStore.setActiveControl("MousePointer");
MainStore.currentDrawListener = {
drawEventHandler,
parameters,
};
drawEventHandler.mousedown(e);
};
const handleMouseUp = (e, element = null) => {
if (
MainStore.lastCreatedElement &&
!MainStore.openModal &&
!MainStore.isMoved &&
MainStore.isDrawing
) {
if (!MainStore.modalLocation.isDragged) {
clientX = e.clientX;
clientY = e.clientY;
if (clientX - 250 > 0) clientX = clientX - 250;
if (clientY - 180 > 0) clientY = clientY - 180;
MainStore.modalLocation.x = clientX;
MainStore.modalLocation.y = clientY;
}
MainStore.getCurrentElementsId.forEach((element) => {
delete MainStore.currentElements[element];
});
MainStore.currentElements[MainStore.lastCreatedElement.id] = MainStore.lastCreatedElement;
MainStore.openModal = true;
} else if (
MainStore.lastCloned &&
!MainStore.isMoved &&
MainStore.activeControl == "mouse-pointer"
) {
deleteCurrentElements();
} else {
MainStore.activeControl == "barcode" && (MainStore.openBarcodeModal = element);
}
MainStore.setActiveControl("MousePointer");
MainStore.isMoved = MainStore.isMoveStart = false;
MainStore.lastCloned = null;
};
const handleDblClick = (e, element) => {
element && setCurrentElement(e, element);
MainStore.openBarcodeModal = element;
};
</script>
<style lang="scss" deep>
.fallback-barcode {
width: 100%;
user-select: none;
height: 100%;
display: flex;
overflow: hidden;
align-items: center;
justify-content: center;
background-color: var(--subtle-fg);
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
span {
font-size: smaller;
text-align: center;
}
}
}
</style>
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/components/base/BaseBarcode.vue
|
Vue
|
agpl-3.0
| 6,273
|
<template>
<div
@dblclick.stop="handleDblClick($event, object)"
@mousedown.left="handleMouseDown($event, object)"
@mouseup="handleMouseUp"
:style="[
postionalStyles(startX, startY, width, height),
!isFixedSize && {
width: 'fit-content',
height: 'fit-content',
maxWidth:
MainStore.page.width -
MainStore.page.marginLeft -
MainStore.page.marginRight -
startX +
'px',
},
style.zIndex && { zIndex: style.zIndex },
]"
:class="MainStore.getCurrentElementsId.includes(id) ? 'active-elements' : 'text-hover'"
:ref="setElements(object, index)"
:key="id"
>
<div
:style="[
style,
style.backgroundColor == '' && { backgroundColor: 'transparent' },
widthHeightStyle(width, height),
!isFixedSize && {
width: 'fit-content',
height: 'fit-content',
maxWidth:
MainStore.page.width -
MainStore.page.marginLeft -
MainStore.page.marginRight -
startX +
'px',
},
]"
:class="['dynamicText', classes]"
v-if="type == 'text'"
data-placeholder=""
>
<template
v-for="(field, index) in dynamicContent"
:key="`${field.parentField}${field.fieldname}`"
>
<BaseDynamicTextSpanTag
v-bind="{
field,
labelStyle,
selectedDynamicText,
setSelectedDynamicText,
index,
parentClass: '',
}"
/>
</template>
</div>
<BaseResizeHandles
v-if="
MainStore.activeControl == 'mouse-pointer' &&
MainStore.getCurrentElementsId.includes(id)
"
/>
</div>
</template>
<script setup>
import BaseDynamicTextSpanTag from "./BaseDynamicTextSpanTag.vue";
import BaseResizeHandles from "./BaseResizeHandles.vue";
import { toRefs, onUpdated, watch, onMounted, nextTick } from "vue";
import { useMainStore } from "../../store/MainStore";
import { useElement } from "../../composables/Element";
import { useDraw } from "../../composables/Draw";
import {
postionalStyles,
widthHeightStyle,
setCurrentElement,
lockAxis,
cloneElement,
} from "../../utils";
import { onClickOutside } from "@vueuse/core";
const MainStore = useMainStore();
const props = defineProps({
object: {
type: Object,
required: true,
},
index: {
type: Number,
required: true,
},
});
const {
id,
type,
DOMRef,
isFixedSize,
dynamicContent,
selectedDynamicText,
isDraggable,
isResizable,
startX,
startY,
width,
height,
style,
labelStyle,
styleEditMode,
classes,
} = toRefs(props.object);
const setSelectedDynamicText = (value, isLabel) => {
if (
MainStore.activeControl != "text" ||
MainStore.getCurrentElementsId.indexOf(id.value) == -1
)
return;
if (
selectedDynamicText.value === value &&
styleEditMode.value == (isLabel ? "label" : "main")
) {
selectedDynamicText.value = null;
} else {
selectedDynamicText.value = value;
let removeSelectedText = onClickOutside(DOMRef.value, (event) => {
for (let index = 0; index < event.composedPath().length; index++) {
if (event.composedPath()[index].id === "canvas") {
selectedDynamicText.value = null;
removeSelectedText();
}
}
});
}
styleEditMode.value = isLabel ? "label" : "main";
};
const { setElements } = useElement({
draggable: true,
resizable: true,
});
const { drawEventHandler, parameters } = useDraw();
const toggleDragResize = (toggle) => {
isDraggable.value = toggle;
isResizable.value = toggle;
props.object.contenteditable = !toggle;
};
watch(
() => MainStore.activeControl,
() => {
if (MainStore.activeControl == "text") {
toggleDragResize(false);
} else {
toggleDragResize(true);
}
}
);
const showWarning = frappe.utils.debounce((pageInfoInBody) => {
frappe.show_alert({
message: "Please move <b>" + pageInfoInBody.join(", ") + "</b> to header / footer",
indicator: "orange",
});
}, 500);
// Remove If Becomes Unnecessary Overhead. This will be fine once temparary state is introduced.
watch(
() => [startY.value],
() => {
if (
startY.value + height.value < MainStore.page.headerHeight + MainStore.page.marginTop ||
startY.value >
MainStore.page.height -
MainStore.page.footerHeight -
MainStore.page.marginTop -
MainStore.page.marginBottom
) {
classes.value.splice(classes.value.indexOf("error"), 1);
return;
}
let pageInfoInBody = [];
dynamicContent.value
.filter((el) => ["page", "topage", "date", "time"].indexOf(el.fieldname) != -1)
.forEach((field) => {
pageInfoInBody.push(field.fieldname);
});
if (pageInfoInBody.length) {
if (classes.value.indexOf("error") == -1) {
classes.value.push("error");
}
showWarning(pageInfoInBody);
}
},
{ flush: "post" }
);
const handleMouseDown = (e, element) => {
lockAxis(element, e.shiftKey);
if (MainStore.openModal) return;
MainStore.currentDrawListener = { drawEventHandler, parameters };
element && setCurrentElement(e, element);
if (MainStore.activeControl == "mouse-pointer" && e.altKey) {
cloneElement();
drawEventHandler.mousedown(e);
}
e.stopPropagation();
if (e.target.parentElement === element.DOMRef) {
element.selectedDynamicText = null;
}
};
const handleMouseUp = (e) => {
if (MainStore.activeControl == "mouse-pointer") {
MainStore.currentDrawListener?.drawEventHandler.mouseup(e);
MainStore.isMoved = MainStore.isMoveStart = false;
MainStore.lastCloned = null;
if (MainStore.isDropped) {
MainStore.currentElements = MainStore.isDropped;
MainStore.isDropped = null;
return;
}
}
};
const handleDblClick = (e, element) => {
element && setCurrentElement(e, element);
MainStore.setActiveControl("Text");
MainStore.openDynamicModal = element;
};
onMounted(() => {
selectedDynamicText.value = null;
if (!DOMRef || !!DOMRef.value.firstElementChild.innerText) return;
nextTick(() => {
DOMRef.value.firstElementChild.dataset.placeholder = "Choose Dynamic Field...";
});
});
onUpdated(() => {
if (!isFixedSize.value) {
let targetRect = DOMRef.value.getBoundingClientRect();
width.value = targetRect.width + 2;
height.value = targetRect.height + 2;
}
});
</script>
<style deep lang="scss">
[contenteditable] {
outline: none;
}
p:empty:before {
content: attr(data-placeholder);
}
[contenteditable]:empty:focus:before {
content: "";
}
.error {
color: var(--red-500) !important;
border: 1px solid var(--red-500) !important;
}
.text-hover:hover {
box-sizing: border-box !important;
border-bottom: 1px solid var(--primary-color) !important;
}
.flexDynamicText {
.baseSpanTag {
display: flex;
.labelSpanTag {
flex: 1;
}
.valueSpanTag {
flex: 2;
}
}
}
.flexDirectionColumn {
.baseSpanTag {
flex-direction: column;
}
}
</style>
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/components/base/BaseDynamicText.vue
|
Vue
|
agpl-3.0
| 6,644
|
<template>
<span :class="{ baseSpanTag: !field.is_static && field.is_labelled }">
<span
v-if="!field.is_static && field.is_labelled"
:class="[
parentClass,
'label-text',
'labelSpanTag',
{
'dynamic-span-hover':
parentClass == 'printTable' ? true : MainStore.activeControl == 'text',
'dynamic-span-selected':
selectedDynamicText === field && field?.labelStyleEditing,
},
]"
@click="selectDynamicText(true)"
:style="[labelStyle, field?.labelStyle]"
v-html="
field.label ||
`{{ ${field.parentField ? field.parentField + '.' : ''}${field.fieldname} }}`
"
></span>
<span
:class="[
parentClass,
'dynamic-span',
{
'dynamic-span-hover':
parentClass == 'printTable' ? true : MainStore.activeControl == 'text',
'dynamic-span-selected':
selectedDynamicText === field && !field.labelStyleEditing,
},
{ valueSpanTag: !field.is_static && field.is_labelled },
getPageClass(field),
]"
@click="selectDynamicText()"
:style="[field?.style]"
v-html="parsedValue"
>
</span>
<span
v-if="field.suffix"
:class="[
parentClass,
'dynamic-span',
{
'dynamic-span-hover':
parentClass == 'printTable' ? true : MainStore.activeControl == 'text',
'dynamic-span-selected':
selectedDynamicText === field && !field.labelStyleEditing,
},
]"
@click="selectDynamicText()"
:style="[field?.style]"
v-html="field.suffix"
>
</span>
<br v-if="field.nextLine" />
</span>
</template>
<script setup>
import { useMainStore } from "../../store/MainStore";
import { ref, watch, onMounted } from "vue";
import { getFormattedValue } from "../../utils";
const selectDynamicText = (isLabel = false) => {
props.field.labelStyleEditing = isLabel;
props.setSelectedDynamicText(props.field, isLabel);
};
const MainStore = useMainStore();
const props = defineProps({
field: {
type: Object,
required: true,
},
labelStyle: {
type: Object,
required: true,
},
selectedDynamicText: {
type: Object,
required: false,
},
setSelectedDynamicText: {
type: Function,
required: true,
},
index: {
type: Number,
required: true,
},
parentClass: {
type: String,
required: true,
},
table: {
type: Object,
default: null,
},
});
const parsedValue = ref("");
const row = ref(null);
onMounted(() => {
watch(
() => [MainStore.docData],
async () => {
if (Object.keys(MainStore.docData).length == 0) return;
if (props.table) {
row.value = MainStore.docData[props.table.fieldname]?.[props.index - 1];
}
},
{ immediate: true, deep: true }
);
});
watch(
() => [
props.field.value,
props.field.parseJinja,
MainStore.docData,
MainStore.mainParsedJinjaData,
row.value,
],
async () => {
parsedValue.value = await getFormattedValue(props.field, row);
},
{ immediate: true, deep: true }
);
const getPageClass = (field) => {
if (["page", "frompage", "time", "date"].indexOf(field.fieldname) == -1) return "";
return `page_info_${field.fieldname}`;
};
</script>
<style lang="scss" scoped>
.dynamic-span {
padding: 1px !important;
}
.dynamic-span-hover:hover:not(.dynamic-span-selected) {
border-bottom: 1px solid var(--gray-600) !important;
cursor: default;
}
.dynamic-span-selected {
border-bottom: 1px solid var(--primary-color) !important;
}
</style>
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/components/base/BaseDynamicTextSpanTag.vue
|
Vue
|
agpl-3.0
| 3,364
|
<template>
<div
:style="[
postionalStyles(startX, startY, width, height),
{ padding: '1px' },
style.zIndex && { zIndex: style.zIndex },
]"
:ref="setElements(object, index)"
:class="[MainStore.getCurrentElementsId.includes(id) && 'active-elements']"
@mousedown.left="handleMouseDown($event, object)"
@dblclick.stop="handleDblClick($event, object)"
@mouseup="handleMouseUp($event, object)"
>
<div
v-if="isDynamic ? image && Boolean(image.value) : image && Boolean(image.file_url)"
:style="[
widthHeightStyle(width, height),
style,
style.backgroundColor == '' && { backgroundColor: 'transparent' },
`background-image: url('${isDynamic ? image.value : image.file_url}');`,
]"
:class="['image', classes]"
:key="id"
></div>
<div class="fallback-image" v-else>
<div class="content">
<IconsUse
v-if="width >= 30 || height >= 30"
:draggable="false"
:size="18"
name="es-line-image-alt1"
key="es-line-image-alt1"
/>
<span
v-if="
(width >= 120 || height >= 120) && isDynamic
? image && !Boolean(image.value)
: image && !Boolean(image.file_url)
"
>{{ isDynamic ? "Image not Linked" : "Unable to load Image :(" }}</span
>
<span v-else-if="width >= 120 || height >= 120"
>Please Double click to select Image</span
>
</div>
</div>
<BaseResizeHandles
v-if="
MainStore.activeControl == 'mouse-pointer' &&
MainStore.getCurrentElementsId.includes(id)
"
/>
</div>
</template>
<script setup>
import { useMainStore } from "../../store/MainStore";
import { toRefs } from "vue";
import { useElement } from "../../composables/Element";
import {
postionalStyles,
setCurrentElement,
lockAxis,
cloneElement,
deleteCurrentElements,
widthHeightStyle,
} from "../../utils";
import { useDraw } from "../../composables/Draw";
import BaseResizeHandles from "./BaseResizeHandles.vue";
import IconsUse from "../../icons/IconsUse.vue";
const MainStore = useMainStore();
const props = defineProps({
object: {
type: Object,
required: true,
},
index: {
type: Number,
required: true,
},
});
const { id, image, isDynamic, startX, startY, width, height, style, classes } = toRefs(
props.object
);
const { setElements } = useElement({
draggable: true,
resizable: true,
});
const { drawEventHandler, parameters } = useDraw();
const handleMouseDown = (e, element = null) => {
e.stopPropagation();
if (MainStore.openModal) return;
lockAxis(element, e.shiftKey);
MainStore.isMoveStart = true;
if (MainStore.activeControl == "mouse-pointer" && e.altKey) {
element && setCurrentElement(e, element);
cloneElement();
} else {
element && setCurrentElement(e, element);
}
MainStore.setActiveControl("MousePointer");
MainStore.currentDrawListener = {
drawEventHandler,
parameters,
};
};
const handleMouseUp = (e, element = null) => {
if (
e.target.classList.contains("resize-handle")
? e.target.parentElement !== element.DOMRef
: e.target !== element.DOMRef
)
return;
if (
MainStore.lastCreatedElement &&
!MainStore.openModal &&
!MainStore.isMoved &&
MainStore.isDrawing
) {
if (!MainStore.modalLocation.isDragged) {
clientX = e.clientX;
clientY = e.clientY;
if (clientX - 250 > 0) clientX = clientX - 250;
if (clientY - 180 > 0) clientY = clientY - 180;
MainStore.modalLocation.x = clientX;
MainStore.modalLocation.y = clientY;
}
MainStore.getCurrentElementsId.forEach((element) => {
delete MainStore.currentElements[element];
});
MainStore.currentElements[MainStore.lastCreatedElement.id] = MainStore.lastCreatedElement;
MainStore.openModal = true;
} else if (
MainStore.lastCloned &&
!MainStore.isMoved &&
MainStore.activeControl == "mouse-pointer"
) {
deleteCurrentElements();
} else {
MainStore.activeControl == "image" && (MainStore.openImageModal = element);
}
MainStore.setActiveControl("MousePointer");
MainStore.isMoved = MainStore.isMoveStart = false;
MainStore.lastCloned = null;
};
const handleDblClick = (e, element) => {
element && setCurrentElement(e, element);
MainStore.openImageModal = element;
};
</script>
<style lang="scss" scoped>
.fallback-image {
width: 100%;
user-select: none;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background-color: var(--gray-100);
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
span {
font-size: smaller;
text-align: center;
}
}
}
</style>
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/components/base/BaseImage.vue
|
Vue
|
agpl-3.0
| 4,558
|
<template>
<div
class="header-footer-overlay"
:style="[postionalStyles(startX, startY, width, height), 'width: 100%']"
v-if="elementType && ['header', 'footer'].includes(elementType)"
@dblclick="(e) => editHeaderFooter(e, elementType)"
>
<p>{{ `Double Click to edit ${elementType}` }}</p>
</div>
<div
:style="[
style,
style.backgroundColor == '' && { backgroundColor: 'transparent' },
postionalStyles(startX, startY, width, height),
elementType && ['header', 'footer'].includes(elementType) && 'width: 100%',
]"
:class="[
'rectangle',
{ 'active-elements': MainStore.getCurrentElementsId.includes(id) },
classes,
]"
:ref="setElements(object, index)"
@mousedown.left.stop="handleMouseDown($event, object, index)"
@mouseup.left="handleMouseUp($event, object, index)"
>
<BaseResizeHandles
v-if="
MainStore.activeControl == 'mouse-pointer' &&
MainStore.getCurrentElementsId.includes(id)
"
/>
<template v-for="(object, index) in object.childrens" :key="object.id">
<component
:is="
object.type == 'text'
? isComponent[object.type][object.isDynamic ? 'dynamic' : 'static']
: isComponent[object.type]
"
v-bind="{ object, index }"
>
</component>
</template>
</div>
</template>
<script setup>
import BaseStaticText from "./BaseStaticText.vue";
import BaseDynamicText from "./BaseDynamicText.vue";
import BaseImage from "./BaseImage.vue";
import BaseTable from "./BaseTable.vue";
import BaseBarcode from "./BaseBarcode.vue";
import BaseResizeHandles from "./BaseResizeHandles.vue";
import { toRefs } from "vue";
import { useMainStore } from "../../store/MainStore";
import { useElementStore } from "../../store/ElementStore";
import { useElement } from "../../composables/Element";
import { useDraw } from "../../composables/Draw";
import {
setCurrentElement,
cloneElement,
deleteCurrentElements,
lockAxis,
postionalStyles,
updateDynamicData,
} from "../../utils";
const props = defineProps({
object: {
type: Object,
required: true,
},
index: {
type: Number,
required: true,
},
});
const isComponent = Object.freeze({
rectangle: "BaseRectangle",
text: {
static: BaseStaticText,
dynamic: BaseDynamicText,
},
image: BaseImage,
table: BaseTable,
barcode: BaseBarcode,
});
const { id, startX, startY, width, height, style, classes, elementType } = toRefs(props.object);
const ElementStore = useElementStore();
const MainStore = useMainStore();
const { setElements } = useElement({
draggable: true,
resizable: true,
});
const { drawEventHandler, parameters } = useDraw();
const handleMouseDown = (e, element = null, index) => {
if (MainStore.openModal) return;
lockAxis(element, e.shiftKey);
MainStore.isMoveStart = true;
if (MainStore.activeControl == "mouse-pointer" && e.altKey) {
element && setCurrentElement(e, element);
cloneElement();
drawEventHandler.mousedown(e);
} else {
if (MainStore.isDrawing) {
const newElement = ElementStore.createNewObject(
{
startX: e.offsetX,
startY: e.offsetY,
pageX: e.x,
pageY: e.y,
},
element
);
drawEventHandler.mousedown({
startX: e.offsetX,
startY: e.offsetY,
clientX: e.clientX,
clientY: e.clientY,
});
newElement && setCurrentElement(e, newElement);
} else if (MainStore.activeControl == "text") {
if (MainStore.getCurrentElementsId.length) {
MainStore.getCurrentElementsId.forEach((element) => {
delete MainStore.currentElements[element];
});
} else {
const newElement = ElementStore.createNewObject(
{
startX: e.offsetX,
startY: e.offsetY,
pageX: e.x,
pageY: e.y,
},
element
);
newElement && setCurrentElement(e, newElement);
if (MainStore.textControlType == "dynamic") {
MainStore.openDynamicModal = newElement;
}
}
} else {
element && setCurrentElement(e, element);
}
}
MainStore.currentDrawListener = {
drawEventHandler,
parameters,
restrict: {
top: startY.value - e.target.offsetTop - 1,
bottom: startY.value + height.value - e.target.offsetTop - 1,
left: startX.value - e.target.offsetLeft - 1,
right: startX.value + width.value - e.target.offsetLeft - 1,
},
};
};
const handleMouseUp = (e, element = null, index) => {
if (
e.target.classList.contains("resize-handle")
? e.target.parentElement !== element.DOMRef
: e.target !== element.DOMRef
)
return;
if (MainStore.isDropped) {
MainStore.currentElements = MainStore.isDropped;
MainStore.isDropped = null;
MainStore.isMoved = MainStore.isMoveStart = false;
MainStore.lastCloned = null;
return;
}
if (
!MainStore.openModal &&
!MainStore.isMoved &&
MainStore.activeControl == "mouse-pointer" &&
e.target == element.DOMRef
) {
element && setCurrentElement(e, element);
}
if (
MainStore.lastCreatedElement &&
!MainStore.openModal &&
!MainStore.isMoved &&
MainStore.isDrawing
) {
if (!MainStore.modalLocation.isDragged) {
clientX = e.clientX;
clientY = e.clientY;
if (clientX - 250 > 0) clientX = clientX - 250;
if (clientY - 180 > 0) clientY = clientY - 180;
MainStore.modalLocation.x = clientX;
MainStore.modalLocation.y = clientY;
}
MainStore.getCurrentElementsId.forEach((element) => {
delete MainStore.currentElements[element];
});
MainStore.currentElements[MainStore.lastCreatedElement.id] = MainStore.lastCreatedElement;
MainStore.openModal = true;
} else if (
MainStore.lastCloned &&
!MainStore.isMoved &&
MainStore.activeControl == "mouse-pointer"
) {
deleteCurrentElements();
} else {
MainStore.currentDrawListener?.drawEventHandler.mouseup(e);
}
MainStore.isMoved = MainStore.isMoveStart = false;
MainStore.lastCloned = null;
};
const editHeaderFooter = (e, mode) => {
MainStore.mode = mode;
let RawObject = [];
let object;
if (mode == "header") {
ElementStore.HeadersRawObject = RawObject;
object = [...ElementStore.Headers];
} else {
ElementStore.FootersRawObject = RawObject;
object = [...ElementStore.Footers];
}
ElementStore.Elements.map((el) => delete el.header);
ElementStore.Elements.map((el) => delete el.footer);
ElementStore.ElementsRawObject = [
...ElementStore.Elements.map((el) => ElementStore.childrensSave(el)),
];
RawObject.push(...object.map((el) => ElementStore.childrensSave(el)));
ElementStore.Elements.length = 0;
ElementStore.Elements.push(
...object.map((el) => ElementStore.childrensLoad(el, ElementStore.Elements))
);
updateDynamicData();
};
</script>
<script>
export default {
name: "BaseRectangle",
};
</script>
<style lang="scss" scoped>
.header-footer-overlay {
position: absolute;
display: flex;
justify-content: center;
align-items: center;
background-color: transparent;
z-index: 1000;
p {
display: none;
}
}
.header-footer-overlay:hover {
background-color: var(--subtle-accent);
opacity: 0.85;
cursor: pointer;
p {
display: block;
}
outline: 1px solid var(--primary) !important;
}
</style>
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/components/base/BaseRectangle.vue
|
Vue
|
agpl-3.0
| 7,004
|
<template>
<div class="resize-handle top-left resize-top resize-left"></div>
<div class="resize-handle top-right resize-top resize-right"></div>
<div class="resize-handle top-middle resize-top"></div>
<div class="resize-handle left-middle resize-left"></div>
<div class="resize-handle right-middle resize-right"></div>
<div class="resize-handle bottom-left resize-bottom resize-left"></div>
<div class="resize-handle bottom-middle resize-bottom"></div>
<div class="resize-handle bottom-right resize-bottom resize-right"></div>
</template>
<script setup></script>
<style lang="scss" scoped>
.resize-handle {
width: 6px;
height: 6px;
background: white;
border: 1px solid var(--primary-color);
position: absolute;
z-index: 9999;
}
.top-left {
left: -4px;
top: -4px;
cursor: nwse-resize;
}
.top-middle {
top: -4px;
left: calc(50% - 3px);
cursor: ns-resize;
}
.top-right {
right: -4px;
top: -4px;
cursor: nesw-resize;
}
.right-middle {
right: -4px;
top: calc(50% - 3px);
cursor: ew-resize;
}
.left-middle {
left: -4px;
top: calc(50% - 3px);
cursor: ew-resize;
}
.bottom-middle {
bottom: -4px;
left: calc(50% - 3px);
cursor: ns-resize;
}
.bottom-left {
left: -4px;
bottom: -4px;
cursor: nesw-resize;
}
.bottom-right {
right: -4px;
bottom: -4px;
cursor: nwse-resize;
}
</style>
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/components/base/BaseResizeHandles.vue
|
Vue
|
agpl-3.0
| 1,311
|
<template>
<div
@dblclick.stop="handleDblClick($event, object, index)"
@mousedown.left="handleMouseDown($event, object, index)"
@mouseup="handleMouseUp"
:style="[
postionalStyles(startX, startY, width, height),
!isFixedSize && {
width: 'fit-content',
height: 'fit-content',
maxWidth:
MainStore.page.width -
MainStore.page.marginLeft -
MainStore.page.marginRight -
startX +
'px',
},
style.zIndex && { zIndex: style.zIndex },
]"
:class="MainStore.getCurrentElementsId.includes(id) ? 'active-elements' : 'text-hover'"
:ref="setElements(object, index)"
:key="id"
>
<p
:contenteditable="contenteditable"
@keydown.stop="handleKeyDown"
@focus="handleFocus"
@blur="handleBlur"
@keyup.stop
:style="[
style,
style.backgroundColor == '' && { backgroundColor: 'transparent' },
widthHeightStyle(width, height),
!isFixedSize && {
width: 'fit-content',
height: 'fit-content',
maxWidth:
MainStore.page.width -
MainStore.page.marginLeft -
MainStore.page.marginRight -
startX +
'px',
},
]"
:class="['staticText', classes]"
v-if="type == 'text'"
data-placeholder=""
v-html="parsedValue"
></p>
<BaseResizeHandles
v-if="!contenteditable && MainStore.getCurrentElementsId.includes(id)"
/>
</div>
</template>
<script setup>
import BaseResizeHandles from "./BaseResizeHandles.vue";
import { toRefs, watch, onMounted, onUpdated, ref } from "vue";
import { useMainStore } from "../../store/MainStore";
import { useElement } from "../../composables/Element";
import { useDraw } from "../../composables/Draw";
import {
postionalStyles,
setCurrentElement,
lockAxis,
cloneElement,
widthHeightStyle,
deleteCurrentElements,
} from "../../utils";
const MainStore = useMainStore();
const props = defineProps({
object: {
type: Object,
required: true,
},
index: {
type: Number,
required: true,
},
});
const {
id,
type,
DOMRef,
content,
contenteditable,
isFixedSize,
isDraggable,
isResizable,
startX,
startY,
width,
height,
style,
classes,
parseJinja,
} = toRefs(props.object);
const parsedValue = ref("");
const { setElements } = useElement({
draggable: true,
resizable: true,
});
const { drawEventHandler, parameters } = useDraw();
watch(
() => [
contenteditable.value,
content.value,
parseJinja.value,
MainStore.docData,
MainStore.mainParsedJinjaData,
],
async () => {
if (
!contenteditable.value &&
content.value != "" &&
parseJinja.value &&
Object.keys(MainStore.docData).length > 0
) {
try {
// call render_user_text_withdoc method using frappe.call and return the result
const MainStore = useMainStore();
let result = await frappe.call({
method: "print_designer.print_designer.page.print_designer.print_designer.render_user_text_withdoc",
args: {
string: content.value,
doctype: MainStore.doctype,
docname: MainStore.currentDoc,
send_to_jinja: MainStore.mainParsedJinjaData || {},
},
});
result = result.message;
if (result.success) {
parsedValue.value = result.message;
} else {
console.error("Error From User Provided Jinja String\n\n", result.error);
}
} catch (error) {
console.error("Error in Jinja Template\n", { value_string: content.value, error });
frappe.show_alert(
{
message: "Unable Render Jinja Template. Please Check Console",
indicator: "red",
},
5
);
parsedValue.value = content.value;
}
} else {
parsedValue.value = content.value;
}
},
{ immediate: true, deep: true }
);
const handleMouseDown = (e, element) => {
lockAxis(element, e.shiftKey);
if (MainStore.openModal) return;
MainStore.currentDrawListener = { drawEventHandler, parameters };
element && setCurrentElement(e, element);
if (MainStore.activeControl == "mouse-pointer" && e.altKey) {
element && setCurrentElement(e, element);
cloneElement();
drawEventHandler.mousedown(e);
}
e.stopPropagation();
};
const handleMouseUp = (e) => {
if (MainStore.activeControl == "mouse-pointer") {
MainStore.currentDrawListener?.drawEventHandler.mouseup(e);
MainStore.isMoved = MainStore.isMoveStart = false;
MainStore.lastCloned = null;
if (MainStore.isDropped) {
MainStore.currentElements = MainStore.isDropped;
MainStore.isDropped = null;
return;
}
}
};
const handleDblClick = (e, element, index) => {
element && setCurrentElement(e, element);
contenteditable.value = true;
isDraggable.value = false;
isResizable.value = false;
MainStore.setActiveControl("Text");
setTimeout(function () {
DOMRef.value.firstElementChild.focus();
}, 0);
};
onMounted(() => {
if (!DOMRef || !!DOMRef.value.firstElementChild.innerText) return;
setTimeout(function () {
DOMRef.value.firstElementChild.focus();
DOMRef.value.firstElementChild.dataset.placeholder = "Type Something...";
}, 0);
});
onUpdated(() => {
if (!isFixedSize.value && DOMRef) {
let targetRect = DOMRef.value.getBoundingClientRect();
width.value = targetRect.width + 2;
height.value = targetRect.height + 2;
}
});
const handleBlur = (e) => {
let targetRect = e.target.getBoundingClientRect();
if (!isFixedSize.value) {
width.value = targetRect.width + 2;
height.value = targetRect.height + 2;
}
content.value = DOMRef.value.firstElementChild.innerText; // This will break styled texts :(
MainStore.getCurrentElementsId.includes(id.value) &&
DOMRef.value.classList.add("active-elements");
contenteditable.value = false;
};
const handleKeyDown = (e) => {
if (e.key == "Tab") {
handleBlur(e);
e.target.blur();
e.preventDefault();
} else if (e.key == "Escape") {
handleBlur(e);
e.target.blur();
}
};
const handleFocus = (e) => {
DOMRef.value.classList.remove("active-elements");
};
</script>
<style scoped>
[contenteditable] {
outline: none;
min-width: 1px;
}
[contenteditable]:empty:before {
content: attr(data-placeholder);
}
[contenteditable]:empty:focus:before {
content: "";
}
</style>
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/components/base/BaseStaticText.vue
|
Vue
|
agpl-3.0
| 6,057
|
<template>
<div
:ref="setElements(object, index)"
@mousedown.left="handleMouseDown($event, object)"
@mouseup="handleMouseUp($event, width)"
@mousemove="mouseMoveHandler($event, width)"
@mouseleave="mouseLeaveHandler(width)"
:style="[
postionalStyles(startX, startY, width, height),
style.zIndex && { zIndex: style.zIndex },
]"
:class="[
'table-container',
classes,
MainStore.getCurrentElementsId.includes(id) && 'active-elements',
]"
>
<div
:style="['overflow: hidden;', widthHeightStyle(width, height)]"
@click.self="
() => {
selectedColumn = null;
selectedDynamicText = null;
}
"
>
<table class="printTable">
<thead>
<tr v-if="columns.length">
<th
:style="[
'cursor: pointer;',
column.width && {
width: `${column.width}%`,
maxWidth: `${column.width}%`,
},
headerStyle,
column.applyStyleToHeader && column.style,
]"
v-for="(column, index) in columns"
:class="
(menu?.index == index || column == selectedColumn) &&
'current-column'
"
:key="column.fieldname"
:draggable="columnDragging"
@dragstart="dragstart($event, index)"
@drop="drop($event, index)"
@dragleave="dragleave"
@dragover="allowDrop"
@contextmenu.prevent="handleMenu($event, index)"
@mousedown="handleColumnClick(column)"
@dblclick.stop="handleDblClick(table, column)"
:ref="
(el) => {
column.DOMRef = el;
}
"
>
<span :class="{ emptyColumnHead: !Boolean(column.label.length) }">{{
column?.label
}}</span>
<div
class="resizer"
draggable="false"
:ref="
(el) => {
column.DOMRef = el;
}
"
@mousedown.left="mouseDownHandler($event, column)"
@mouseup.left="mouseUpHandler"
:style="{
height: DOMRef
? DOMRef.firstChild.getBoundingClientRect().height + 'px'
: '100%',
}"
></div>
</th>
</tr>
</thead>
<tbody>
<tr
v-if="columns.length"
v-for="row in MainStore.docData[table?.fieldname]?.slice(
0,
PreviewRowNo || 3
) || [{}]"
:key="row.idx"
>
<BaseTableTd
v-bind="{
row,
columns,
style,
labelStyle,
selectedDynamicText,
setSelectedDynamicText,
table,
altStyle,
}"
/>
</tr>
</tbody>
</table>
</div>
<BaseResizeHandles
v-if="
MainStore.activeControl == 'mouse-pointer' &&
MainStore.getCurrentElementsId.includes(id)
"
/>
<AppTableContextMenu v-if="menu" v-bind="{ menu }" @handleMenuClick="handleMenuClick" />
</div>
</template>
<script setup>
import { useMainStore } from "../../store/MainStore";
import { useElement } from "../../composables/Element";
import {
postionalStyles,
setCurrentElement,
lockAxis,
cloneElement,
deleteCurrentElements,
widthHeightStyle,
} from "../../utils";
import { toRefs, ref, watch } from "vue";
import { useDraw } from "../../composables/Draw";
import BaseResizeHandles from "./BaseResizeHandles.vue";
import AppTableContextMenu from "../layout/AppTableContextMenu.vue";
import BaseTableTd from "./BaseTableTd.vue";
import { onClickOutside } from "@vueuse/core";
const MainStore = useMainStore();
const props = defineProps({
object: {
type: Object,
required: true,
},
index: {
type: Number,
required: true,
},
});
const isResizeOn = ref(false);
const currentColumn = ref(null);
const columnDragging = ref(true);
const draggableEl = ref(-1);
const menu = ref(null);
const {
id,
table,
columns,
startX,
startY,
width,
height,
style,
labelStyle,
headerStyle,
altStyle,
classes,
PreviewRowNo,
styleEditMode,
selectedColumn,
selectedDynamicText,
DOMRef,
} = toRefs(props.object);
watch(
() => selectedColumn.value,
(value) => {
if (value) {
MainStore.frappeControls.applyStyleToHeader?.set_value(value.applyStyleToHeader);
}
}
);
const setSelectedDynamicText = (value, isLabel) => {
if (
selectedDynamicText.value === value &&
styleEditMode.value == (isLabel ? "label" : "main")
) {
selectedDynamicText.value = null;
} else {
selectedDynamicText.value = value;
selectedColumn.value = null;
let removeSelectedText = onClickOutside(DOMRef.value, (event) => {
for (let index = 0; index < event.composedPath().length; index++) {
if (event.composedPath()[index].id === "canvas") {
selectedDynamicText.value = null;
removeSelectedText();
}
}
});
}
styleEditMode.value = isLabel ? "label" : "main";
};
const handleColumnClick = (column) => {
if (!props.object.table) {
MainStore.frappeControls.table.set_focus();
} else if (MainStore.activeControl == "mouse-pointer") {
selectedColumn.value = column;
MainStore.frappeControls.tableStyleEditMode?.set_value("main");
selectedDynamicText.value = null;
let removeSelectedColumn = onClickOutside(DOMRef.value, (event) => {
for (let index = 0; index < event.composedPath().length; index++) {
if (event.composedPath()[index].id === "canvas") {
selectedColumn.value = null;
removeSelectedColumn();
}
}
});
}
};
const handleDblClick = (table, column) => {
if (!props.object.table) {
MainStore.frappeControls.table.set_focus();
MainStore.frappeControls.table.$input.one("blur", () => {
MainStore.openTableColumnModal = {
table: MainStore.getCurrentElementsValues[0]?.table,
column,
};
});
} else {
MainStore.openTableColumnModal = { table, column };
}
};
const handleMenuClick = (index, action) => {
switch (action) {
case "before":
columns.value.splice(index, 0, {
id: index,
label: "",
style: {},
applyStyleToHeader: false,
});
break;
case "after":
columns.value.splice(index + 1, 0, {
id: index + 1,
label: "",
style: {},
applyStyleToHeader: false,
});
break;
case "delete":
columns.value.splice(index, 1)[0].dynamicContent?.forEach((el) => {
MainStore.dynamicData.splice(MainStore.dynamicData.indexOf(el), 1);
});
break;
}
columns.value.forEach((element, index) => {
element.id = index;
});
menu.value.index = null;
};
const { setElements } = useElement({
draggable: true,
resizable: true,
});
const handleMenu = (e, index) => {
if (!menu.value) {
menu.value = {
left: e.x - DOMRef.value.getBoundingClientRect().x + "px",
top: e.y - DOMRef.value.getBoundingClientRect().y + "px",
index: index,
};
} else {
menu.value.left = e.x - DOMRef.value.getBoundingClientRect().x + "px";
menu.value.top = e.y - DOMRef.value.getBoundingClientRect().y + "px";
menu.value.index = index;
}
};
const dragstart = (ev, index) => {
draggableEl.value = index;
ev.dataTransfer.dropEffect = "move";
};
const dragleave = (ev) => {
ev.target.classList.remove("dropzone");
};
const allowDrop = (ev) => {
ev.dataTransfer.dropEffect = "move";
ev.target.classList.add("dropzone");
ev.preventDefault();
};
const drop = (ev, index) => {
ev.target.classList.remove("dropzone");
columns.value.splice(index, 0, columns.value.splice(draggableEl.value, 1)[0]);
columns.value.forEach((element, index) => {
element.id = index;
});
ev.preventDefault();
draggableEl.value = null;
};
const mouseDownHandler = (e, column) => {
column.x = e.clientX;
columnDragging.value = false;
isResizeOn.value = true;
column.DOMRef = e.target;
!currentColumn.value && (currentColumn.value = column);
column.DOMRef.classList.add("resizer-active");
column.w = e.target.parentElement.getBoundingClientRect().width;
DOMRef.value.style.cursor = "col-resize";
};
const mouseLeaveHandler = (tablewidth) => {
if (isResizeOn.value) {
columns.value.forEach((column) => {
column.width = (column.DOMRef.getBoundingClientRect().width * 100) / tablewidth;
});
}
if (currentColumn.value) {
document.querySelector(".resizer-active").classList.remove("resizer-active");
columnDragging.value = true;
currentColumn.value = null;
isResizeOn.value = false;
DOMRef.value.style.cursor = "";
}
};
const mouseMoveHandler = (e, tablewidth) => {
if (!isResizeOn.value || !currentColumn.value) return;
const dx = e.clientX - currentColumn.value.x;
const newWidth = dx + currentColumn.value.w;
currentColumn.value.width = (newWidth * 100) / tablewidth;
if (currentColumn.value.width < 2) {
currentColumn.value.width = 2;
}
};
const { drawEventHandler, parameters } = useDraw();
const handleMouseDown = (e, element = null) => {
MainStore.setActiveControl("MousePointer");
lockAxis(element, e.shiftKey);
e.stopPropagation();
MainStore.isMoveStart = true;
if (e.altKey) {
element && setCurrentElement(e, element);
cloneElement();
} else {
element && setCurrentElement(e, element);
}
drawEventHandler.mousedown(e);
MainStore.currentDrawListener = { drawEventHandler, parameters };
e.stopPropagation();
};
const handleMouseUp = (e, tablewidth) => {
if (currentColumn.value) {
document.querySelector(".resizer-active").classList.remove("resizer-active");
currentColumn.value = null;
isResizeOn.value = false;
DOMRef.value.style.cursor = "";
}
columnDragging.value = true;
if (MainStore.lastCloned && !MainStore.isMoved && MainStore.activeControl == "mouse-pointer") {
deleteCurrentElements();
}
MainStore.currentDrawListener?.drawEventHandler.mouseup(e);
MainStore.setActiveControl("MousePointer");
MainStore.isMoved = MainStore.isMoveStart = false;
MainStore.lastCloned = null;
if (MainStore.frappeControls.table?.get_value() == "") {
MainStore.frappeControls.table.set_focus();
}
};
</script>
<style lang="scss" scoped>
.emptyColumnHead::after {
content: "Select Field";
}
.dropzone {
background-color: var(--gray-300);
}
.table-container {
background-color: var(--gray-50);
.printTable {
border-collapse: collapse;
box-sizing: border-box;
border-spacing: 0px;
width: 100%;
overflow: hidden;
tr:first-child th {
border-top-style: solid !important;
}
tr th:first-child {
border-left-style: solid !important;
}
tr th:last-child {
border-right-style: solid !important;
}
.current-column {
outline: 1.5px solid var(--primary-color);
outline-offset: -1.5px;
}
}
th {
position: relative;
}
.resizer {
position: absolute;
top: 0;
right: 0;
width: 5px;
cursor: col-resize;
user-select: none;
border-right: 1px solid transparent;
}
}
.resizer:hover,
.resizer-active,
.resizing {
border-right: 2px solid var(--primary-color);
}
[contenteditable] {
outline: none;
}
[contenteditable]:empty:before {
content: attr(data-placeholder);
}
[contenteditable]:empty:focus:before {
content: "";
}
.text-hover:hover {
box-sizing: border-box !important;
border-bottom: 1px solid var(--primary-color) !important;
}
</style>
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/components/base/BaseTable.vue
|
Vue
|
agpl-3.0
| 10,910
|
<template>
<td
v-for="column in columns"
:key="column.fieldname"
:style="[style, altStyle && row.idx % 2 == 0 && altStyle, column.style]"
@click.self="setSelectedDynamicText(null)"
>
<template
v-for="field in column?.dynamicContent"
:key="`${field?.parentField}${field?.fieldname}`"
>
<BaseDynamicTextSpanTag
v-bind="{
field,
labelStyle,
index: row.idx,
selectedDynamicText,
setSelectedDynamicText,
parentClass: 'printTable',
table,
}"
/>
</template>
</td>
</template>
<script setup>
import BaseDynamicTextSpanTag from "./BaseDynamicTextSpanTag.vue";
const props = defineProps({
table: {
type: Object,
required: true,
},
row: {
type: Object,
required: true,
},
columns: {
type: Object,
required: true,
},
style: {
type: Object,
required: true,
},
labelStyle: {
type: Object,
required: true,
},
altStyle: {
type: Object,
required: false,
},
selectedDynamicText: {
type: Object,
required: false,
},
setSelectedDynamicText: {
type: Function,
required: false,
},
});
</script>
<style lang="scss" scoped>
tr:last-child td {
border-bottom-style: solid !important;
}
tr td:first-child {
border-left-style: solid !important;
}
tr td:last-child {
border-right-style: solid !important;
}
</style>
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/components/base/BaseTableTd.vue
|
Vue
|
agpl-3.0
| 1,312
|
import { onMounted, onUnmounted } from "vue";
import { useMainStore } from "../store/MainStore";
import { useElementStore } from "../store/ElementStore";
import { checkUpdateElementOverlapping, deleteCurrentElements } from "../utils";
export function useAttachKeyBindings() {
const MainStore = useMainStore();
const ElementStore = useElementStore();
function updateStartXY(axis, value) {
MainStore.getCurrentElementsValues.forEach((element) => {
let restrict;
restrict = element.parent.DOMRef.getBoundingClientRect();
if (element[`start${axis}`] + value <= -1) {
element[`start${axis}`] = -1;
} else if (
element[`start${axis}`] + element[axis == "X" ? "width" : "height"] + value >=
restrict[axis == "X" ? "width" : "height"] - 1
) {
element[`start${axis}`] =
restrict[axis == "X" ? "width" : "height"] -
element[axis == "X" ? "width" : "height"] -
1;
} else {
element[`start${axis}`] += value;
}
});
checkUpdateElementOverlapping();
}
function updateWidthHeight(key, value) {
MainStore.getCurrentElementsValues.forEach((element) => {
let restrict = element.parent.DOMRef.getBoundingClientRect();
if (element[key] + value <= -1) {
element[key] = -1;
} else if (
element[key] + element[key == "width" ? "startX" : "startY"] + value >=
restrict[key] - 1
) {
element[key] = restrict[key] - element[key == "width" ? "startX" : "startY"] - 1;
} else {
element[key] += value;
}
});
checkUpdateElementOverlapping();
}
const handleKeyDown = async (e) => {
MainStore.isAltKey = e.altKey;
MainStore.isShiftKey = e.shiftKey;
if (!e.target.classList.contains("print-format-container") || MainStore.openModal) return;
if (e.ctrlKey || e.metaKey) {
if (["a", "A"].indexOf(e.key) != -1) {
ElementStore.Elements.forEach((page) => {
page.childrens.forEach((element) => {
MainStore.currentElements[element.id] = element;
});
});
} else if (!e.repeat && ["s", "S"].indexOf(e.key) != -1) {
await ElementStore.saveElements();
} else if (!e.repeat && ["l", "L"].indexOf(e.key) != -1) {
e.preventDefault();
MainStore.isLayerPanelEnabled = !MainStore.isLayerPanelEnabled;
}
}
if (
(!MainStore.isDrawing ||
(MainStore.isDrawing &&
(MainStore.currentDrawListener
? !MainStore.currentDrawListener.parameters.isMouseDown
: true))) &&
MainStore.getCurrentElementsId.length &&
["Space", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].indexOf(e.key) != -1
) {
e.preventDefault();
switch (e.key) {
case "ArrowUp":
if (e.altKey) {
updateWidthHeight("height", e.shiftKey ? -10 : -1);
break;
}
updateStartXY("Y", e.shiftKey ? -10 : -1);
break;
case "ArrowDown":
if (e.altKey) {
updateWidthHeight("height", e.shiftKey ? 10 : 1);
break;
}
updateStartXY("Y", e.shiftKey ? 10 : 1);
break;
case "ArrowLeft":
if (e.altKey) {
updateWidthHeight("width", e.shiftKey ? -10 : -1);
break;
}
updateStartXY("X", e.shiftKey ? -10 : -1);
break;
case "ArrowRight":
if (e.altKey) {
updateWidthHeight("width", e.shiftKey ? 10 : 1);
break;
}
updateStartXY("X", e.shiftKey ? 10 : 1);
break;
}
}
if (e.altKey || e.shiftKey || e.ctrlKey || e.metaKey) return;
if ((e.key == "M") | (e.key == "m")) {
MainStore.setActiveControl("MousePointer");
} else if (e.key == "A" || e.key == "a") {
MainStore.setActiveControl("Text");
} else if (e.key == "M" || e.key == "m") {
MainStore.setActiveControl("MousePointer");
} else if (e.key == "R" || e.key == "r") {
MainStore.setActiveControl("Rectangle");
} else if (e.key == "I" || e.key == "i") {
MainStore.setActiveControl("Image");
} else if (e.key == "T" || e.key == "t") {
MainStore.setActiveControl("Table");
// } else if (e.key == "C" || e.key == "c") {
// MainStore.setActiveControl("Components");
} else if (e.key == "B" || e.key == "b") {
MainStore.setActiveControl("Barcode");
} else if (e.key === "Delete" || e.key === "Backspace") {
deleteCurrentElements();
}
};
const handleKeyUp = (e) => {
MainStore.isAltKey = e.altKey;
MainStore.isShiftKey = e.shiftKey;
};
onMounted(() => {
window.addEventListener("keydown", handleKeyDown, false);
window.addEventListener("keyup", handleKeyUp);
});
onUnmounted(() => {
window.removeEventListener("keydown", handleKeyDown, false);
window.removeEventListener("keyup", handleKeyUp);
});
}
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/composables/AttachKeyBindings.js
|
JavaScript
|
agpl-3.0
| 4,553
|
import { parseFloatAndUnit } from "../utils";
/**
*
* @param {{inputString: String, defaultInputUnit: 'px'|'mm'|'cm'|'in', convertionUnit: 'px'|'mm'|'cm'|'in'}} `px is considered by default for defaultInputUnit and convertionUnit`
* @example
* useChangeValueUnit("210 mm", "in") : {
* value: 8.26771653553125,
* unit: in,
* error: false
* }
* @returns {{value: Number, unit: String, error: Boolean}} converted value based on unit parameters
*/
export function useChangeValueUnit({
inputString,
defaultInputUnit = "px",
convertionUnit = "px",
}) {
const parsedInput = parseFloatAndUnit(inputString, defaultInputUnit);
const UnitValues = Object.freeze({
px: 1,
mm: 3.7795275591,
cm: 37.795275591,
in: 96,
});
const converstionFactor = Object.freeze({
from_px: {
to_px: 1,
to_mm: UnitValues.px / UnitValues.mm,
to_cm: UnitValues.px / UnitValues.cm,
to_in: UnitValues.px / UnitValues.in,
},
from_mm: {
to_mm: 1,
to_px: UnitValues.mm / UnitValues.px,
to_cm: UnitValues.mm / UnitValues.cm,
to_in: UnitValues.mm / UnitValues.in,
},
from_cm: {
to_cm: 1,
to_px: UnitValues.cm / UnitValues.px,
to_mm: UnitValues.cm / UnitValues.mm,
to_in: UnitValues.cm / UnitValues.in,
},
from_in: {
to_in: 1,
to_px: UnitValues.in / UnitValues.px,
to_mm: UnitValues.in / UnitValues.mm,
to_cm: UnitValues.in / UnitValues.cm,
},
});
return {
value:
parsedInput.value *
converstionFactor[`from_${parsedInput.unit}`][`to_${convertionUnit}`],
unit: convertionUnit,
error: [NaN, null, undefined].includes(parsedInput.value),
};
}
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/composables/ChangeValueUnit.js
|
JavaScript
|
agpl-3.0
| 1,606
|
import interact from "@interactjs/interact";
import "@interactjs/actions/drag";
import "@interactjs/auto-start";
import "@interactjs/modifiers";
import { useMainStore } from "../store/MainStore";
import { useElementStore } from "../store/ElementStore";
import { recursiveChildrens, checkUpdateElementOverlapping } from "../utils";
export function useDraggable({
element,
restrict = "parent",
ignore = "th",
dragMoveListener,
dragStartListener,
dragStopListener,
}) {
if (interact.isSet(element["DOMRef"]) && interact(element["DOMRef"]).draggable().enabled)
return;
const MainStore = useMainStore();
let elementPreviousZAxis;
let top, left, bottom, right;
if (typeof restrict != "string") {
let rect = restrict.getBoundingClientRect();
(top = rect.top), (left = rect.left), (bottom = rect.bottom), (right = rect.right);
}
const restrictToParent = interact.modifiers.restrictRect({
restriction:
typeof restrict == "string"
? restrict
: {
top,
left,
bottom,
right,
},
});
interact(element["DOMRef"])
.draggable({
ignoreFrom: ignore,
autoScroll: true,
modifiers: [
restrictToParent,
interact.modifiers.snap({
targets: MainStore.snapPoints,
relativePoints: [{ x: 0, y: 0 }],
}),
],
listeners: {
move: dragMoveListener,
},
})
.on("dragstart", dragStartListener)
.on("dragend", function (e) {
element.style && (element.style.zIndex = elementPreviousZAxis);
dragStopListener && dragStopListener(e);
if (element.DOMRef.className == "modal-dialog modal-sm") {
return;
}
checkUpdateElementOverlapping(element);
});
return;
}
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/composables/Draggable.js
|
JavaScript
|
agpl-3.0
| 1,653
|
import { reactive } from "vue";
import { useMainStore } from "../store/MainStore";
export function useDraw() {
const MainStore = useMainStore();
const parameters = reactive({
startX: 0,
startY: 0,
width: 0,
height: 0,
isMouseDown: false,
isReversedX: false,
isReversedY: false,
initialScrollX: 0,
scrollX: 0,
initialScrollY: 0,
scrollY: 0,
});
const handleScroll = (e) => {
parameters.scrollX = canvas.parentElement.scrollLeft - parameters.initialScrollX;
parameters.scrollY = canvas.parentElement.scrollTop - parameters.initialScrollY;
};
const drawEventHandler = {
mousedown: (e) => {
parameters.isMouseDown = true;
parameters.width = 0;
parameters.height = 0;
parameters.initialX = e.clientX;
parameters.initialY = e.clientY;
parameters.offsetX = e.clientX - e.startX || 0;
parameters.offsetY = e.clientY - e.startY || 0;
parameters.startX = e.startX || e.clientX;
parameters.startY = e.startY || e.clientY;
parameters.initialScrollX = canvas.parentElement.scrollLeft;
parameters.initialScrollY = canvas.parentElement.scrollTop;
parameters.scrollX = 0;
parameters.scrollY = 0;
canvas.parentElement.addEventListener("scroll", handleScroll);
},
mousemove: (e) => {
let moveX = e.clientX - parameters.initialX + parameters.scrollX;
let moveY = e.clientY - parameters.initialY + parameters.scrollY;
let moveAbsX = Math.abs(moveX);
let moveAbsY = Math.abs(moveY);
if (!parameters.isMouseDown) return;
if (moveX < 0) {
parameters.isReversedX = true;
parameters.startX = e.clientX - parameters.offsetX + parameters.scrollX;
parameters.width = moveAbsX;
} else {
parameters.isReversedX = false;
parameters.startX = parameters.initialX - parameters.offsetX;
parameters.width = moveAbsX;
}
if (moveY < 0) {
parameters.isReversedY = true;
parameters.startY = e.clientY - parameters.offsetY + parameters.scrollY;
parameters.height = moveAbsY;
} else {
parameters.isReversedY = false;
parameters.startY = parameters.initialY - parameters.offsetY;
parameters.height = moveAbsY;
}
if (!e.shiftKey || MainStore.isMarqueeActive) return;
if (parameters.isReversedX) {
parameters.startX -=
parameters.width < parameters.height
? parameters.height - parameters.width
: 0;
}
if (parameters.isReversedY) {
parameters.startY -=
parameters.height < parameters.width
? parameters.width - parameters.height
: 0;
}
parameters.width = parameters.height =
parameters.width > parameters.height ? parameters.width : parameters.height;
},
mouseup: (e) => {
parameters.isMouseDown = false;
canvas.parentElement.removeEventListener("scroll", handleScroll);
},
};
return { parameters, drawEventHandler };
}
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/composables/Draw.js
|
JavaScript
|
agpl-3.0
| 2,816
|
import interact from "@interactjs/interact";
import "@interactjs/actions/drop";
import "@interactjs/auto-start";
import "@interactjs/modifiers";
import { useMainStore } from "../store/MainStore";
import { recursiveChildrens } from "../utils";
export function useDropZone({ element }) {
const MainStore = useMainStore();
if (interact.isSet(element["DOMRef"]) && interact(element["DOMRef"]).dropzone().enabled)
return;
interact(element.DOMRef).dropzone({
ignoreFrom: ".dropzone",
overlap: 1,
ondrop: (event) => {
let currentRef = event.draggable.target.piniaElementRef;
let currentDROP = event.dropzone.target.piniaElementRef;
let currentRect = event.draggable.target.getBoundingClientRect();
let dropRect = event.dropzone.target.getBoundingClientRect();
if (currentDROP === currentRef.parent) return;
let splicedElement = currentRef.parent.childrens.splice(currentRef.index, 1)[0];
splicedElement = { ...splicedElement };
splicedElement.startX = currentRect.left - dropRect.left;
splicedElement.startY = currentRect.top - dropRect.top;
splicedElement.parent = currentDROP;
recursiveChildrens({ element: splicedElement, isClone: false });
currentDROP.childrens.push(splicedElement);
let droppedElement = new Object();
droppedElement[splicedElement.id] = splicedElement;
MainStore.isDropped = droppedElement;
},
});
return;
}
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/composables/DropZone.js
|
JavaScript
|
agpl-3.0
| 1,384
|
import { useMainStore } from "../store/MainStore";
import { useDraggable } from "./Draggable";
import { useResizable } from "./Resizable";
import { useDropZone } from "./DropZone";
import { watch, markRaw } from "vue";
import interact from "@interactjs/interact";
import {
changeDraggable,
changeResizable,
changeDropZone,
getSnapPointsAndEdges,
getParentPage,
} from "../utils";
export function useElement({ draggable = true, resizable = true }) {
const MainStore = useMainStore();
const setReferance = (element) => (el) => {
element.DOMRef = markRaw(el);
el.piniaElementRef = element;
};
const setElements = (element, index) => (DOMElement) => {
if (!element) return;
element.index = index;
if (element.DOMRef) return;
if (element && DOMElement) {
setReferance(element)(DOMElement);
draggable && setDraggable(element);
resizable && setResizable(element);
const {
rowSnapPoint,
columnSnapPoint,
leftSnapEdge,
rightSnapEdge,
topSnapEdge,
bottomSnapEdge,
} = getSnapPointsAndEdges(element);
element.snapPoints = [rowSnapPoint, columnSnapPoint];
element.snapEdges = [leftSnapEdge, rightSnapEdge, topSnapEdge, bottomSnapEdge];
if (element.type == "rectangle" || element.type == "page") {
setDropZone(element);
}
element && changeResizable(element);
element && changeDraggable(element);
element && changeDropZone(element);
watch(
() => [
MainStore.page.width,
MainStore.page.height,
MainStore.page.marginTop,
MainStore.page.marginBottom,
MainStore.page.marginLeft,
MainStore.page.marginRight,
],
() => {
if (!element) return;
if (interact.isSet(element.DOMRef)) {
interact(element.DOMRef).unset();
}
draggable && setDraggable(element);
resizable && setResizable(element);
}
);
watch(
() => [MainStore.activeControl, MainStore.isAltKey],
() => {
if (!element) return;
if (MainStore.activeControl == "mouse-pointer") {
if (element.type != "page") {
element.isDraggable = true;
}
if (!MainStore.isAltKey) {
element.isResizable = true;
if (element.type == "rectangle" || element.type == "page") {
element.isDropZone = true;
}
} else {
element.isResizable = false;
element.isDropZone = false;
}
} else {
element.isDraggable = false;
element.isResizable = false;
element.isDropZone = false;
}
}
);
watch(
() => element?.isResizable,
() => {
element && changeResizable(element);
}
);
watch(
() => element?.isDraggable,
() => {
element && changeDraggable(element);
}
);
watch(
() => element?.isDropZone,
() => {
element && changeDropZone(element);
}
);
}
};
const setDraggable = (element) => {
if (element.relativeContainer) return;
const pageParent = getParentPage(element);
if (!pageParent) {
return;
}
const parentDOMRef = pageParent.DOMRef;
useDraggable({
element,
restrict: parentDOMRef,
dragMoveListener: (e) => {
if (e.metaKey || e.ctrlKey) {
e.interactable.options.drag.modifiers[0].disable();
} else {
e.interactable.options.drag.modifiers[0].enable();
}
let x = e.dx;
let y = e.dy;
if (MainStore.getCurrentElementsId.length < 1) {
element.pageX = (parseFloat(element.pageX) || 0) + x;
element.pageY = (parseFloat(element.pageY) || 0) + y;
element.startX = (parseFloat(element.startX) || 0) + x;
element.startY = (parseFloat(element.startY) || 0) + y;
} else {
MainStore.getCurrentElementsValues.forEach((currentElement) => {
if (currentElement && currentElement.isDraggable) {
currentElement.pageX = (parseFloat(currentElement.pageX) || 0) + x;
currentElement.pageY = (parseFloat(currentElement.pageY) || 0) + y;
currentElement.startX = (parseFloat(currentElement.startX) || 0) + x;
currentElement.startY = (parseFloat(currentElement.startY) || 0) + y;
}
});
}
e.stopImmediatePropagation();
},
dragStartListener: (e) => {
const parentRect =
element.parent.DOMRef?.getBoundingClientRect() ||
parentDOMRef.getBoundingClientRect();
const elementRect = element.DOMRef.getBoundingClientRect();
let offsetRect = MainStore.getCurrentElementsValues.reduce(
(offset, currentElement) => {
if (!currentElement) return offset;
let currentElementRect = currentElement.DOMRef.getBoundingClientRect();
currentElementRect.left < offset.left &&
(offset.left = currentElementRect.left);
currentElementRect.top < offset.top &&
(offset.top = currentElementRect.top);
currentElementRect.right > offset.right &&
(offset.right = currentElementRect.right);
currentElementRect.bottom > offset.bottom &&
(offset.bottom = currentElementRect.bottom);
return offset;
},
{ left: 9999, top: 9999, right: 0, bottom: 0 }
);
let restrictRect = {
left:
elementRect.left - offsetRect.left > 0
? elementRect.left - offsetRect.left
: 0,
top:
elementRect.top - offsetRect.top > 0
? elementRect.top - offsetRect.top
: 0,
right:
offsetRect.right - elementRect.right > 0
? offsetRect.right - elementRect.right
: 0,
bottom:
offsetRect.bottom - elementRect.bottom > 0
? offsetRect.bottom - elementRect.bottom
: 0,
};
elementPreviousZAxis = element.style.zIndex || 0;
element.style.zIndex = 9999;
const restrictionRect = {
top: parentRect.top + restrictRect.top,
left: parentRect.left + restrictRect.left,
right: parentRect.right - restrictRect.right,
bottom: parentRect.bottom - restrictRect.bottom,
};
if (MainStore.mode == "editing" && element.parent.type == "page") {
restrictionRect.top += MainStore.page.headerHeight;
restrictionRect.bottom -= MainStore.page.footerHeight;
}
e.interactable.options.drag.modifiers[0].options.restriction = restrictionRect;
},
});
};
const setResizable = (element) => {
const pageParent = getParentPage(element);
if (!pageParent) {
return;
}
const parentDOMRef = pageParent.DOMRef;
useResizable({
element,
restrict: parentDOMRef,
resizeStartListener: (e) => {
let parentRect = element.parent.DOMRef.getBoundingClientRect();
const restrictionRect = {
top: parentRect.top,
left: parentRect.left,
right: parentRect.right,
bottom: parentRect.bottom,
};
if (MainStore.mode == "editing" && element.parent.type == "page") {
restrictionRect.top += MainStore.page.headerHeight;
restrictionRect.bottom -= MainStore.page.footerHeight;
}
e.interactable.options.resize.modifiers[0].options.outer = restrictionRect;
if (!element.childrens || !element.childrens.length) return;
let offsetRect = element.childrens.reduce(
(offset, currentElement) => {
if (!currentElement) return offset;
let currentElementRect = currentElement.DOMRef.getBoundingClientRect();
currentElementRect.left < offset.left &&
(offset.left = currentElementRect.left);
currentElementRect.top < offset.top &&
(offset.top = currentElementRect.top);
currentElementRect.right > offset.right &&
(offset.right = currentElementRect.right);
currentElementRect.bottom > offset.bottom &&
(offset.bottom = currentElementRect.bottom);
return offset;
},
{ left: 9999, top: 9999, right: 0, bottom: 0 }
);
e.interactable.options.resize.modifiers[0].options.inner = {
top: offsetRect.top,
left: offsetRect.left,
right: offsetRect.right,
bottom: offsetRect.bottom,
};
},
resizeMoveListener: (e) => {
if (element.type == "text") {
element.isFixedSize = true;
}
if (e.metaKey || e.ctrlKey) {
e.interactable.options.resize.modifiers[0].disable();
} else {
e.interactable.options.resize.modifiers[0].enable();
}
element.startX = (element.startX || 0) + e.deltaRect.left;
element.startY = (element.startY || 0) + e.deltaRect.top;
element.width = (element.width || 0) - e.deltaRect.left + e.deltaRect.right;
element.height = (element.height || 0) - e.deltaRect.top + e.deltaRect.bottom;
if (element.type == "rectangle" || element.type == "page") {
element.childrens &&
element.childrens.forEach((childEl) => {
childEl.startX -= e.deltaRect.left;
childEl.startY -= e.deltaRect.top;
});
}
},
});
};
const setDropZone = (element) => {
useDropZone({
element,
});
};
return { setElements };
}
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/composables/Element.js
|
JavaScript
|
agpl-3.0
| 8,735
|
import { useMainStore } from "../store/MainStore";
import { useElementStore } from "../store/ElementStore";
import { useDraw } from "./Draw";
export function useMarqueeSelection() {
let canvas;
let marqueeElement = document.createElement("div");
let isElementInCanvas;
let beforeDraw, callback;
const MainStore = useMainStore();
const ElementStore = useElementStore();
const vMarquee = {
mounted: (el, binding) => {
if (binding.value) {
beforeDraw = binding.value.beforeDraw;
callback = binding.value.callback;
} else {
callback = undefined;
beforeDraw = true;
}
canvas = el;
canvas.addEventListener("mousedown", mouseDown);
canvas.addEventListener("mouseup", mouseUp);
canvas.addEventListener("mouseleave", mouseUp);
callback && callback(el);
},
unmounted: () => {
canvas.removeEventListener("mousedown", mouseDown);
canvas.removeEventListener("mouseup", mouseUp);
canvas.removeEventListener("mouseleave", mouseUp);
},
};
const { drawEventHandler, parameters } = useDraw();
function mouseDown(e) {
if (e.buttons != 1) return;
if (e.target.id == "canvas" && MainStore.activeControl != "mouse-pointer") {
MainStore.setActiveControl("MousePointer");
MainStore.activePage = null;
MainStore.isMarqueeActive = true;
}
if (!MainStore[beforeDraw]) return;
drawEventHandler.mousedown(e);
canvas.addEventListener("mousemove", mouseMove);
if (!e.shiftKey && MainStore.getCurrentElementsId.length) {
MainStore.getCurrentElementsId.forEach((element) => {
delete MainStore.currentElements[element];
});
}
if (!canvas) return;
if (marqueeElement) {
marqueeElement.remove();
}
marqueeElement = document.createElement("div");
marqueeElement.className = "selection";
marqueeElement.style.zIndex = 9999;
marqueeElement.style.left = parameters.startX - canvas.getBoundingClientRect().left + "px";
marqueeElement.style.top = parameters.startY - canvas.getBoundingClientRect().top + "px";
}
function mouseMove(e) {
if (!MainStore[beforeDraw]) return;
drawEventHandler.mousemove(e);
if (
!isElementInCanvas &&
parameters.isMouseDown &&
(parameters.width > 5 || parameters.height > 5)
) {
canvas.appendChild(marqueeElement);
isElementInCanvas = true;
}
if (marqueeElement) {
marqueeElement.style.width = Math.abs(parameters.width) + "px";
marqueeElement.style.height = Math.abs(parameters.height) + "px";
marqueeElement.style.left =
parameters.startX -
canvas.getBoundingClientRect().left -
parameters.scrollX +
"px";
marqueeElement.style.top =
parameters.startY - canvas.getBoundingClientRect().top - parameters.scrollY + "px";
}
}
function mouseUp(e) {
canvas.removeEventListener("mousemove", mouseMove);
if (!MainStore[beforeDraw]) return;
drawEventHandler.mouseup(e);
if (marqueeElement) {
const inBounds = [];
if (!e.shiftKey && MainStore.getCurrentElementsId.length) {
MainStore.getCurrentElementsId.forEach((element) => {
delete MainStore.currentElements[element];
});
}
const canvas = {
x: parameters.startX,
y: parameters.startY,
width: Math.abs(parameters.width),
height: Math.abs(parameters.height),
};
for (const page of ElementStore.Elements) {
const pageRect = page.DOMRef.getBoundingClientRect();
a = { ...canvas };
a.x -= pageRect.x;
a.y -= pageRect.y;
for (const element of page.childrens) {
const { id, startX, startY, width, height, DOMRef } = element;
const b = {
id,
x: startX,
y: startY,
width,
height,
DOMRef,
};
if (!element.relativeContainer && isInBounds(a, b)) {
inBounds.push(DOMRef);
if ((e.metaKey || e.ctrlKey) && e.shiftKey) {
delete MainStore.currentElements[id];
} else {
MainStore.currentElements[id] = element;
}
}
}
}
marqueeElement.remove();
marqueeElement = null;
isElementInCanvas = false;
}
}
function isInBounds(a, b) {
return (
a.x < b.x + b.width &&
a.x + a.width > b.x &&
a.y < b.y + b.height &&
a.y + a.height > b.y
);
}
return { mouseDown, mouseMove, mouseUp, canvas, vMarquee };
}
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/composables/MarqueeSelectionTool.js
|
JavaScript
|
agpl-3.0
| 4,211
|
import interact from "@interactjs/interact";
import "@interactjs/actions/resize";
import "@interactjs/auto-start";
import "@interactjs/modifiers";
import { useMainStore } from "../store/MainStore";
import { useElementStore } from "../store/ElementStore";
import { recursiveChildrens, checkUpdateElementOverlapping, getParentPage } from "../utils";
export function useResizable({
element,
resizeMoveListener,
resizeStartListener,
resizeStopListener,
restrict = "parent",
}) {
if (element && restrict) {
if (interact.isSet(element.DOMRef) && interact(element.DOMRef).resizable().enabled) {
return;
}
const MainStore = useMainStore();
const ElementStore = useElementStore();
const edges = {
bottom: ".resize-bottom",
};
if (!element.relativeContainer) {
edges.left = ".resize-left";
edges.right = ".resize-right";
edges.top = ".resize-top";
}
interact(element.DOMRef)
.resizable({
ignoreFrom: ".resizer",
edges: edges,
modifiers: [
interact.modifiers.restrictEdges(),
interact.modifiers.snapEdges({
targets: MainStore.snapEdges,
}),
],
listeners: {
move: resizeMoveListener,
},
})
.on("resizestart", resizeStartListener)
.on("resizeend", function (e) {
resizeStopListener && resizeStopListener(e);
if (element.DOMRef.className == "modal-dialog modal-sm") {
return;
}
checkUpdateElementOverlapping(element);
if (element.parent == e.target.piniaElementRef.parent) return;
if (
!e.dropzone &&
e.target.piniaElementRef.parent.type != "page" &&
!MainStore.lastCloned
) {
let splicedElement;
let currentRect = e.target.getBoundingClientRect();
let canvasRect = getParentPage(
e.target.piniaElementRef.parent
).DOMRef.getBoundingClientRect();
let currentParent = e.target.piniaElementRef.parent;
if (currentParent.type == "page") {
splicedElement = currentParent.splice(
e.target.piniaElementRef.index,
1
)[0];
} else {
splicedElement = currentParent.childrens.splice(
e.target.piniaElementRef.index,
1
)[0];
}
splicedElement = { ...splicedElement };
splicedElement.startX = currentRect.left - canvasRect.left;
splicedElement.startY = currentRect.top - canvasRect.top;
splicedElement.parent = ElementStore.Elements;
recursiveChildrens({ element: splicedElement, isClone: false });
ElementStore.Elements.push(splicedElement);
let droppedElement = new Object();
droppedElement[splicedElement.id] = splicedElement;
MainStore.isDropped = droppedElement;
}
});
}
return;
}
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/composables/Resizable.js
|
JavaScript
|
agpl-3.0
| 2,661
|
import { useMainStore } from "./store/MainStore";
export const createRectangle = (cordinates, parent = null) => {
const MainStore = useMainStore();
let id = frappe.utils.get_random(10);
if (cordinates instanceof MouseEvent) {
cordinates = {
startX: cordinates.offsetX,
startY: cordinates.offsetY,
pageX: cordinates.x,
pageY: cordinates.y,
};
}
const newRectangle = {
id: id,
type: "rectangle",
DOMRef: null,
childrens: [],
parent: parent,
isDraggable: false,
isResizable: false,
isDropZone: false,
startX: cordinates.startX,
startY: cordinates.startY,
pageX: cordinates.pageX,
pageY: cordinates.pageY,
width: 0,
height: 0,
styleEditMode: "main",
style: {},
classes: [],
};
parent.childrens?.push(newRectangle);
MainStore.lastCreatedElement = newRectangle;
return newRectangle;
};
export const createImage = (cordinates, parent = null) => {
const MainStore = useMainStore();
let id = frappe.utils.get_random(10);
if (cordinates instanceof MouseEvent) {
cordinates = {
startX: cordinates.offsetX,
startY: cordinates.offsetY,
pageX: cordinates.x,
pageY: cordinates.y,
};
}
const newImage = {
id: id,
type: "image",
DOMRef: null,
parent: parent,
isDraggable: false,
isResizable: false,
isDropZone: false,
isDynamic: false,
image: null,
startX: cordinates.startX,
startY: cordinates.startY,
pageX: cordinates.pageX,
pageY: cordinates.pageY,
width: 0,
height: 0,
styleEditMode: "main",
style: {},
classes: [],
};
parent.childrens?.push(newImage) || parent.childrens.push(newImage);
MainStore.lastCreatedElement = newImage;
return newImage;
};
export const createBarcode = (cordinates, parent = null) => {
const MainStore = useMainStore();
let id = frappe.utils.get_random(10);
if (cordinates instanceof MouseEvent) {
cordinates = {
startX: cordinates.offsetX,
startY: cordinates.offsetY,
pageX: cordinates.x,
pageY: cordinates.y,
};
}
const newBarcode = {
id: id,
type: "barcode",
barcodeFormat: MainStore.globalStyles["barcode"].barcodeFormat || "qrcode",
barcodeColor: "#000000",
barcodeBackgroundColor: "#ffffff",
DOMRef: null,
parent: parent,
isDraggable: false,
isResizable: false,
isDropZone: false,
isDynamic: false,
value: "",
dynamicContent: [],
startX: cordinates.startX,
startY: cordinates.startY,
pageX: cordinates.pageX,
pageY: cordinates.pageY,
width: 0,
height: 0,
styleEditMode: "main",
style: {},
classes: [],
};
parent.childrens?.push(newBarcode) || parent.childrens.push(newBarcode);
MainStore.lastCreatedElement = newBarcode;
return newBarcode;
};
export const createTable = (cordinates, parent = null) => {
const MainStore = useMainStore();
let id = frappe.utils.get_random(10);
if (cordinates instanceof MouseEvent) {
cordinates = {
startX: cordinates.offsetX,
startY: cordinates.offsetY,
pageX: cordinates.x,
pageY: cordinates.y,
};
}
const newTable = {
id: id,
type: "table",
DOMRef: null,
parent: parent,
isDraggable: false,
isResizable: false,
isDropZone: false,
table: null,
columns: [],
PreviewRowNo: 1,
selectedColumn: null,
selectedDynamicText: null,
startX: cordinates.startX,
startY: cordinates.startY,
pageX: cordinates.pageX,
pageY: cordinates.pageY,
width: 0,
height: 0,
styleEditMode: "main",
labelDisplayStyle: "standard",
style: {},
labelStyle: {},
headerStyle: {},
altStyle: {},
heightType: "auto",
classes: [],
};
parent.childrens?.push(newTable) || parent.childrens.push(newTable);
MainStore.lastCreatedElement = newTable;
return newTable;
};
export const createText = (cordinates, parent = null) => {
const MainStore = useMainStore();
let id = frappe.utils.get_random(10);
if (cordinates instanceof MouseEvent) {
cordinates = {
startX: cordinates.offsetX,
startY: cordinates.offsetY,
pageX: cordinates.x,
pageY: cordinates.y,
};
}
const newStaticText = {
id: id,
type: "text",
DOMRef: null,
parent: parent,
content: "",
contenteditable: true,
isDynamic: false,
isFixedSize: false,
isDraggable: false,
isResizable: false,
isDropZone: false,
parseJinja: false,
startX: cordinates.startX - 5,
startY: cordinates.startY - 16,
pageX: cordinates.pageX,
pageY: cordinates.pageY,
width: 0,
height: 0,
styleEditMode: "main",
labelDisplayStyle: "standard",
style: {},
classes: [],
};
parent.childrens?.push(newStaticText) || parent.childrens.push(newStaticText);
MainStore.lastCreatedElement = newStaticText;
return newStaticText;
};
export const createDynamicText = (cordinates, parent = null) => {
const MainStore = useMainStore();
let id = frappe.utils.get_random(10);
if (cordinates instanceof MouseEvent) {
cordinates = {
startX: cordinates.offsetX,
startY: cordinates.offsetY,
pageX: cordinates.x,
pageY: cordinates.y,
};
}
const newDynamicText = {
id: id,
type: "text",
DOMRef: null,
parent: parent,
content: "",
contenteditable: false,
isDynamic: true,
isFixedSize: false,
dynamicContent: [],
selectedDynamicText: null,
isDraggable: false,
isResizable: false,
isDropZone: false,
startX: cordinates.startX - 5,
startY: cordinates.startY - 16,
pageX: cordinates.pageX,
pageY: cordinates.pageY,
width: 0,
height: 0,
styleEditMode: "main",
labelDisplayStyle: "standard",
style: {},
labelStyle: {},
heightType: "auto",
classes: [],
};
parent.childrens?.push(newDynamicText) || parent.childrens.push(newDynamicText);
MainStore.lastCreatedElement = newDynamicText;
return newDynamicText;
};
export const GoogleFonts = {
Alegreya: [
[400, 500, 600, 700, 800, 900],
[400, 500, 600, 700, 800, 900],
],
"Alegreya Sans": [
[100, 300, 400, 500, 700, 800, 900],
[100, 300, 400, 500, 700, 800, 900],
],
"Andada Pro": [
[400, 500, 600, 700, 800],
[400, 500, 600, 700, 800],
],
Anton: [[400], []],
Archivo: [
[100, 200, 300, 400, 500, 600, 700, 800, 900],
[100, 200, 300, 400, 500, 600, 700, 800, 900],
],
"Archivo Narrow": [
[400, 500, 600, 700],
[400, 500, 600, 700],
],
BioRhyme: [[200, 300, 400, 700, 800], []],
Cardo: [[400, 700], [400]],
Chivo: [
[100, 200, 300, 400, 500, 600, 700, 800, 900],
[100, 200, 300, 400, 500, 600, 700, 800, 900],
],
Cormorant: [
[300, 400, 500, 600, 700],
[300, 400, 500, 600, 700],
],
"Crimson Text": [
[400, 600, 700],
[400, 600, 700],
],
"DM Sans": [
[400, 500, 700],
[400, 500, 700],
],
Eczar: [[400, 500, 600, 700, 800], []],
"Encode Sans": [[100, 200, 300, 400, 500, 600, 700, 800, 900], []],
"Fira Sans": [
[100, 200, 300, 400, 500, 600, 700, 800, 900],
[100, 200, 300, 400, 500, 600, 700, 800, 900],
],
Hahmlet: [[100, 200, 300, 400, 500, 600, 700, 800, 900], []],
"IBM Plex Sans": [
[100, 200, 300, 400, 500, 600, 700],
[100, 200, 300, 400, 500, 600, 700],
],
Inconsolata: [[200, 300, 400, 500, 600, 700, 800, 900], []],
"Inknut Antiqua": [[300, 400, 500, 600, 700, 800, 900], []],
Inter: [[100, 200, 300, 400, 500, 600, 700, 800, 900], []],
"JetBrains Mono": [
[100, 200, 300, 400, 500, 600, 700, 800],
[100, 200, 300, 400, 500, 600, 700, 800],
],
Karla: [
[200, 300, 400, 500, 600, 700, 800],
[200, 300, 400, 500, 600, 700, 800],
],
Lato: [
[100, 300, 400, 700, 900],
[100, 300, 400, 700, 900],
],
"Libre Baskerville": [[400, 700], [400]],
"Libre Franklin": [
[100, 200, 300, 400, 500, 600, 700, 800, 900],
[100, 200, 300, 400, 500, 600, 700, 800, 900],
],
Lora: [
[400, 500, 600, 700],
[400, 500, 600, 700],
],
Manrope: [[200, 300, 400, 500, 600, 700, 800], []],
Merriweather: [
[300, 400, 700, 900],
[300, 400, 700, 900],
],
Montserrat: [
[100, 200, 300, 400, 500, 600, 700, 800, 900],
[100, 200, 300, 400, 500, 600, 700, 800, 900],
],
Neuton: [[200, 300, 400, 700, 800], [400]],
Nunito: [
[200, 300, 400, 500, 600, 700, 800, 900],
[200, 300, 400, 500, 600, 700, 800, 900],
],
"Old Standard TT": [[400, 700], [400]],
"Open Sans": [
[300, 400, 500, 600, 700, 800],
[300, 400, 500, 600, 700, 800],
],
Oswald: [[200, 300, 400, 500, 600, 700], []],
Oxygen: [[300, 400, 700], []],
"PT Sans": [
[400, 700],
[400, 700],
],
"PT Serif": [
[400, 700],
[400, 700],
],
"Playfair Display": [
[400, 500, 600, 700, 800, 900],
[400, 500, 600, 700, 800, 900],
],
Poppins: [
[100, 200, 300, 400, 500, 600, 700, 800, 900],
[100, 200, 300, 400, 500, 600, 700, 800, 900],
],
"Proza Libre": [
[400, 500, 600, 700, 800],
[400, 500, 600, 700, 800],
],
Raleway: [
[100, 200, 300, 400, 500, 600, 700, 800, 900],
[100, 200, 300, 400, 500, 600, 700, 800, 900],
],
Roboto: [
[100, 300, 400, 500, 700, 900],
[100, 300, 400, 500, 700, 900],
],
"Roboto Slab": [[100, 200, 300, 400, 500, 600, 700, 800, 900], []],
Rubik: [
[300, 400, 500, 600, 700, 800, 900],
[300, 400, 500, 600, 700, 800, 900],
],
Sora: [[100, 200, 300, 400, 500, 600, 700, 800], []],
"Source Sans Pro": [
[200, 300, 400, 600, 700, 900],
[200, 300, 400, 600, 700, 900],
],
"Source Serif Pro": [
[200, 300, 400, 600, 700, 900],
[200, 300, 400, 600, 700, 900],
],
"Space Grotesk": [[300, 400, 500, 600, 700], []],
"Space Mono": [
[400, 700],
[400, 700],
],
Spectral: [
[200, 300, 400, 500, 600, 700, 800],
[200, 300, 400, 500, 600, 700, 800],
],
Syne: [[400, 500, 600, 700, 800], []],
"Work Sans": [
[100, 200, 300, 400, 500, 600, 700, 800, 900],
[100, 200, 300, 400, 500, 600, 700, 800, 900],
],
};
export const barcodeFormats = [
{ label: "QR Code", value: "qrcode" },
{ label: "Code39", value: "code39" },
{ label: "Code128", value: "code128" },
{ label: "EAN", value: "ean" },
{ label: "EAN8", value: "ean8" },
{ label: "EAN13", value: "ean13" },
{ label: "EAN14", value: "ean14" },
{ label: "GTIN", value: "gtin" },
{ label: "JAN", value: "jan" },
{ label: "UPCA", value: "upc" },
{ label: "UPCA", value: "upca" },
{ label: "ISSN", value: "issn" },
{ label: "ISBN", value: "isbn" },
{ label: "ISBN10", value: "isbn10" },
{ label: "ISBN13", value: "isbn13" },
{ label: "PZN", value: "pzn" },
{ label: "ITF", value: "itf" },
{ label: "GS1", value: "gs1" },
{ label: "Gs1_128", value: "gs1_128" },
];
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/defaultObjects.js
|
JavaScript
|
agpl-3.0
| 10,261
|
import { watch, isRef, nextTick, shallowReactive } from "vue";
import { useMainStore } from "./store/MainStore";
import { onClickOutside } from "@vueuse/core";
import { getConditonalObject } from "./utils";
export const makeFeild = ({
name,
ref,
fieldtype,
requiredData,
options,
reactiveObject,
propertyName,
isStyle = false,
isFontStyle = false,
onChangeCallback = null,
formatValue = (object, property, isStyle, toDB = false) => {
if (isStyle) {
const MainStore = useMainStore();
return MainStore.getCurrentStyle(property);
}
return getConditonalObject({
reactiveObject: object,
isStyle,
isFontStyle,
property,
});
},
}) => {
const MainStore = useMainStore();
if (ref === null) MainStore.frappeControls[name]?.vueWatcher?.();
if (!ref || MainStore.frappeControls[name]?.parent?.[0] === ref) return;
if (MainStore.frappeControls[name]?.awesomplete) {
MainStore.frappeControls[name].awesomplete.destroy();
Awesomplete.all.splice([MainStore.frappeControls[name].awesomplete.count - 1], 1);
}
const createField = () => {
obj_value = null;
last_value = null;
MainStore.frappeControls[name] = shallowReactive(
frappe.ui.form.make_control({
parent: $(ref),
df: {
fieldtype: fieldtype,
options: typeof options == "function" ? options() : options || "",
change: () => {
let object;
if (isStyle) {
object = MainStore.getStyleObject(isFontStyle);
} else {
object = reactiveObject;
isRef(reactiveObject) && (object = object.value);
typeof reactiveObject == "function" && (object = object());
}
if (!object) return;
let value = MainStore.frappeControls[name].get_value();
last_value = value;
obj_value = formatValue(object, propertyName, isStyle);
if (
(!(typeof value == "undefined" || value === null) ||
fieldtype == "Color") &&
obj_value != value
) {
object[propertyName] = value;
onChangeCallback && onChangeCallback(value);
} else if (!value && formatValue(object, propertyName, isStyle)) {
if (
fieldtype == "Color" &&
propertyName == "backgroundColor" &&
!value
)
return;
MainStore.frappeControls[name].set_value(
formatValue(object, propertyName, isStyle)
);
onChangeCallback && onChangeCallback();
}
},
},
only_input: true,
render_input: true,
})
);
let object;
if (isStyle) {
object = MainStore.getStyleObject(isFontStyle);
} else {
object = reactiveObject;
isRef(reactiveObject) && (object = object.value);
typeof reactiveObject == "function" && (object = object());
}
MainStore.frappeControls[name].set_value(formatValue(object, propertyName, isStyle));
if (["Link", "Autocomplete"].indexOf(fieldtype) != -1) {
MainStore.frappeControls[name].$input[0].onfocus = () => {
MainStore.frappeControls[name].$input.select();
MainStore.frappeControls[name].$input.one("blur", () => {
let value = MainStore.frappeControls[name].value;
if (
typeof value == "undefined" ||
value === null ||
(fieldtype == "Int" && !Number.isInteger(value))
) {
value = MainStore.frappeControls[name].last_value;
}
MainStore.frappeControls[name].$input.val(value);
});
};
} else if (fieldtype === "Select") {
MainStore.frappeControls[name].$input.change((event) => {
event.target.blur();
});
} else if (fieldtype === "Color") {
if (MainStore.frappeControls[name]) {
let hidePicker;
MainStore.frappeControls[name].$wrapper.on("show.bs.popover", () => {
if (!MainStore.frappeControls[name]) return;
MainStore.frappeControls[name].$input[0].classList.add("input-active");
hidePicker = onClickOutside(
MainStore.frappeControls[name].picker.parent,
() => {
MainStore.frappeControls[name] &&
MainStore.frappeControls[name].$wrapper.popover("hide");
}
);
});
MainStore.frappeControls[name].$wrapper.on("hidden.bs.popover", () => {
if (!MainStore.frappeControls[name]) return;
MainStore.frappeControls[name].$input[0].classList.remove("input-active");
hidePicker && hidePicker();
});
}
}
if (isStyle && !MainStore.frappeControls[name].vueWatcher) {
MainStore.frappeControls[name].vueWatcher = watch(
() => MainStore.getCurrentStyle(propertyName),
() => {
if (MainStore.getCurrentElementsValues.length < 2) {
MainStore.frappeControls[name]?.refresh();
nextTick(() => {
MainStore.frappeControls[name]?.set_value(
MainStore.getCurrentStyle(propertyName)
);
onChangeCallback &&
onChangeCallback(MainStore.getCurrentStyle(propertyName));
});
}
}
);
}
if (object === MainStore && !MainStore.frappeControls[name].vueWatcher) {
MainStore.frappeControls[name].vueWatcher = watch(
() => object[propertyName],
(newValue) => {
MainStore.frappeControls[name]?.refresh();
nextTick(() => {
MainStore.frappeControls[name]?.set_value(
formatValue(object, propertyName, isStyle)
);
onChangeCallback &&
onChangeCallback(formatValue(object, propertyName, isStyle));
});
},
{ immediate: true }
);
} else if (
!isStyle &&
["styleEditMode"].indexOf(propertyName) != -1 &&
!MainStore.frappeControls[name].vueWatcher
) {
MainStore.frappeControls[name].vueWatcher = watch(
() => [
MainStore.getGlobalStyleObject,
MainStore.getCurrentElementsValues[0]?.styleEditMode,
],
() => {
let styleClass = "table";
if (MainStore.activeControl == "text") {
if (MainStore.textControlType == "dynamic") {
styleClass = "dynamicText";
} else {
styleClass = "staticText";
}
}
nextTick(() => {
if (!MainStore.frappeControls[name]) return;
if (
("text" == MainStore.getCurrentElementsValues[0]?.type &&
MainStore.getCurrentElementsValues[0]?.isDynamic) ||
("text" == MainStore.activeControl &&
MainStore.textControlType == "dynamic")
) {
MainStore.frappeControls[name].df.options = [
{ label: "Label Element", value: "label" },
{ label: "Main Element", value: "main" },
];
} else if (
"text" == MainStore.getCurrentElementsValues[0]?.type ||
"text" == MainStore.activeControl
) {
MainStore.frappeControls[name].df.options = [
{ label: "Main Element", value: "main" },
];
} else {
MainStore.frappeControls[name].df.options = [
{ label: "Table Header", value: "header" },
{ label: "All Rows", value: "main" },
{ label: "Alternate Rows", value: "alt" },
{ label: "Field Labels", value: "label" },
];
}
MainStore.frappeControls[name].refresh();
MainStore.frappeControls[name]?.set_value(
MainStore.getCurrentElementsValues[0]?.styleEditMode ||
MainStore.globalStyles[styleClass].styleEditMode
);
onChangeCallback &&
onChangeCallback(formatValue(object, propertyName, isStyle));
});
},
{ immediate: true }
);
}
};
if (
Array.isArray(requiredData)
? requiredData.every((condition) =>
isRef(condition) ? !!condition.value : !!condition
)
: requiredData
) {
createField();
} else {
let removeWatcher = watch(
() => requiredData,
() => {
if (!ref || MainStore.frappeControls[name]?.parent?.[0] === ref) return;
if (
Array.isArray(requiredData)
? requiredData.every((condition) =>
isRef(condition) ? !!condition.value : !!condition
)
: requiredData
)
return;
createField();
removeWatcher();
}
);
}
};
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/frappeControl.js
|
JavaScript
|
agpl-3.0
| 7,818
|
export const globalStyles = {
staticText: new Object({
isGlobalStyle: true,
styleEditMode: "main",
labelDisplayStyle: "standard",
type: "text",
isDynamic: false,
mainRuleSelector: ".staticText",
style: {
display: "inline-block",
fontFamily: "Inter",
fontSize: "14px",
fontWeight: 400,
color: "#000000",
textAlign: "left",
fontStyle: "normal",
textDecoration: "none",
textTransform: "none",
lineHeight: 1.25,
letterSpacing: "0px",
contenteditable: false,
border: "none",
borderWidth: "0px",
borderColor: "#000000",
borderStyle: "solid",
borderRadius: 0,
backgroundColor: "",
paddingTop: "0px",
paddingBottom: "0px",
paddingLeft: "0px",
paddingRight: "0px",
margin: "0px",
minWidth: "0px",
minHeight: "0px",
boxShadow: "none",
overflow: "hidden",
overflowWrap: "break-word",
whiteSpace: "normal",
userSelect: "none",
opacity: 1,
zIndex: 1,
},
}),
dynamicText: new Object({
isGlobalStyle: true,
styleEditMode: "main",
labelDisplayStyle: "standard",
type: "text",
isDynamic: true,
mainRuleSelector: ".dynamicText",
labelRuleSelector: ".dynamicText .label-text",
style: {
display: "inline-block",
fontFamily: "Inter",
fontSize: "14px",
fontWeight: 400,
color: "#000000",
textAlign: "left",
fontStyle: "normal",
textDecoration: "none",
textTransform: "none",
lineHeight: 1.25,
letterSpacing: "0px",
contenteditable: false,
border: "none",
borderWidth: "0px",
borderColor: "#000000",
borderStyle: "solid",
borderRadius: 0,
backgroundColor: "",
paddingTop: "0px",
paddingBottom: "0px",
paddingLeft: "0px",
paddingRight: "0px",
margin: "0px",
minWidth: "0px",
minHeight: "0px",
boxShadow: "none",
overflow: "hidden",
overflowWrap: "break-word",
whiteSpace: "normal",
userSelect: "none",
opacity: 1,
},
labelStyle: {
fontFamily: "Inter",
fontSize: "14px",
fontWeight: 600,
color: "#000000",
textAlign: "left",
fontStyle: "normal",
textDecoration: "none",
textTransform: "none",
lineHeight: 1.25,
letterSpacing: "0px",
border: "none",
borderWidth: "0px",
borderColor: "#000000",
borderStyle: "solid",
borderRadius: 0,
backgroundColor: "",
paddingTop: "0px",
paddingBottom: "0px",
paddingLeft: "0px",
paddingRight: "0px",
margin: "0px",
minWidth: "0px",
minHeight: "0px",
boxShadow: "none",
whiteSpace: "normal",
userSelect: "none",
opacity: 1,
zIndex: 1,
},
}),
rectangle: new Object({
isGlobalStyle: true,
styleEditMode: "main",
type: "rectangle",
isDynamic: false,
mainRuleSelector: ".rectangle",
style: {
paddingTop: "0px",
paddingBottom: "0px",
paddingLeft: "0px",
paddingRight: "0px",
margin: "0px",
whiteSpace: "normal",
userSelect: "none",
minWidth: "0px",
minHeight: "0px",
color: "#000000",
backgroundColor: "",
border: "1px solid black",
borderColor: "#000000",
borderStyle: "solid",
borderWidth: "1px",
boxSizing: "border-box",
outline: "none",
borderRadius: 0,
boxShadow: "none",
opacity: 1,
zIndex: 0,
},
}),
image: new Object({
isGlobalStyle: true,
styleEditMode: "main",
type: "image",
isDynamic: false,
mainRuleSelector: ".image",
style: {
display: "block",
border: "none",
borderWidth: "0px",
borderColor: "#000000",
borderStyle: "solid",
borderRadius: 0,
backgroundColor: "",
paddingTop: "0px",
paddingBottom: "0px",
paddingLeft: "0px",
paddingRight: "0px",
margin: "0px",
minWidth: "0px",
minHeight: "0px",
boxShadow: "none",
whiteSpace: "normal",
userSelect: "none",
objectFit: "scale-down",
objectPosition: "center center",
// wkhtmltopdf doesn't support object-fit and object-position :(
backgroundSize: "contain",
backgroundPosition: "center center",
backgroundRepeat: "no-repeat",
opacity: 1,
},
}),
barcode: new Object({
isGlobalStyle: true,
styleEditMode: "main",
type: "barcode",
isDynamic: false,
mainRuleSelector: ".barcode",
style: {
display: "block",
border: "none",
borderWidth: "0px",
borderColor: "#000000",
borderStyle: "solid",
borderRadius: 0,
backgroundColor: "",
paddingTop: "0px",
paddingBottom: "0px",
paddingLeft: "0px",
paddingRight: "0px",
margin: "0px",
minWidth: "0px",
minHeight: "0px",
boxShadow: "none",
whiteSpace: "normal",
userSelect: "none",
opacity: 1,
},
}),
table: new Object({
isGlobalStyle: true,
styleEditMode: "main",
labelDisplayStyle: "standard",
type: "table",
isDynamic: true,
mainRuleSelector: ".printTable td",
headerRuleSelector: ".printTable th",
altRuleSelector: ".printTable tr:nth-child(even) td",
labelRuleSelector: ".printTable .label-text",
style: {
fontFamily: "Inter",
fontSize: "10px",
fontWeight: 400,
color: "#000000",
textAlign: "left",
fontStyle: "normal",
textDecoration: "none",
textTransform: "none",
lineHeight: 1.25,
letterSpacing: "0px",
contenteditable: false,
border: "none",
borderWidth: "1px",
borderColor: "#000000",
borderStyle: "solid",
borderRadius: 0,
backgroundColor: "#ffffff",
paddingTop: "10px",
paddingBottom: "10px",
paddingLeft: "10px",
paddingRight: "10px",
margin: "0px",
minWidth: "0px",
minHeight: "0px",
boxShadow: "none",
overflowWrap: "break-word",
whiteSpace: "normal",
userSelect: "none",
verticalAlign: "baseline",
opacity: 1,
},
labelStyle: {
fontFamily: "Inter",
fontSize: "10px",
fontWeight: 600,
color: "#000000",
textAlign: "left",
fontStyle: "normal",
textDecoration: "none",
textTransform: "none",
lineHeight: 1.25,
letterSpacing: "0px",
border: "none",
borderWidth: "0px",
borderColor: "#000000",
borderStyle: "solid",
borderRadius: 0,
backgroundColor: "#ffffff",
paddingTop: "0px",
paddingBottom: "0px",
paddingLeft: "0px",
paddingRight: "0px",
margin: "0px",
minWidth: "0px",
minHeight: "0px",
boxShadow: "none",
whiteSpace: "normal",
userSelect: "none",
opacity: 1,
verticalAlign: "baseline",
zIndex: 1,
},
headerStyle: {
fontFamily: "Inter",
fontSize: "11px",
fontWeight: 600,
color: "#000000",
textAlign: "left",
fontStyle: "normal",
textDecoration: "none",
textTransform: "none",
lineHeight: 1.25,
letterSpacing: "0px",
border: "none",
borderWidth: "1px",
borderColor: "#000000",
borderStyle: "solid",
borderRadius: 0,
backgroundColor: "#ffffff",
paddingTop: "10px",
paddingBottom: "10px",
paddingLeft: "10px",
paddingRight: "10px",
margin: "0px",
minWidth: "0px",
minHeight: "0px",
boxShadow: "none",
whiteSpace: "normal",
userSelect: "none",
opacity: 1,
zIndex: 1,
},
altStyle: {},
}),
};
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/globalStyles.js
|
JavaScript
|
agpl-3.0
| 6,954
|
<template>
<svg
id="printIcons"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
style="display: none"
>
<symbol id="layerPanel" fill="none" viewBox="0 0 16 16">
<g filter="url(#a)">
<path
fill="var(--icon-stroke)"
fill-rule="evenodd"
d="M8.347 2.123a.7.7 0 0 0-.694 0L4.252 4.066 1.056 5.892a.7.7 0 0 0 0 1.216l3.196 1.826 3.4 1.943a.7.7 0 0 0 .695 0l3.401-1.943 3.196-1.826a.7.7 0 0 0 0-1.216l-6.597-3.77ZM4.748 4.934 8 3.076 13.992 6.5l-2.74 1.566L8 9.924 4.748 8.066 2.008 6.5l2.74-1.566Zm-3.5 4.132a.5.5 0 0 0-.496.868l3.5 2 3.4 1.943a.7.7 0 0 0 .695 0l3.401-1.943 3.5-2a.5.5 0 0 0-.496-.868l-3.5 2L8 12.924l-3.252-1.858-3.5-2Z"
class="Union"
clip-rule="evenodd"
/>
</g>
<defs>
<filter
id="a"
width="24"
height="24"
x="-4"
y="-4"
class="a"
color-interpolation-filters="sRGB"
filterUnits="userSpaceOnUse"
>
<feFlood flood-opacity="0" result="BackgroundImageFix" />
<feGaussianBlur in="BackgroundImageFix" stdDeviation="2" />
<feComposite
in2="SourceAlpha"
operator="in"
result="effect1_backgroundBlur_84_50838"
/>
<feBlend
in="SourceGraphic"
in2="effect1_backgroundBlur_84_50838"
result="shape"
/>
</filter>
</defs>
</symbol>
<symbol id="mouseTool" fill="none" viewBox="0 0 16 16">
<g clip-path="url(#a)">
<path
fill="var(--icon-stroke)"
fill-rule="evenodd"
d="M.646.646a.5.5 0 0 0-.119.517l4.828 14a.5.5 0 0 0 .927.046L9.1 9.102l1.781-.823 4.328-1.996a.5.5 0 0 0-.047-.927l-14-4.828a.5.5 0 0 0-.517.12Zm7.478 8.185-2.23 4.83L1.808 1.807l11.854 4.088-3.198 1.475-1.632.754-2.167-2.167a.5.5 0 1 0-.707.707L8.124 8.83Z"
clip-rule="evenodd"
/>
</g>
<defs>
<clipPath id="a">
<path fill="#fff" d="M16 0H0v16h16z" />
</clipPath>
</defs>
</symbol>
<symbol id="textTool" fill="none" viewBox="0 0 16 16">
<path
fill="var(--icon-stroke)"
fill-rule="evenodd"
d="M5.6 1.5a.5.5 0 0 0 0 1 1.9 1.9 0 0 1 1.9 1.9v7.221A1.9 1.9 0 0 1 5.6 13.5a.5.5 0 0 0 0 1A2.9 2.9 0 0 0 8 13.228a2.9 2.9 0 0 0 2.4 1.272.5.5 0 1 0 0-1 1.9 1.9 0 0 1-1.9-1.9V4.379A1.9 1.9 0 0 1 10.4 2.5a.5.5 0 1 0 0-1A2.9 2.9 0 0 0 8 2.772 2.9 2.9 0 0 0 5.6 1.5Z"
clip-rule="evenodd"
/>
</symbol>
<symbol id="tableTool" fill="none" viewBox="0 0 16 16">
<path
fill="var(--icon-stroke)"
fill-rule="evenodd"
d="M4.5 2h-1A1.5 1.5 0 0 0 2 3.5v9A1.5 1.5 0 0 0 3.5 14h1V2ZM5 1H3.5A2.5 2.5 0 0 0 1 3.5v9A2.5 2.5 0 0 0 3.5 15h9a2.5 2.5 0 0 0 2.5-2.5v-9A2.5 2.5 0 0 0 12.5 1H5Zm.5 1v3H14V3.5A1.5 1.5 0 0 0 12.5 2h-7Zm0 4v3.5H14V6H5.5Zm0 4.5V14h7a1.5 1.5 0 0 0 1.5-1.5v-2H5.5Z"
clip-rule="evenodd"
/>
</symbol>
<symbol id="imageTool" fill="none" viewBox="0 0 16 16">
<path
fill="var(--icon-stroke)"
fill-rule="evenodd"
d="M12.5 2.5h-9A1.5 1.5 0 0 0 2 4v8a1.5 1.5 0 0 0 1.102 1.447.502.502 0 0 1 .053-.06l6.429-6.112a.9.9 0 0 1 1.1-.11L14 9.252V4a1.5 1.5 0 0 0-1.5-1.5Zm0 11H4.488l5.729-5.447 3.767 2.37.016.01V12a1.5 1.5 0 0 1-1.5 1.5Zm-9-12h9A2.5 2.5 0 0 1 15 4v8a2.5 2.5 0 0 1-2.5 2.5h-9A2.5 2.5 0 0 1 1 12V4a2.5 2.5 0 0 1 2.5-2.5ZM6 5.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0ZM5.25 7.5a1.75 1.75 0 1 0 0-3.5 1.75 1.75 0 0 0 0 3.5Z"
clip-rule="evenodd"
/>
</symbol>
<symbol id="rectangleTool" fill="none" viewBox="0 0 16 16">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M12.5 2H3.5C2.67157 2 2 2.67157 2 3.5V12.5C2 13.3284 2.67157 14 3.5 14H12.5C13.3284 14 14 13.3284 14 12.5V3.5C14 2.67157 13.3284 2 12.5 2ZM3.5 1C2.11929 1 1 2.11929 1 3.5V12.5C1 13.8807 2.11929 15 3.5 15H12.5C13.8807 15 15 13.8807 15 12.5V3.5C15 2.11929 13.8807 1 12.5 1H3.5Z"
fill="var(--icon-stroke)"
/>
</symbol>
<symbol id="barcodeTool" fill="none" viewBox="0 0 16 16">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M0.5 4C0.776142 4 1 4.18172 1 4.40588V12.2191C1 12.4433 0.776142 12.625 0.5 12.625C0.223858 12.625 0 12.4433 0 12.2191V4.40588C0 4.18172 0.223858 4 0.5 4Z"
fill="var(--icon-stroke)"
/>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M2.12354 4C2.39968 4 2.62354 4.18172 2.62354 4.40588V12.2191C2.62354 12.4433 2.39968 12.625 2.12354 12.625C1.84739 12.625 1.62354 12.4433 1.62354 12.2191V4.40588C1.62354 4.18172 1.84739 4 2.12354 4Z"
fill="var(--icon-stroke)"
/>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M5.25293 4C5.52907 4 5.75293 4.18172 5.75293 4.40588V12.2191C5.75293 12.4433 5.52907 12.625 5.25293 12.625C4.97679 12.625 4.75293 12.4433 4.75293 12.2191V4.40588C4.75293 4.18172 4.97679 4 5.25293 4Z"
fill="var(--icon-stroke)"
/>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M6.87646 4C7.15261 4 7.37646 4.18172 7.37646 4.40588V12.2191C7.37646 12.4433 7.15261 12.625 6.87646 12.625C6.60032 12.625 6.37646 12.4433 6.37646 12.2191V4.40588C6.37646 4.18172 6.60032 4 6.87646 4Z"
fill="var(--icon-stroke)"
/>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M8.5 4C8.77614 4 9 4.18172 9 4.40588V12.2191C9 12.4433 8.77614 12.625 8.5 12.625C8.22386 12.625 8 12.4433 8 12.2191V4.40588C8 4.18172 8.22386 4 8.5 4Z"
fill="var(--icon-stroke)"
/>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M10.9351 4C11.2112 4 11.4351 4.18172 11.4351 4.40588V12.2191C11.4351 12.4433 11.2112 12.625 10.9351 12.625C10.6589 12.625 10.4351 12.4433 10.4351 12.2191V4.40588C10.4351 4.18172 10.6589 4 10.9351 4Z"
fill="var(--icon-stroke)"
/>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M12.5586 4C12.8347 4 13.0586 4.18172 13.0586 4.40588V12.2191C13.0586 12.4433 12.8347 12.625 12.5586 12.625C12.2825 12.625 12.0586 12.4433 12.0586 12.2191V4.40588C12.0586 4.18172 12.2825 4 12.5586 4Z"
fill="var(--icon-stroke)"
/>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M14.9941 4C15.2703 4 15.4941 4.18172 15.4941 4.40588V12.2191C15.4941 12.4433 15.2703 12.625 14.9941 12.625C14.718 12.625 14.4941 12.4433 14.4941 12.2191V4.40588C14.4941 4.18172 14.718 4 14.9941 4Z"
fill="var(--icon-stroke)"
/>
</symbol>
<symbol id="alignTop">
<path
d="M2.1,1H21.9m1,0a1,1,0,0,0-1-1H2.1a1,1,0,0,0,0,1.94H21.9A1,1,0,0,0,22.87,1Zm-3.09,14v-10A.81.81,0,0,0,19,4.1H14.88a.8.8,0,0,0-.8.81v10a.8.8,0,0,0,.8.8H19A.8.8,0,0,0,19.78,14.92Zm1,0v-10A1.76,1.76,0,0,0,19,3.13H14.86A1.76,1.76,0,0,0,13.1,4.89V14.94a1.76,1.76,0,0,0,1.76,1.76H19A1.76,1.76,0,0,0,20.75,14.94Zm-5.7-9.87h3.76v9.68H15.05ZM10.64,22.22V4.91a.8.8,0,0,0-.8-.81H5.75a.81.81,0,0,0-.81.81V22.22a.81.81,0,0,0,.81.81H9.84A.8.8,0,0,0,10.64,22.22Zm1,0V4.89A1.76,1.76,0,0,0,9.86,3.13H5.72A1.76,1.76,0,0,0,4,4.89V22.25A1.76,1.76,0,0,0,5.72,24H9.86A1.76,1.76,0,0,0,11.62,22.25ZM5.91,5.07H9.67v17H5.91Z"
/>
</symbol>
<symbol id="alignBottom">
<path
d="M2.1,23H21.9m0-1H2.1A1,1,0,0,0,2.1,24H21.9a1,1,0,0,0,0-1.94ZM19,8.28H14.88a.8.8,0,0,0-.8.8v10a.8.8,0,0,0,.8.81H19a.81.81,0,0,0,.81-.81v-10A.8.8,0,0,0,19,8.28Zm0-1H14.86A1.76,1.76,0,0,0,13.1,9.06v10a1.76,1.76,0,0,0,1.76,1.76H19a1.76,1.76,0,0,0,1.75-1.76v-10A1.76,1.76,0,0,0,19,7.3Zm-3.95,2h3.76v9.68H15.05ZM9.84,1H5.75a.81.81,0,0,0-.81.81V19.09a.81.81,0,0,0,.81.81H9.84a.8.8,0,0,0,.8-.81V1.78A.8.8,0,0,0,9.84,1Zm0-1H5.72A1.76,1.76,0,0,0,4,1.75V19.11a1.76,1.76,0,0,0,1.75,1.76H9.86a1.76,1.76,0,0,0,1.76-1.76V1.75A1.76,1.76,0,0,0,9.86,0ZM5.91,1.94H9.67v17H5.91Z"
/>
</symbol>
<symbol id="alignLeft">
<path
d="M.84,22V2m0-1a1,1,0,0,0-1,1V22a1,1,0,0,0,2,0V2A1,1,0,0,0,.84,1ZM15,4.13H4.82A.81.81,0,0,0,4,4.94V9.1a.8.8,0,0,0,.81.8H15a.8.8,0,0,0,.81-.8V4.94A.81.81,0,0,0,15,4.13Zm0-1H4.8A1.77,1.77,0,0,0,3,4.92V9.11A1.77,1.77,0,0,0,4.8,10.88H15a1.77,1.77,0,0,0,1.77-1.77V4.92A1.77,1.77,0,0,0,15,3.15ZM5,8.92V5.11h9.79V8.92Zm17.36,4.45H4.82a.81.81,0,0,0-.81.81v4.16a.8.8,0,0,0,.81.8H22.35a.8.8,0,0,0,.81-.8V14.18A.81.81,0,0,0,22.35,13.37Zm0-1H4.8A1.77,1.77,0,0,0,3,14.16v4.19A1.77,1.77,0,0,0,4.8,20.12H22.36a1.78,1.78,0,0,0,1.78-1.77V14.16A1.78,1.78,0,0,0,22.36,12.39ZM5,18.16V14.35H22.17v3.81Z"
/>
</symbol>
<symbol id="alignRight">
<path
d="M23.16,2V22m-1-20V22a1,1,0,0,0,2,0V2a1,1,0,0,0-2,0Zm-13.94,3V9.1A.8.8,0,0,0,9,9.9H19.18A.8.8,0,0,0,20,9.1V4.94a.81.81,0,0,0-.81-.81H9A.81.81,0,0,0,8.23,4.94Zm-1,0V9.11A1.77,1.77,0,0,0,9,10.88H19.2A1.77,1.77,0,0,0,21,9.11V4.92A1.77,1.77,0,0,0,19.2,3.15H9A1.77,1.77,0,0,0,7.25,4.92Zm2,4V5.11H19V8.92ZM.84,14.18v4.16a.8.8,0,0,0,.81.8H19.18a.8.8,0,0,0,.81-.8V14.18a.81.81,0,0,0-.81-.81H1.65A.81.81,0,0,0,.84,14.18Zm-1,0v4.19a1.78,1.78,0,0,0,1.78,1.77H19.2A1.77,1.77,0,0,0,21,18.35V14.16a1.77,1.77,0,0,0-1.77-1.77H1.64A1.78,1.78,0,0,0-.14,14.16Zm2,4V14.35H19v3.81Z"
/>
</symbol>
<symbol id="alignVerticalCenter">
<path
d="M2.1,12H21.9M24,12a1,1,0,0,0-1.07-1H1.07a1,1,0,1,0,0,1.94H22.93A1,1,0,0,0,24,12Zm-4.22,5V7a.8.8,0,0,0-.81-.8H14.88a.8.8,0,0,0-.8.8V17a.8.8,0,0,0,.8.8H19A.8.8,0,0,0,19.78,17Zm1,0V7A1.75,1.75,0,0,0,19,5.22H14.86A1.75,1.75,0,0,0,13.1,7V17a1.75,1.75,0,0,0,1.76,1.75H19A1.75,1.75,0,0,0,20.75,17Zm-5.7-9.87h3.76v9.68H15.05Zm-4.41,13.5V3.34a.8.8,0,0,0-.8-.8H5.75a.8.8,0,0,0-.81.8V20.66a.8.8,0,0,0,.81.8H9.84A.8.8,0,0,0,10.64,20.66Zm1,0V3.32A1.75,1.75,0,0,0,9.86,1.57H5.72A1.75,1.75,0,0,0,4,3.32V20.68a1.75,1.75,0,0,0,1.75,1.75H9.86A1.75,1.75,0,0,0,11.62,20.68ZM5.91,3.51H9.67v17H5.91Z"
/>
</symbol>
<symbol id="alignHorizontalCenter">
<path
d="M12,22.93V1.07M12,0a1,1,0,0,0-1,1.07V22.93a1,1,0,1,0,1.94,0V1.07A1,1,0,0,0,12,0Zm5,4.22H7a.8.8,0,0,0-.8.81V9.12a.8.8,0,0,0,.8.8H17a.8.8,0,0,0,.8-.8V5A.8.8,0,0,0,17,4.22Zm0-1H7A1.75,1.75,0,0,0,5.22,5V9.14A1.75,1.75,0,0,0,7,10.9H17a1.75,1.75,0,0,0,1.75-1.76V5A1.75,1.75,0,0,0,17,3.25ZM7.16,9V5.19h9.68V9Zm13.5,4.41H3.34a.8.8,0,0,0-.8.8v4.09a.8.8,0,0,0,.8.81H20.66a.8.8,0,0,0,.8-.81V14.16A.8.8,0,0,0,20.66,13.36Zm0-1H3.32a1.75,1.75,0,0,0-1.75,1.76v4.14A1.75,1.75,0,0,0,3.32,20H20.68a1.75,1.75,0,0,0,1.75-1.75V14.14A1.75,1.75,0,0,0,20.68,12.38ZM3.51,18.09V14.33h17v3.76Z"
/>
</symbol>
<symbol id="textAlignLeft">
<path
d="M22,18.54H2.05a.94.94,0,1,1,0-1.87H22a.94.94,0,1,1,0,1.87ZM15,12a1,1,0,0,0-1-.93H2.05a.94.94,0,1,0,0,1.86H14A1,1,0,0,0,15,12Zm0,11.21a1,1,0,0,0-1-.93H2.05a.94.94,0,1,0,0,1.86H14A1,1,0,0,0,15,23.21ZM23,6.39A1,1,0,0,0,22,5.46H2.05a1,1,0,0,0-1,.93,1,1,0,0,0,1,.94H22A1,1,0,0,0,23,6.39ZM15,.79a1,1,0,0,0-1-.93H2.05A1,1,0,0,0,1,.79a1,1,0,0,0,1,.93H14A1,1,0,0,0,15,.79Z"
/>
</symbol>
<symbol id="textAlignCenter">
<path
d="M22,18.42H2.05a.93.93,0,1,1,0-1.84H22a.93.93,0,1,1,0,1.84ZM19,12A1,1,0,0,0,18,11.08H6A1,1,0,0,0,5,12a1,1,0,0,0,1,.92H18A1,1,0,0,0,19,12Zm0,11A1,1,0,0,0,18,22.08H6a.93.93,0,1,0,0,1.84H18A1,1,0,0,0,19,23ZM23,6.5A1,1,0,0,0,22,5.58H2.05A1,1,0,0,0,1,6.5a1,1,0,0,0,1,.92H22A1,1,0,0,0,23,6.5ZM19,1A1,1,0,0,0,18,.08H6A1,1,0,0,0,5,1a1,1,0,0,0,1,.92H18A1,1,0,0,0,19,1Z"
/>
</symbol>
<symbol id="textAlignRight">
<path
d="M22,18.42H2.05a.93.93,0,1,1,0-1.84H22a.93.93,0,1,1,0,1.84ZM23,12A1,1,0,0,0,22,11.08H10A1,1,0,0,0,9,12a1,1,0,0,0,1,.92H22A1,1,0,0,0,23,12Zm0,11A1,1,0,0,0,22,22.08H10a.93.93,0,1,0,0,1.84H22A1,1,0,0,0,23,23ZM23,6.5A1,1,0,0,0,22,5.58H2.05A1,1,0,0,0,1,6.5a1,1,0,0,0,1,.92H22A1,1,0,0,0,23,6.5ZM23,1A1,1,0,0,0,22,.08H10A1,1,0,0,0,9,1a1,1,0,0,0,1,.92H22A1,1,0,0,0,23,1Z"
/>
</symbol>
<symbol id="textAlignJustify">
<path
d="M22,1.92H2.05A1,1,0,0,1,1,1a1,1,0,0,1,1-.92H22A1,1,0,0,1,23,1,1,1,0,0,1,22,1.92ZM23,6.5A1,1,0,0,0,22,5.58H2.05A1,1,0,0,0,1,6.5a1,1,0,0,0,1,.92H22A1,1,0,0,0,23,6.5ZM23,12A1,1,0,0,0,22,11.08H2.05A1,1,0,0,0,1,12a1,1,0,0,0,1,.92H22A1,1,0,0,0,23,12Zm0,5.5A1,1,0,0,0,22,16.58H2.05a.93.93,0,1,0,0,1.84H22A1,1,0,0,0,23,17.5ZM23,23A1,1,0,0,0,22,22.08H2.05a.93.93,0,1,0,0,1.84H22A1,1,0,0,0,23,23Z"
/>
</symbol>
<symbol id="fontSize">
<path
d="M.2,5.53V2H17.05V5.53H10.82V21.78H6.43V5.53Zm12.74,7.08V10.07H23.8v2.54H20.05V22H16.68V12.61Z"
/>
</symbol>
<symbol id="lineHeight">
<path
d="M23.24,4.73H9.92a.76.76,0,1,1,0-1.52H23.24a.76.76,0,0,1,0,1.52ZM24,12a.76.76,0,0,0-.76-.75H9.92a.76.76,0,1,0,0,1.51H23.24A.76.76,0,0,0,24,12Zm0,7.61a.76.76,0,0,0-.76-.76H9.92a.76.76,0,1,0,0,1.52H23.24A.76.76,0,0,0,24,19.6ZM3.17,2.82.3,6a.28.28,0,0,0,.21.46H6.24A.28.28,0,0,0,6.45,6L3.58,2.82A.28.28,0,0,0,3.17,2.82ZM6.68,6.38a.75.75,0,0,0-.13-.83L4,2.66a.81.81,0,0,0-1.15,0L.2,5.55a.75.75,0,0,0-.13.83.76.76,0,0,0,.71.46H6A.75.75,0,0,0,6.68,6.38ZM3.39,3.17,6,6.08l-5.21,0,2.6-2.89-.28-.25Zm.19,18L6.45,18a.28.28,0,0,0-.21-.46H.51A.28.28,0,0,0,.3,18l2.87,3.18A.28.28,0,0,0,3.58,21.17Zm.37.16,2.6-2.89A.77.77,0,0,0,6,17.15H.78a.74.74,0,0,0-.71.46.75.75,0,0,0,.13.83l2.6,2.89a.79.79,0,0,0,1.15,0Zm2-3.4-2.6,2.89.28.25-.31-.25L.78,17.91Zm-2-13H2.73V17.15H4Zm.38-.38H2.35v13H4.4Zm-1.29.76h.53V16.77H3.11Z"
/>
</symbol>
<symbol id="borderRadius">
<path
d="M2.05,23.6a2,2,0,0,1-2-2V8.16A7.77,7.77,0,0,1,7.72.4H22a2,2,0,1,1,0,4.09H7.74A3.68,3.68,0,0,0,4.1,8.16v13.4A2,2,0,0,1,2.05,23.6Z"
/>
</symbol>
<symbol id="fontItalic">
<path
d="M16.48,3.45,12.09,20.52h4.45L15.62,24h-13l.92-3.48h4.1L12.06,3.45H7.8L8.64,0H21.41l-.92,3.45Z"
/>
</symbol>
<symbol id="fontUnderLine">
<path
d="M16.23,0h3.42V12.31a6.71,6.71,0,0,1-.95,3.57A6.49,6.49,0,0,1,16,18.27a8.79,8.79,0,0,1-4,.86,8.83,8.83,0,0,1-4-.86A6.4,6.4,0,0,1,5.3,15.88a6.71,6.71,0,0,1-1-3.57V0H7.77V12a4.19,4.19,0,0,0,.52,2.1,3.68,3.68,0,0,0,1.46,1.44,4.7,4.7,0,0,0,2.25.52,4.7,4.7,0,0,0,2.25-.52,3.64,3.64,0,0,0,1.47-1.44,4.29,4.29,0,0,0,.51-2.1ZM2.49,24V21h19v3Z"
/>
</symbol>
<symbol id="letterSpacing">
<path
d="M5.68,11.11H9.94l.94,2.79h2.2l-4-11.34H6.54l-4,11.34H4.74ZM7.77,4.89h.08L9.39,9.46H6.23Zm7.71,8.89a3.8,3.8,0,0,0,2.61.11,2.63,2.63,0,0,0,.82-.49,2.43,2.43,0,0,0,.51-.67h.07V13.9h1.93V8.21a2.88,2.88,0,0,0-.31-1.41,2.35,2.35,0,0,0-.81-.9,3.91,3.91,0,0,0-1.11-.47A5.73,5.73,0,0,0,18,5.29a4.91,4.91,0,0,0-1.62.26,3.3,3.3,0,0,0-1.25.79,3,3,0,0,0-.73,1.3l1.87.26a1.61,1.61,0,0,1,.58-.76A1.92,1.92,0,0,1,18,6.82,1.54,1.54,0,0,1,19,7.16a1.26,1.26,0,0,1,.37,1v0a.46.46,0,0,1-.21.42,1.72,1.72,0,0,1-.68.2l-1.21.14a11.55,11.55,0,0,0-1.2.21,3.86,3.86,0,0,0-1,.43,2.1,2.1,0,0,0-.72.76,2.36,2.36,0,0,0-.27,1.19,2.5,2.5,0,0,0,.38,1.4A2.32,2.32,0,0,0,15.48,13.78Zm.74-2.93a1.37,1.37,0,0,1,.56-.39,4.25,4.25,0,0,1,.8-.2l.47-.06.55-.09a3.06,3.06,0,0,0,.5-.12.88.88,0,0,0,.32-.14v1a1.65,1.65,0,0,1-.24.87,1.71,1.71,0,0,1-.69.64,2.13,2.13,0,0,1-1,.24,1.74,1.74,0,0,1-1-.28,1,1,0,0,1-.41-.84A.92.92,0,0,1,16.22,10.85Zm7.7,7.84-2.67,2.67a.26.26,0,0,1-.45-.19V19.41H3.2v1.74a.28.28,0,0,1-.47.19L.08,18.69a.26.26,0,0,1,0-.38l2.65-2.66a.28.28,0,0,1,.47.2v1.74H20.8V15.83a.26.26,0,0,1,.45-.19l2.67,2.67A.26.26,0,0,1,23.92,18.69Z"
/>
</symbol>
<symbol id="borderWidth">
<path d="M23.75,5.75H.25V4.25h23.5Zm0,4H.25v2.5h23.5Zm0,6.5H.25v3.5h23.5Z" />
</symbol>
<symbol id="borderAll">
<rect
id="background"
x="2"
y="2"
width="20"
height="20"
style="fill: var(--gray-100)"
/>
<path
d="M23,0H1A1,1,0,0,0,0,1V23a1,1,0,0,0,1,1H23a1,1,0,0,0,1-1V1A1,1,0,0,0,23,0ZM22,22H2V2H22Z"
/>
</symbol>
<symbol id="borderLeftStyle">
<rect
id="background"
x="2"
y="2"
width="20"
height="20"
style="fill: var(--gray-100)"
/>
<path
id="mainBorder"
d="M24,23V1a1,1,0,0,0-1-1H2V2H22V22H2v2H23A1,1,0,0,0,24,23Z"
style="fill: var(--gray-300)"
/>
<path id="activeBorder" d="M2,2V0H1A1,1,0,0,0,0,1V23a1,1,0,0,0,1,1H2V2Z" />
</symbol>
<symbol id="borderRightStyle">
<rect
id="background"
x="2"
y="2"
width="20"
height="20"
style="fill: var(--gray-100)"
/>
<path
id="mainBorder"
d="M0,1V23a1,1,0,0,0,1,1H22V22H2V2H22V0H1A1,1,0,0,0,0,1Z"
style="fill: var(--gray-300)"
/>
<path id="activeBorder" d="M22,22v2h1a1,1,0,0,0,1-1V1a1,1,0,0,0-1-1H22V22Z" />
</symbol>
<symbol id="borderTopStyle">
<rect
id="background"
x="2"
y="2"
width="20"
height="20"
style="fill: var(--gray-100)"
/>
<path
id="mainBorder"
d="M1,24H23a1,1,0,0,0,1-1V2H22V22H2V2H0V23A1,1,0,0,0,1,24Z"
style="fill: var(--gray-300)"
/>
<path id="activeBorder" d="M22,2h2V1a1,1,0,0,0-1-1H1A1,1,0,0,0,0,1V2H22Z" />
</symbol>
<symbol id="borderBottomStyle">
<rect
id="background"
x="2"
y="2"
width="20"
height="20"
style="fill: var(--gray-100)"
/>
<path
id="mainBorder"
d="M23,0H1A1,1,0,0,0,0,1V22H2V2H22V22h2V1A1,1,0,0,0,23,0Z"
style="fill: var(--gray-300)"
/>
<path id="activeBorder" d="M2,22H0v1a1,1,0,0,0,1,1H23a1,1,0,0,0,1-1V22H2Z" />
</symbol>
</svg>
</template>
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/icons/Icons.vue
|
Vue
|
agpl-3.0
| 16,580
|
<template>
<svg
:viewBox="`0 0 24 24`"
:width="size"
:height="size"
:style="`padding: ${padding}px; margin-top: ${margin}px; margin-bottom: ${margin}px;`"
:class="class"
>
<use :href="`#${name}`" :style="`fill: ${color}; --icon-stroke:${color};`" />
</svg>
</template>
<script setup>
const props = defineProps({
name: {
type: String,
required: true,
},
size: {
type: Number,
default: 16,
},
padding: {
type: Number,
default: 0,
},
margin: {
type: Number,
default: 0,
},
color: {
default: "var(--neutral)",
},
class: {
type: String,
default: "",
},
});
</script>
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/icons/IconsUse.vue
|
Vue
|
agpl-3.0
| 612
|
export const pageSizes = {
A10: [26, 37],
A1: [594, 841],
A0: [841, 1189],
A3: [297, 420],
A2: [420, 594],
A5: [148, 210],
A4: [210, 297],
A7: [74, 105],
A6: [105, 148],
A9: [37, 52],
A8: [52, 74],
B10: [44, 31],
"B1+": [1020, 720],
B4: [353, 250],
B5: [250, 176],
B6: [176, 125],
B7: [125, 88],
B0: [1414, 1000],
B1: [1000, 707],
B2: [707, 500],
B3: [500, 353],
"B2+": [720, 520],
B8: [88, 62],
B9: [62, 44],
C10: [40, 28],
C9: [57, 40],
C8: [81, 57],
C3: [458, 324],
C2: [648, 458],
C1: [917, 648],
C0: [1297, 917],
C7: [114, 81],
C6: [162, 114],
C5: [229, 162],
C4: [324, 229],
Legal: [216, 356],
"Junior Legal": [127, 203],
Letter: [216, 279],
Tabloid: [279, 432],
Ledger: [432, 279],
"ANSI C": [432, 559],
"ANSI A (letter)": [216, 279],
"ANSI B (ledger & tabloid)": [279, 432],
"ANSI E": [864, 1118],
"ANSI D": [559, 864],
CUSTOM: ["*", "*"],
};
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/pageSizes.js
|
JavaScript
|
agpl-3.0
| 897
|
import { createApp } from "vue";
import { createPinia } from "pinia";
import Designer from "./App.vue";
class PrintDesigner {
constructor({ wrapper, print_format }) {
this.$wrapper = $(wrapper);
this.print_format = print_format;
const app = createApp(Designer, { print_format_name: this.print_format });
app.use(createPinia());
SetVueGlobals(app);
app.mount(this.$wrapper.get(0));
let headerContainer = document.querySelector("header .container");
headerContainer.style.width = "100%";
headerContainer.style.minWidth = "100%";
headerContainer.style.userSelect = "none";
frappe.router.once("change", () => {
headerContainer.style.width = null;
headerContainer.style.minWidth = null;
headerContainer.style.userSelect = "auto";
app.unmount();
});
}
}
frappe.provide("frappe.ui");
frappe.ui.PrintDesigner = PrintDesigner;
export default PrintDesigner;
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/print_designer.bundle.js
|
JavaScript
|
agpl-3.0
| 887
|
import { defineStore } from "pinia";
import { useMainStore } from "./MainStore";
import {
createText,
createRectangle,
createDynamicText,
createImage,
createTable,
createBarcode,
} from "../defaultObjects";
import {
handlePrintFonts,
setCurrentElement,
createHeaderFooterElement,
getParentPage,
} from "../utils";
import html2canvas from "html2canvas";
export const useElementStore = defineStore("ElementStore", {
state: () => ({
Elements: new Array(),
Headers: new Array(),
Footers: new Array(),
}),
actions: {
createNewObject(event, element) {
let newElement;
const MainStore = useMainStore();
if (MainStore.activeControl == "text") {
if (MainStore.textControlType == "static") {
newElement = createText(event, element);
} else {
newElement = createDynamicText(event, element);
}
} else if (MainStore.activeControl == "rectangle") {
newElement = createRectangle(event, element);
} else if (MainStore.activeControl == "image") {
newElement = createImage(event, element);
} else if (MainStore.activeControl == "table") {
newElement = createTable(event, element);
} else if (MainStore.activeControl == "barcode") {
newElement = createBarcode(event, element);
}
return newElement;
},
computeLayoutForSave() {
this.handleHeaderFooterOverlapping();
const { header, body, footer } = this.computeMainLayout();
// before modifying save json object that is used by loadElements and UI.
const objectToSave = {
print_designer_header: JSON.stringify(header || []),
print_designer_body: JSON.stringify(body),
print_designer_footer: JSON.stringify(footer || []),
print_designer_after_table: null,
};
const layout = {
header: [],
body: [],
footer: [],
};
let headerElements = [];
let bodyElements = [];
let footerElements = [];
if (header) {
const headerArray = header.map((h) => {
h.childrens = this.computeRowLayout(h.childrens, headerElements, "header");
return h;
});
layout.header = {
firstPage: headerArray.find((h) => h.firstPage).childrens,
oddPage: headerArray.find((h) => h.oddPage).childrens,
evenPage: headerArray.find((h) => h.evenPage).childrens,
lastPage: headerArray.find((h) => h.lastPage).childrens,
};
}
// it will throw error if body is empty so no need to check here
layout.body = body.map((b) => {
b.childrens = this.computeRowLayout(b.childrens, bodyElements, "body");
return b;
});
if (footer) {
const footerArray = footer.map((f) => {
f.childrens = this.computeRowLayout(f.childrens, footerElements, "footer");
return f;
});
layout.footer = {
firstPage: footerArray.find((h) => h.firstPage).childrens,
oddPage: footerArray.find((h) => h.oddPage).childrens,
evenPage: footerArray.find((h) => h.evenPage).childrens,
lastPage: footerArray.find((h) => h.lastPage).childrens,
};
}
// WARNING: lines below are for debugging purpose only.
// this.Elements.length = 0;
// this.Headers.length = 0;
// this.Footers.length = 0;
// this.Headers.push(...header);
// this.Elements.push(...body);
// this.Footers.push(...footer);
// this.Elements.forEach((page, index) => {
// page.header = [createHeaderFooterElement(this.getHeaderObject(index).childrens, "header")];
// page.footer = [createHeaderFooterElement(this.getFooterObject(index).childrens, "footer")]
// });
// End of debugging code
objectToSave.print_designer_print_format = JSON.stringify(layout);
// update fonts in store
const MainStore = useMainStore();
MainStore.currentFonts.length = 0;
MainStore.currentFonts.push(
...Object.keys({
...(MainStore.printHeaderFonts || {}),
...(MainStore.printBodyFonts || {}),
...(MainStore.printFooterFonts || {}),
})
);
return objectToSave;
},
// This is modified version of upload function used in frappe/FileUploader.vue
async upload_file(file) {
const MainStore = useMainStore();
MainStore.print_designer_preview_img = null;
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState == XMLHttpRequest.DONE) {
if (xhr.status === 200) {
try {
r = JSON.parse(xhr.responseText);
if (r.message.doctype === "File") {
file_url = r.message.file_url;
frappe.db.set_value(
"Print Format",
MainStore.printDesignName,
"print_designer_preview_img",
file_url
);
}
} catch (e) {
r = xhr.responseText;
}
}
}
};
xhr.open("POST", "/api/method/upload_file", true);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("X-Frappe-CSRF-Token", frappe.csrf_token);
let form_data = new FormData();
if (file.file_obj) {
form_data.append("file", file.file_obj, file.name);
}
form_data.append("is_private", 1);
form_data.append("doctype", "Print Format");
form_data.append("docname", MainStore.printDesignName);
form_data.append("fieldname", "print_designer_preview_img");
if (file.optimize) {
form_data.append("optimize", true);
}
xhr.send(form_data);
});
},
async generatePreview() {
const MainStore = useMainStore();
// first delete old preview image
const filter = {
attached_to_doctype: "Print Format",
attached_to_name: MainStore.printDesignName,
attached_to_field: "print_designer_preview_img",
};
// get filename before uploading new file
let old_filename = await frappe.db.get_value("File", filter, "name");
old_filename = old_filename.message.name;
if (old_filename) {
frappe.db.delete_doc("File", old_filename);
}
const options = {
backgroundColor: "#ffffff",
height: MainStore.page.height,
width: MainStore.page.width,
};
const print_stylesheet = document.createElement("style");
print_stylesheet.rel = "stylesheet";
let st = `.main-container::after {
display: none;
}`;
document.getElementsByClassName("main-container")[0].appendChild(print_stylesheet);
print_stylesheet.sheet.insertRule(st, 0);
const preview_canvas = await html2canvas(
document.getElementsByClassName("main-container")[0],
options
);
document.getElementsByClassName("main-container")[0].removeChild(print_stylesheet);
preview_canvas.toBlob(async (blob) => {
const file = new File(
[blob],
`print_designer-${frappe.scrub(MainStore.printDesignName)}-preview.jpg`,
{ type: "image/jpeg" }
);
const file_data = {
file_obj: file,
optimize: 1,
name: file.name,
private: true,
};
await this.upload_file(file_data);
});
},
async saveElements() {
const MainStore = useMainStore();
if (this.checkIfAnyTableIsEmpty()) return;
let is_standard = await frappe.db.get_value(
"Print Format",
MainStore.printDesignName,
"standard"
);
MainStore.is_standard = is_standard.message.standard == "Yes";
// Update the header and footer height with margin
MainStore.page.headerHeightWithMargin =
MainStore.page.headerHeight + MainStore.page.marginTop;
MainStore.page.footerHeightWithMargin =
MainStore.page.footerHeight + MainStore.page.marginBottom;
const objectToSave = this.computeLayoutForSave();
if (!objectToSave) return;
const updatedPage = { ...MainStore.page };
const settingsForSave = {
page: updatedPage,
pdfPrintDPI: MainStore.pdfPrintDPI,
globalStyles: MainStore.globalStyles,
currentPageSize: MainStore.currentPageSize,
isHeaderFooterAuto: MainStore.isHeaderFooterAuto,
currentDoc: MainStore.currentDoc,
textControlType: MainStore.textControlType,
currentFonts: MainStore.currentFonts,
printHeaderFonts: MainStore.printHeaderFonts,
printFooterFonts: MainStore.printFooterFonts,
printBodyFonts: MainStore.printBodyFonts,
userProvidedJinja: MainStore.userProvidedJinja,
schema_version: MainStore.schema_version,
};
const convertCsstoString = (stylesheet) => {
let cssRule = Array.from(stylesheet.cssRules)
.map((rule) => rule.cssText || "")
.join(" ");
return stylesheet.cssRules ? cssRule : "";
};
const css =
convertCsstoString(MainStore.screenStyleSheet) +
convertCsstoString(MainStore.printStyleSheet);
objectToSave.print_designer_settings = JSON.stringify(settingsForSave);
objectToSave.print_designer_after_table = null;
objectToSave.css = css;
if (MainStore.isOlderSchema("1.3.0")) {
await this.printFormatCopyOnOlderSchema(objectToSave);
} else {
await frappe.db.set_value("Print Format", MainStore.printDesignName, objectToSave);
frappe.show_alert(
{
message: `Print Format Saved Successfully`,
indicator: "green",
},
5
);
await this.generatePreview();
}
},
checkIfAnyTableIsEmpty() {
const emptyTable = this.Elements.find((el) => el.type == "table" && el.table == null);
if (emptyTable) {
let message = __("You have Empty Table. Please add table fields or remove table.");
setCurrentElement({}, emptyTable);
frappe.show_alert(
{
message: message,
indicator: "red",
},
5
);
return true;
}
return false;
},
computeMainLayout() {
let header = [];
let body = [];
let footer = [];
const pages = [...this.Elements];
const headerArray = [...this.Headers];
const footerArray = [...this.Footers];
headerArray.forEach((h) => {
const headerCopy = { ...h };
delete headerCopy.DOMRef;
delete headerCopy.parent;
h.childrens = this.cleanUpElementsForSave(h.childrens, "header") || [];
header.push(headerCopy);
});
pages.forEach((page) => {
const pageCopy = { ...page };
delete pageCopy.DOMRef;
delete pageCopy.parent;
delete pageCopy.header;
delete pageCopy.footer;
pageCopy.childrens.sort((a, b) => {
return a.startY < b.startY ? -1 : 1;
});
pageCopy.childrens = this.cleanUpElementsForSave(pageCopy.childrens, "body");
body.push(pageCopy);
});
footerArray.forEach((f) => {
const footerCopy = { ...f };
delete footerCopy.DOMRef;
delete footerCopy.parent;
footerCopy.childrens = this.cleanUpElementsForSave(f.childrens, "footer") || [];
footer.push(footerCopy);
});
return { header, body, footer };
},
// TODO: Refactor this function
computeRowLayout(column, parentContainer = null, type = "row") {
const MainStore = useMainStore();
const rowElements = [];
let prevDimension = null;
column.sort((a, b) => (a.startY < b.startY ? -1 : 1));
const rows = column.reduce((currentRow, currentEl) => {
if (currentRow.length == 0) {
currentRow.push(currentEl);
return currentRow;
}
// replace with .at() after checking compatibility for our user base.
const el = currentRow.at(-1);
const currentStartY = parseInt(currentEl.startY);
const currentEndY = parseInt(currentEl.startY + currentEl.height);
const maxEndY = parseInt(el.startY + el.height);
if (currentStartY >= maxEndY) {
const dimension = this.computeRowElementDimensions(
currentRow,
rowElements.length,
prevDimension,
type
);
prevDimension = dimension;
const wrapper = this.createRowWrapperElement(
dimension,
currentRow,
parentContainer
);
rowElements.push(wrapper);
currentRow.length = 0;
currentRow.push(currentEl);
return currentRow;
}
if (currentEndY > maxEndY) {
currentRow.push(currentEl);
} else {
currentRow.splice(-1, 0, currentEl);
}
return currentRow;
}, []);
// don't create row if it is there is only one row and parent is column
if (parentContainer?.layoutType == "column" && rowElements.length == 0) {
return;
}
if (rows.length != 0) {
const dimension = this.computeRowElementDimensions(
rows,
rowElements.length,
prevDimension,
type
);
if (parentContainer.layoutType == "column") {
dimension.bottom = parentContainer.height;
}
prevDimension = dimension;
const wrapper = this.createRowWrapperElement(dimension, rows, parentContainer);
rowElements.push(wrapper);
}
rowElements.sort((a, b) => (a.startY < b.startY ? -1 : 1));
if (type == "header" && rowElements.length) {
const lastHeaderRow = rowElements[rowElements.length - 1];
lastHeaderRow.height =
MainStore.page.headerHeight - MainStore.page.marginTop - lastHeaderRow.startY;
} else if (type == "footer" && rowElements.length) {
const lastFooterRow = rowElements[rowElements.length - 1];
lastFooterRow.height = MainStore.page.footerHeight - lastFooterRow.startY;
}
return rowElements;
},
// TODO: extract repeated code to a function
computeColumnLayout(row, parentContainer) {
const columnElements = [];
let prevDimension = null;
row.sort((a, b) => (a.startX < b.startX ? -1 : 1));
const columns = row.reduce((currentColumn, currentEl) => {
if (currentColumn.length == 0) {
currentColumn.push(currentEl);
return currentColumn;
}
const el = currentColumn.at(-1);
const currentStartX = parseInt(currentEl.startX);
const currentEndX = parseInt(currentEl.startX + currentEl.width);
const maxEndX = parseInt(el.startX + el.width);
if (currentStartX >= maxEndX) {
const dimension = this.computeColumnElementDimensions(
currentColumn,
columnElements.length,
prevDimension
);
prevDimension = dimension;
const wrapper = this.createColumnWrapperElement(
dimension,
currentColumn,
parentContainer
);
columnElements.push(wrapper);
currentColumn.length = 0;
currentColumn.push(currentEl);
return currentColumn;
}
if (currentEndX > maxEndX) {
currentColumn.push(currentEl);
} else {
currentColumn.splice(-1, 0, currentEl);
}
return currentColumn;
}, []);
if (columnElements.length == 0) {
return;
}
if (columns.length != 0) {
// column is defined so now run row layout
const dimension = this.computeColumnElementDimensions(
columns,
columnElements.length,
prevDimension
);
// if parent is row then set right to parent width else page width
if (parentContainer.layoutType == "row") {
dimension.right = parentContainer.width;
} else {
dimension.right =
MainStore.page.width -
MainStore.page.marginLeft -
MainStore.page.marginRight;
}
prevDimension = dimension;
const wrapper = this.createColumnWrapperElement(
dimension,
columns,
parentContainer
);
columnElements.push(wrapper);
}
return columnElements;
},
computeLayoutInsideRectangle(childElements) {
if (childElements.at(-1).type == "rectangle") {
const el = childElements.at(-1);
if (el.type == "rectangle") {
el.childrens = this.computeRowLayout(el.childrens, el);
el.layoutType = "column";
el.classes = el.classes.filter((c) => c != "relative-column");
el.rectangleContainer = true;
if (el.childrens.some((e) => e.heightType == "auto-min-height")) {
el.heightType = "auto-min-height";
} else if (el.childrens.some((e) => e.heightType == "auto")) {
el.heightType = "auto";
} else {
el.heightType = "fixed";
}
}
}
},
handleHeaderFooterOverlapping() {
const elements = this.Elements;
const MainStore = useMainStore();
const throwOverlappingError = (type) => {
let message = __(`Please resolve overlapping elements `);
const messageType = Object.freeze({
header: "<b>" + __("in header") + "</b>",
footer: "<b>" + __("in footer") + "</b>",
auto: __("in table, auto layout failed"),
});
message += messageType[type];
frappe.show_alert(
{
message: message,
indicator: "red",
},
6
);
throw new Error(message);
};
const tableElement = this.Elements.filter((el) => el.type == "table");
if (tableElement.length == 1 && MainStore.isHeaderFooterAuto) {
if (!this.autoCalculateHeaderFooter(tableElement[0])) {
throwOverlappingError("auto");
}
} else {
elements.forEach((element) => {
if (
element.startY < MainStore.page.headerHeight &&
element.startY + element.height > MainStore.page.headerHeight
) {
throwOverlappingError("header");
} else if (
element.startY <
MainStore.page.height -
MainStore.page.footerHeight -
MainStore.page.marginTop -
MainStore.page.marginBottom &&
element.startY + element.height >
MainStore.page.height -
MainStore.page.footerHeight -
MainStore.page.marginTop -
MainStore.page.marginBottom
) {
throwOverlappingError("footer");
}
});
}
},
autoCalculateHeaderFooter(tableEl) {
const MainStore = useMainStore();
if (this.isElementOverlapping(tableEl)) return false;
MainStore.page.headerHeight = tableEl.startY - 1;
MainStore.page.footerHeight =
MainStore.page.height +
1 -
(tableEl.startY +
tableEl.height +
MainStore.page.marginTop +
MainStore.page.marginBottom);
return true;
},
computeRowElementDimensions(row, index, prevDimensions = null, containerType = "row") {
const MainStore = useMainStore();
if (!prevDimensions) {
prevDimensions = {
left:
MainStore.page.width -
MainStore.page.marginRight -
MainStore.page.marginLeft,
bottom: 0,
};
}
return this.calculateWrapperElementDimensions(
prevDimensions,
row,
containerType,
index
);
},
computeColumnElementDimensions(column, index, prevDimensions = null) {
if (!prevDimensions) {
prevDimensions = {
right: 0,
};
}
return this.calculateWrapperElementDimensions(prevDimensions, column, "column", index);
},
// TODO: move logic to computeRowElementDimensions
calculateWrapperElementDimensions(prevDimensions, children, containerType, index) {
// basically returns lowest left - top highest right - bottom from all of the children elements
const MainStore = useMainStore();
const parentRect = {
top: 0,
left: 0,
width:
MainStore.page.width - MainStore.page.marginLeft - MainStore.page.marginRight,
height:
MainStore.page.height - MainStore.page.marginTop - MainStore.page.marginBottom,
};
let offsetRect = children.reduce(
(offset, currentElement) => {
let currentElementRect = {
top: currentElement.startY,
left: currentElement.startX,
right: currentElement.startX + currentElement.width,
bottom: currentElement.startY + currentElement.height,
};
currentElementRect.left < offset.left &&
(offset.left = currentElementRect.left);
currentElementRect.top < offset.top && (offset.top = currentElementRect.top);
currentElementRect.right > offset.right &&
(offset.right = currentElementRect.right);
currentElementRect.bottom > offset.bottom &&
(offset.bottom = currentElementRect.bottom);
return offset;
},
{ left: 9999, top: 9999, right: 0, bottom: 0 }
);
(offsetRect.top -= parentRect.top), (offsetRect.left -= parentRect.left);
(offsetRect.right -= parentRect.left), (offsetRect.bottom -= parentRect.top);
if (containerType == "header" && index == 0) {
offsetRect.top = 0;
}
if (containerType == "body") {
if (index == 0 && offsetRect.top >= MainStore.page.headerHeight) {
offsetRect.top = MainStore.page.headerHeight;
}
}
// element is parent level row.
if (index > 0 && ["header", "body", "footer"].includes(containerType)) {
offsetRect.top = prevDimensions.bottom;
}
if (containerType == "column") {
offsetRect.left = prevDimensions.right;
offsetRect.top = 0;
}
if (containerType == "row") {
if (index == 0) {
offsetRect.top = 0;
} else {
offsetRect.top = prevDimensions.bottom;
}
}
return offsetRect;
},
cleanUpElementsForSave(rows, type) {
if (this.checkIfPrintFormatIsEmpty(rows, type)) return;
const MainStore = useMainStore();
const fontsObject = {};
switch (type) {
case "header":
MainStore.printHeaderFonts = fontsObject;
break;
case "body":
MainStore.printBodyFonts = fontsObject;
break;
case "footer":
MainStore.printFooterFonts = fontsObject;
}
return rows.map((element) => {
let newElement = this.childrensSave(element, fontsObject);
newElement.classes = newElement.classes.filter(
(name) => ["inHeaderFooter", "overlappingHeaderFooter"].indexOf(name) == -1
);
return newElement;
});
},
checkIfPrintFormatIsEmpty(elements, type) {
const MainStore = useMainStore();
if (elements.length == 0) {
switch (type) {
case "header":
MainStore.printHeaderFonts = null;
break;
case "body":
MainStore.printBodyFonts = null;
let message = __("Atleast 1 element is required inside body");
frappe.show_alert(
{
message: message,
indicator: "red",
},
5
);
// This is intentionally using throw to stop the execution
throw new Error(message);
case "footer":
MainStore.printFooterFonts = null;
break;
}
return true;
}
return false;
},
childrensSave(element, printFonts = null) {
let saveEl = { ...element };
delete saveEl.DOMRef;
delete saveEl.snapPoints;
delete saveEl.snapEdges;
delete saveEl.parent;
this.cleanUpDynamicContent(saveEl);
if (saveEl.type == "table") {
saveEl.table = { ...saveEl.table };
delete saveEl.table.childfields;
delete saveEl.table.default_layout;
}
if (printFonts && ["text", "table"].indexOf(saveEl.type) != -1) {
handlePrintFonts(saveEl, printFonts);
}
if (saveEl.type == "rectangle" || saveEl.type == "page") {
const childrensArray = saveEl.childrens;
saveEl.childrens = [];
childrensArray.forEach((el) => {
const child = this.childrensSave(el, printFonts);
child && saveEl.childrens.push(child);
});
}
return saveEl;
},
cleanUpDynamicContent(element) {
const MainStore = useMainStore();
if (
["table", "image"].includes(element.type) ||
(["text", "barcode"].includes(element.type) && element.isDynamic)
) {
if (["text", "barcode"].indexOf(element.type) != -1) {
element.dynamicContent = [
...element.dynamicContent.map((el) => {
const newEl = { ...el };
if (!el.is_static) {
newEl.value = "";
}
return newEl;
}),
];
element.selectedDynamicText = null;
} else if (element.type === "table") {
element.columns = [
...element.columns.map((el) => {
const newEl = { ...el };
delete newEl.DOMRef;
return newEl;
}),
];
element.columns.forEach((col) => {
if (!col.dynamicContent) return;
col.dynamicContent = [
...col.dynamicContent.map((el) => {
const newEl = { ...el };
if (!el.is_static) {
newEl.value = "";
}
return newEl;
}),
];
col.selectedDynamicText = null;
});
} else {
element.image = { ...element.image };
if (MainStore.is_standard) {
// remove file_url and file_name if format is standard
["value", "name", "file_name", "file_url", "modified"].forEach((key) => {
element.image[key] = "";
});
}
}
}
},
createWrapperElement(dimensions, parent) {
const MainStore = useMainStore();
const coordinates = {};
if (parent.type == "page") {
coordinates["startY"] = dimensions.top;
coordinates["pageY"] = dimensions.top;
coordinates["startX"] = 0;
coordinates["pageX"] = 0;
} else if (parent.layoutType == "row") {
coordinates["startY"] = 0;
coordinates["pageY"] = 0;
coordinates["startX"] = dimensions.left;
coordinates["pageX"] = dimensions.left;
} else {
coordinates["startY"] = dimensions.top;
coordinates["pageY"] = dimensions.top;
coordinates["startX"] = dimensions.left;
coordinates["pageX"] = dimensions.left;
}
const wrapper = createRectangle(coordinates, parent);
wrapper.layoutType = parent.layoutType == "row" ? "column" : "row";
if (wrapper.layoutType == "column") {
wrapper.width = dimensions.right - dimensions.left;
wrapper.height = parent.height || 0;
wrapper.classes = wrapper.classes.filter((c) => c != "relative-column");
wrapper.classes.push("relative-column");
wrapper.relativeColumn = true;
} else {
wrapper.width =
parent.width ||
MainStore.page.width - MainStore.page.marginLeft - MainStore.page.marginRight;
wrapper.height = dimensions.bottom - dimensions.top;
wrapper.classes = wrapper.classes.filter((c) => c != "relative-row");
wrapper.classes.push("relative-row");
wrapper.classes.push(wrapper.id);
}
return wrapper;
},
updateChildrenInRowWrapper(wrapper, children) {
wrapper.childrens = children;
if (
(wrapper.childrens.length == 1 &&
wrapper.childrens[0].heightType == "auto-min-height") ||
wrapper.childrens.some(
(el) =>
["row", "column"].includes(el.layoutType) &&
el.heightType == "auto-min-height"
)
) {
wrapper.heightType = "auto-min-height";
} else if (
(wrapper.childrens.length == 1 && wrapper.childrens[0].heightType == "auto") ||
wrapper.childrens.some(
(el) => ["row", "column"].includes(el.layoutType) && el.heightType == "auto"
)
) {
wrapper.heightType = "auto";
} else {
wrapper.heightType = "fixed";
}
wrapper.childrens.sort((a, b) => (a.startY < b.startY ? -1 : 1));
wrapper.startX = 0;
return;
},
updateRowChildrenDimensions(wrapper, children, parent) {
if (parent.type == "page") {
children.forEach((el) => {
el.startY -= wrapper.startY;
});
return;
}
children.forEach((el) => {
el.startY -= wrapper.startY;
});
},
updateColumnChildrenDimensions(wrapper, children) {
children.sort((a, b) => (a.startX < b.startX ? -1 : 1));
children.forEach((el) => {
el.startY -= wrapper.startY;
el.startX -= wrapper.startX;
});
},
updateChildrenInColumnWrapper(wrapper, children) {
wrapper.childrens = children;
wrapper.childrens.forEach((el) => {
el.startY += wrapper.startY;
});
// TODO: add better control for dynamic height
wrapper.startY = 0;
if (
wrapper.childrens.some(
(el) => el.layoutType == "row" || el.heightType == "auto-min-height"
)
) {
wrapper.heightType = "auto-min-height";
} else if (
wrapper.childrens.some(
(el) => el.layoutType == "column" || el.heightType == "auto"
)
) {
wrapper.heightType = "auto";
} else {
wrapper.heightType = "fixed";
}
},
createRowWrapperElement(dimension, currentRow, parent) {
const MainStore = useMainStore();
const coordinates = {};
if (parent.type == "page") {
coordinates["startY"] = dimension.top;
coordinates["pageY"] = dimension.top;
coordinates["startX"] = 0;
coordinates["pageX"] = 0;
} else {
coordinates["startY"] = dimension.top;
coordinates["pageY"] = dimension.top;
coordinates["startX"] = dimension.left;
coordinates["pageX"] = dimension.left;
}
const wrapper = createRectangle(coordinates, parent);
wrapper.layoutType = "row";
wrapper.width =
parent.width ||
MainStore.page.width - MainStore.page.marginLeft - MainStore.page.marginRight;
wrapper.height = dimension.bottom - dimension.top;
wrapper.classes = wrapper.classes.filter((c) => c != "relative-row");
wrapper.classes.push("relative-row");
delete wrapper.parent;
this.updateRowElement(wrapper, currentRow, parent);
return wrapper;
},
updateRowElement(wrapper, currentRow, parent) {
wrapper.layoutType = "row";
this.updateRowChildrenDimensions(wrapper, currentRow, parent);
let childElements = [...currentRow];
const columnEls = this.computeColumnLayout(childElements, wrapper);
if (columnEls) {
childElements = columnEls;
} else {
this.computeLayoutInsideRectangle(childElements);
}
this.updateChildrenInRowWrapper(wrapper, childElements);
if (
(childElements.length == 1 && childElements[0].heightType == "auto-min-height") ||
childElements.some(
(el) =>
["row", "column"].includes(el.layoutType) &&
el.heightType == "auto-min-height"
)
) {
wrapper.heightType = "auto-min-height";
} else if (
(childElements.length == 1 && childElements[0].heightType == "auto") ||
childElements.some(
(el) => ["row", "column"].includes(el.layoutType) && el.heightType == "auto"
)
) {
wrapper.heightType = "auto";
} else {
wrapper.heightType = "fixed";
}
},
createColumnWrapperElement(dimension, currentColumn, parent) {
const coordinates = {
startY: dimension.top,
pageY: dimension.top,
startX: dimension.left,
pageX: dimension.left,
};
const wrapper = createRectangle(coordinates, parent);
wrapper.layoutType = "column";
wrapper.width = dimension.right - dimension.left;
wrapper.height = parent.height;
wrapper.classes = wrapper.classes.filter((c) => c != "relative-column");
wrapper.classes.push("relative-column");
wrapper.relativeColumn = true;
delete wrapper.parent;
this.updateColumnElement(wrapper, currentColumn);
return wrapper;
},
updateColumnElement(wrapper, currentColumn) {
wrapper.layoutType = "column";
this.updateColumnChildrenDimensions(wrapper, currentColumn);
let childElements = [...currentColumn];
const rowEls = this.computeRowLayout(childElements, wrapper);
if (rowEls) {
childElements = rowEls;
} else {
this.computeLayoutInsideRectangle(childElements);
}
this.updateChildrenInColumnWrapper(wrapper, childElements);
if (
(childElements.length == 1 && childElements[0].heightType == "auto-min-height") ||
childElements.some(
(el) =>
["row", "column"].includes(el.layoutType) &&
el.heightType == "auto-min-height"
)
) {
wrapper.heightType = "auto-min-height";
} else if (
(childElements.length == 1 && childElements[0].heightType == "auto") ||
childElements.some(
(el) => ["row", "column"].includes(el.layoutType) && el.heightType == "auto"
)
) {
wrapper.heightType = "auto";
} else {
wrapper.heightType = "fixed";
}
},
async printFormatCopyOnOlderSchema(objectToSave) {
// TODO: have better message.
let message = __(
"<b>This Print Format was created from older version of Print Designer.</b>"
);
message += "<hr />";
message += __(
"It is not compatible with current version so instead make copy of this format using new version"
);
message += "<hr />";
message += __(`Do you want to save copy of it ?`);
frappe.confirm(
message,
async () => {
this.promptUserForNewFormatName(objectToSave);
},
async () => {
frappe.show_alert(
{
message: `Print Format not saved`,
indicator: "red",
},
5
);
// intentionally throwing error to stop the saving the format
throw new Error(__("Print Format not saved"));
}
);
},
async promptUserForNewFormatName(objectToSave) {
const MainStore = useMainStore();
let nextFormatCopyNumber = 0;
for (let i = 0; i < 100; i++) {
const pf_exists = await frappe.db.exists(
"Print Format",
MainStore.printDesignName + " ( Copy " + (i ? i : "") + " )"
);
if (pf_exists) continue;
nextFormatCopyNumber = i;
break;
}
// This is just default value for the new print format name
const print_format_name =
MainStore.printDesignName +
" ( Copy " +
(nextFormatCopyNumber ? nextFormatCopyNumber : "") +
" )";
let d = new frappe.ui.Dialog({
title: "New Print Format",
fields: [
{
label: "Name",
fieldname: "print_format_name",
fieldtype: "Data",
reqd: 1,
default: print_format_name,
},
],
size: "small",
primary_action_label: "Save",
static: true,
async primary_action(values) {
try {
await frappe.db.insert({
doctype: "Print Format",
name: values.print_format_name,
doc_type: MainStore.doctype,
print_designer: 1,
print_designer_header: objectToSave.print_designer_header,
print_designer_body: objectToSave.print_designer_body,
print_designer_after_table: null,
print_designer_footer: objectToSave.print_designer_footer,
print_designer_print_format: objectToSave.print_designer_print_format,
print_designer_settings: objectToSave.print_designer_settings,
});
d.hide();
frappe.set_route("print-designer", values.print_format_name);
} catch (error) {
console.error(error);
}
},
});
d.get_close_btn().on("click", () => {
frappe.show_alert(
{
message: `Print Format not saved`,
indicator: "red",
},
5
);
});
d.show();
},
handleDynamicContent(element) {
const MainStore = useMainStore();
if (
element.type == "table" ||
(["text", "image", "barcode"].indexOf(element.type) != -1 && element.isDynamic)
) {
if (["text", "barcode"].indexOf(element.type) != -1) {
element.dynamicContent = [
...element.dynamicContent.map((el) => {
const newEl = { ...el };
if (!el.is_static) {
newEl.value = "";
}
return newEl;
}),
];
element.selectedDynamicText = null;
MainStore.dynamicData.push(...element.dynamicContent);
} else if (element.type === "table") {
if (element.table) {
const mf = MainStore.metaFields.find(
(field) => field.fieldname == element.table.fieldname
);
if (mf) {
element.table = mf;
}
}
element.columns = [
...element.columns.map((el) => {
return { ...el };
}),
];
element.columns.forEach((col) => {
if (!col.dynamicContent) return;
col.dynamicContent = [
...col.dynamicContent.map((el) => {
const newEl = { ...el };
if (!el.is_static) {
newEl.value = "";
}
return newEl;
}),
];
col.selectedDynamicText = null;
MainStore.dynamicData.push(...col.dynamicContent);
});
} else {
element.image = { ...element.image };
MainStore.dynamicData.push(element.image);
}
}
},
childrensLoad(element, parent) {
element.parent = parent;
element.DOMRef = null;
delete element.printY;
element.isDraggable = true;
element.isResizable = true;
this.handleDynamicContent(element);
if (element.type == "rectangle" || element.type == "page") {
element.isDropZone = true;
const childrensArray = element.childrens;
element.childrens = [];
childrensArray.forEach((el) => {
const child = this.childrensLoad(el, element);
child && element.childrens.push(child);
});
} else if (element.type == "text" && !element.isDynamic) {
element.contenteditable = false;
}
return element;
},
loadSettings(settings) {
const MainStore = useMainStore();
if (!settings) return;
Object.keys(settings).forEach((key) => {
switch (key) {
case "schema_version":
MainStore.old_schema_version = settings["schema_version"];
case "currentDoc":
frappe.db
.exists(MainStore.doctype, settings["currentDoc"])
.then((exists) => {
if (exists) {
MainStore.currentDoc = settings["currentDoc"];
}
});
break;
default:
MainStore[key] = settings[key];
break;
}
});
return;
},
getHeaderObject(index) {
if (index == 0) {
return this.Headers.find((header) => header.firstPage == true);
} else if (index == this.Elements.length - 1) {
return this.Headers.find((header) => header.lastPage == true);
} else if (index % 2 != 0) {
return this.Headers.find((header) => header.oddPage == true);
} else {
return this.Headers.find((header) => header.evenPage == true);
}
},
getFooterObject(index) {
if (index == 0) {
return this.Footers.find((footer) => footer.firstPage == true);
} else if (index == this.Elements.length - 1) {
return this.Footers.find((footer) => footer.lastPage == true);
} else if (index % 2 != 0) {
return this.Footers.find((footer) => footer.oddPage == true);
} else {
return this.Footers.find((footer) => footer.evenPage == true);
}
},
setElementProperties(parent) {
parent.childrens.map((element) => {
element.DOMRef = null;
element.parent = parent;
delete element.printY;
element.isDraggable = true;
element.isResizable = true;
this.handleDynamicContent(element);
if (element.type == "rectangle" || element.type == "page") {
element.isDropZone = true;
if (element.childrens.length) {
let childrensArray = element.childrens;
element.childrens = [];
childrensArray.forEach((el) => {
element.childrens.push(this.childrensLoad(el, element));
});
}
} else if (element.type == "text" && !element.isDynamic) {
element.contenteditable = false;
}
return element;
});
},
createPageElement(element, type) {
return {
type: "page",
childrens: [...element],
firstPage: true,
oddPage: true,
evenPage: true,
lastPage: true,
DOMRef: null,
};
},
async loadElements(printDesignName) {
frappe.dom.freeze(__("Loading Print Format"));
const printFormat = await frappe.db.get_value("Print Format", printDesignName, [
"print_designer_header",
"print_designer_body",
"print_designer_after_table",
"print_designer_footer",
"print_designer_settings",
]);
let settings = JSON.parse(printFormat.message.print_designer_settings);
this.loadSettings(settings);
let ElementsBody = JSON.parse(printFormat.message.print_designer_body);
let ElementsAfterTable = JSON.parse(printFormat.message.print_designer_after_table);
const headers = JSON.parse(printFormat.message.print_designer_header);
const footers = JSON.parse(printFormat.message.print_designer_footer);
headers.forEach((header) => {
this.Headers.push(header);
});
footers.forEach((footer) => {
this.Footers.push(footer);
});
// backwards compatibility :(
if (ElementsAfterTable && ElementsAfterTable.length) {
ElementsBody[0].childrens.push(...ElementsAfterTable);
}
this.Elements.length = 0;
this.Elements.push(...ElementsBody);
ElementsBody.forEach((page, index) => {
page.header = [
createHeaderFooterElement(this.getHeaderObject(index).childrens, "header"),
];
page.footer = [
createHeaderFooterElement(this.getFooterObject(index).childrens, "footer"),
];
});
this.Elements.forEach((page) => this.setElementProperties(page));
frappe.dom.unfreeze();
},
setPrimaryTable(tableEl, value) {
if (!value) {
tableEl.isPrimaryTable = value;
return;
}
tables = this.Elements.filter((el) => el.type == "table");
tables.forEach((t) => {
t.isPrimaryTable = t == tableEl;
});
},
// This is called to check if the element is overlapping with any other element (row only)
// TODO: add column calculations
isElementOverlapping(currentEl, elements = null) {
const MainStore = useMainStore();
MainStore.activePage = getParentPage(currentEl.parent);
if (!elements) {
elements = MainStore.activePage.childrens;
}
const currentElIndex = currentEl.index || elements.findIndex((el) => el === currentEl);
const currentStartY = parseInt(currentEl.startY);
const currentStartX = parseInt(currentEl.startX);
const currentEndY = parseInt(currentEl.startY + currentEl.height);
const currentEndX = parseInt(currentEl.startX + currentEl.width);
return (
elements.findIndex((el, index) => {
if (index == currentElIndex) return false;
const elStartY = parseInt(el.startY);
const elEndY = parseInt(el.startY + el.height);
const elStartX = parseInt(el.startX);
const elEndX = parseInt(el.startX + el.width);
if (
currentStartY <= elStartY &&
elStartY <= currentEndY &&
!(currentStartY <= elEndY && elEndY <= currentEndY) &&
currentStartX <= elStartX &&
elStartX <= currentEndX &&
!(currentStartX <= elEndX && elEndX <= currentEndX)
) {
return true;
} else if (
!(currentStartY <= elStartY && elStartY <= currentEndY) &&
currentStartY <= elEndY &&
elEndY <= currentEndY &&
!(currentStartX <= elStartX && elStartX <= currentEndX) &&
currentStartX <= elEndX &&
elEndX <= currentEndX
) {
return true;
} else if (
elStartY <= currentStartY &&
currentStartY <= elEndY &&
elStartY <= currentEndY &&
currentEndY <= elEndY &&
elStartX <= currentStartX &&
currentStartX <= elEndX &&
elStartX <= currentEndX &&
currentEndX <= elEndX
) {
return true;
} else {
return false;
}
}) != -1
);
},
},
});
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/store/ElementStore.js
|
JavaScript
|
agpl-3.0
| 41,488
|
import { defineStore } from "pinia";
import { markRaw } from "vue";
import { useChangeValueUnit } from "../composables/ChangeValueUnit";
import { GoogleFonts, barcodeFormats } from "../defaultObjects";
import { globalStyles } from "../globalStyles";
import { pageSizes } from "../pageSizes";
export const useMainStore = defineStore("MainStore", {
state: () => ({
/**
* @type {'mouse-pointer'|'text'|'rectangle'|'image'|'components'|'table'|'barcode'} activeControl
*/
activeControl: "mouse-pointer",
/**
* @type {'static'|'dynamic'} textControlType
*/
textControlType: "dynamic",
/**
* @type {'editing'|'footer'|'header'} mode
*/
schema_version: "1.3.0",
mode: "editing",
activePage: null,
visiblePages: [],
cursor: "url('/assets/print_designer/images/mouse-pointer.svg'), default !important",
isMarqueeActive: false,
isDrawing: false,
doctype: null,
currentDoc: null,
pdfPrintDPI: 96,
isPDFSetupMode: false,
isHeaderFooterAuto: true,
isPreviewMode: false,
barcodeFormats,
fonts: GoogleFonts,
currentFonts: ["Inter"],
printHeaderFonts: null,
printBodyFonts: null,
printFooterFonts: null,
rawMeta: null,
metaFields: [],
docData: {},
dynamicData: [],
imageDocFields: [],
snapPoints: [],
snapEdges: [],
propertiesContainer: new Object(),
openModal: false,
openDynamicModal: null,
openImageModal: null,
openBarcodeModal: null,
openTableColumnModal: null,
openJinjaModal: false,
mainParsedJinjaData: "",
userProvidedJinja: "",
frappeControls: {
documentControl: null,
tableControl: null,
},
isMoveStart: false,
isDropped: false,
isAltKey: false,
isShiftKey: false,
lastCloned: null,
currentDrawListener: null,
isMoved: false,
isHiddenFieldsVisible: false,
currentPageSize: "A4",
pageSizes,
lastCreatedElement: null,
screenStyleSheet: null,
printStyleSheet: null,
modalLocation: {
isDragged: false,
x: 0,
y: 0,
},
toolbarWidth: 44,
currentElements: {},
globalStyles,
printDesignName: "",
isLayerPanelEnabled: false,
page: {
height: 1122.519685,
width: 793.7007874,
marginTop: 0,
marginBottom: 0,
marginLeft: 0,
marginRight: 0,
headerHeight: 0,
footerHeight: 0,
headerHeightWithMargin: 0,
footerHeightWithMargin: 0,
UOM: "mm",
},
controls: {
MousePointer: {
icon: "mouseTool",
control: "MousePointer",
aria_label: __("Mouse Pointer (M)"),
id: "mouse-pointer",
cursor: "url('/assets/print_designer/images/mouse-pointer.svg'), default",
isDisabled: false,
},
Text: {
icon: "textTool",
control: "Text",
aria_label: __("Text (T)"),
id: "text",
cursor: "url('/assets/print_designer/images/add-text.svg') 10 10, text",
isDisabled: false,
},
Rectangle: {
icon: "rectangleTool",
control: "Rectangle",
aria_label: __("Rectangle (R)"),
id: "rectangle",
cursor: "url('/assets/print_designer/images/add-rectangle.svg') 6 6, crosshair",
isDisabled: false,
},
Image: {
icon: "imageTool",
control: "Image",
aria_label: __("Image (I)"),
id: "image",
cursor: "url('/assets/print_designer/images/add-image.svg') 6 6, crosshair",
isDisabled: false,
},
Table: {
icon: "tableTool",
control: "Table",
aria_label: __("Table (A)"),
id: "table",
cursor: "url('/assets/print_designer/images/add-table.svg') 6 6, crosshair",
isDisabled: false,
},
// Components: {
// icon: "fa fa-cube",
// control: "Components",
// aria_label: __("Components (C)"),
// id: "components",
// cursor: "default",
// },
Barcode: {
icon: "barcodeTool",
control: "Barcode",
aria_label: __("Barcode (B)"),
id: "barcode",
cursor: "url('/assets/print_designer/images/add-barcode.svg') 6 6, crosshair",
},
},
propertiesPanel: [],
}),
getters: {
convertToPageUOM() {
return (input) => {
let convertedUnit = useChangeValueUnit({
inputString: input,
defaultInputUnit: "px",
convertionUnit: this.page.UOM,
});
if (convertedUnit.error) return;
return convertedUnit.value.toFixed(3);
};
},
convertToPX() {
return (input, defaultInputUnit = this.page.UOM) => {
let convertedUnit = useChangeValueUnit({
inputString: input,
defaultInputUnit,
convertionUnit: "px",
});
if (convertedUnit.error) return;
return parseFloat(convertedUnit.value.toFixed(3));
};
},
getPageStyle() {
switch (this.mode) {
case "editing":
return this.getPageSettings;
case "header":
return this.getHeaderSettings;
case "footer":
return this.getFooterSettings;
}
},
getPageSettings() {
return {
height:
this.convertToPageUOM(
this.page.height - (this.page.marginTop + this.page.marginBottom)
) + this.page.UOM,
width:
this.convertToPageUOM(
this.page.width - (this.page.marginLeft + this.page.marginRight)
) + this.page.UOM,
};
},
getHeaderSettings() {
return {
height: this.convertToPageUOM(this.page.headerHeight) + this.page.UOM,
width:
this.convertToPageUOM(
this.page.width - this.page.marginLeft - this.page.marginRight
) + this.page.UOM,
};
},
getFooterSettings() {
return {
height: this.convertToPageUOM(this.page.footerHeight) + this.page.UOM,
width:
this.convertToPageUOM(
this.page.width - this.page.marginLeft - this.page.marginRight
) + this.page.UOM,
};
},
getCurrentElementsValues() {
return Object.values(this.currentElements);
},
getCurrentElementsId() {
return Object.keys(this.currentElements);
},
getLinkMetaFields: (state) => {
return (search_string = null, parentField) => {
let metaFields = state.metaFields.filter((el) => {
if (el.fieldtype != "Link") return false;
if (typeof search_string != "string" || !search_string.length) return true;
if (
el["label"].toLowerCase().includes(search_string.toLowerCase()) ||
el["fieldname"].toLowerCase().includes(search_string.toLowerCase()) ||
el["fieldtype"].toLowerCase().includes(search_string.toLowerCase())
) {
return true;
}
return false;
});
metaFields.sort((a, b) => a.label.localeCompare(b.label));
if (
!parentField ||
typeof search_string != "string" ||
!search_string.length ||
state.doctype.toLowerCase().includes(search_string.toLowerCase())
) {
// Main DocType is added manually as link :D
metaFields.unshift({
fieldname: "",
label: state.doctype,
fieldtype: "Link",
options: state.doctype,
});
}
if (parentField) {
let currentField = state.metaFields.find(
(field) => field.fieldname === parentField
);
if (metaFields.indexOf(currentField) == -1) {
metaFields.unshift(currentField);
}
}
return metaFields;
};
},
getTableMetaFields: (state) => {
return state.metaFields.filter((el) => el.fieldtype == "Table");
},
getTypeWiseMetaFields: (state) => {
return ({
selectedParentField = null,
selectedTable = null,
search_string = null,
show_hidden_fields = false,
}) => {
let fields = {};
let metaFields = state.metaFields;
if (selectedParentField) {
metaFields = metaFields.find(
(e) => e.fieldname === selectedParentField
).childfields;
} else if (selectedTable) {
metaFields = selectedTable.childfields;
}
if (!show_hidden_fields) {
metaFields = metaFields.filter((field) => !field["print_hide"]);
}
if (typeof search_string == "string" && search_string.length) {
metaFields = metaFields.filter(
(o) =>
o["label"]?.toLowerCase().includes(search_string.toLowerCase()) ||
o["fieldname"]?.toLowerCase().includes(search_string.toLowerCase()) ||
o["fieldtype"]?.toLowerCase().includes(search_string.toLowerCase())
);
}
if (selectedTable) {
if (
typeof search_string != "string" ||
!search_string.length ||
"line number no idx".includes(search_string.toLowerCase())
) {
fields["Line Number"] = [
{
fieldname: "idx",
fieldtype: "Int",
label: "No",
options: undefined,
table: selectedTable,
},
];
}
} else if (
typeof search_string != "string" ||
!search_string.length ||
"Name".toLowerCase().includes(search_string.toLowerCase())
) {
fields["Document"] = [
{
fieldname: "name",
fieldtype: "Small Text",
label: "Name",
options: undefined,
},
];
if (!selectedParentField) {
fields["Document"].push(
{
fieldname: "page",
fieldtype: "Small Text",
label: "Current Page",
options: undefined,
},
{
fieldname: "topage",
fieldtype: "Small Text",
label: "Total Pages",
options: undefined,
},
{
fieldname: "time",
fieldtype: "Small Text",
label: "Print Time",
options: undefined,
},
{
fieldname: "date",
fieldtype: "Small Text",
label: "Print Date",
options: undefined,
}
);
}
}
metaFields.forEach((field) => {
if (
["Button", "Color", "Table", "Attach"].indexOf(field.fieldtype) == -1 &&
(selectedTable ||
["Link", "Image", "Attach", "Attach Image"].indexOf(field.fieldtype) ==
-1)
) {
if (!state.openBarcodeModal && field.fieldtype == "Barcode") return;
if (fields[field.fieldtype]) {
fields[field.fieldtype].push(field);
} else {
fields[field.fieldtype] = [field];
}
}
});
return fields;
};
},
getGoogleFonts: (state) => {
return Object.keys(state.fonts);
},
getGoogleFontWeights: (state) => () => {
let fontName = state.getCurrentStyle("fontFamily");
if (!fontName) {
return [
{ label: "Thin", value: 100 },
{ label: "Extra Light", value: 200 },
{ label: "Light", value: 300 },
{ label: "Regular", value: 400 },
{ label: "Medium", value: 500 },
{ label: "Semi Bold", value: 600 },
{ label: "Bold", value: 700 },
{ label: "Extra Bold", value: 800 },
{ label: "Black", value: 900 },
];
}
return [
{ label: "Thin", value: 100 },
{ label: "Extra Light", value: 200 },
{ label: "Light", value: 300 },
{ label: "Regular", value: 400 },
{ label: "Medium", value: 500 },
{ label: "Semi Bold", value: 600 },
{ label: "Bold", value: 700 },
{ label: "Extra Bold", value: 800 },
{ label: "Black", value: 900 },
].filter((weight) => state.fonts[fontName][0].indexOf(weight.value) != -1);
},
getGlobalStyleObject: (state) => {
let globalStyleName;
let object = state.getCurrentElementsValues[0];
const mapper = Object.freeze({
main: "style",
label: "labelStyle",
header: "headerStyle",
alt: "altStyle",
});
let styleEditMode;
if (object) {
styleEditMode = mapper[object.styleEditMode];
globalStyleName = object.type;
if (globalStyleName == "text") {
if (object.isDynamic) {
globalStyleName = "dynamicText";
} else {
globalStyleName = "staticText";
}
}
} else {
if (state.activeControl == "mouse-pointer") return;
globalStyleName = state.activeControl;
if (globalStyleName == "text") {
if (state.textControlType == "dynamic") {
globalStyleName = "dynamicText";
} else {
globalStyleName = "staticText";
}
}
styleEditMode = mapper[state.globalStyles[globalStyleName].styleEditMode];
}
return state.globalStyles[globalStyleName][styleEditMode];
},
getStyleObject: (state) => (isFontStyle) => {
let object = state.getCurrentElementsValues[0];
if (!object) return state.getGlobalStyleObject;
const mapper = Object.freeze({
main: "style",
label: "labelStyle",
header: "headerStyle",
alt: "altStyle",
});
let styleEditMode = mapper[object.styleEditMode];
return !isFontStyle
? object.selectedColumn?.["style"] || object[styleEditMode]
: object.selectedDynamicText?.[styleEditMode] ||
object.selectedColumn?.["style"] ||
object[styleEditMode];
},
isValidValue: (state) => (value) => {
if (typeof value == "string") {
return value.length != 0;
} else if (typeof value == "number") {
return true;
}
return false;
},
getCurrentStyle: (state) => (propertyName) => {
let object = state.getCurrentElementsValues[0];
if (!object) return state.getGlobalStyleObject?.[propertyName];
const mapper = Object.freeze({
main: "style",
label: "labelStyle",
header: "headerStyle",
alt: "altStyle",
});
let styleEditMode = mapper[object.styleEditMode];
if (propertyName != "backgroundColor") {
if (
state.isValidValue(object.selectedDynamicText?.[styleEditMode][propertyName])
) {
return object.selectedDynamicText?.[styleEditMode][propertyName];
}
if (state.isValidValue(object.selectedColumn?.["style"]?.[propertyName])) {
return object.selectedColumn?.["style"][propertyName];
}
if (state.isValidValue(object[styleEditMode][propertyName])) {
return object[styleEditMode][propertyName];
}
if (state.isValidValue(state.getGlobalStyleObject[propertyName])) {
return state.getGlobalStyleObject[propertyName];
}
} else {
// we need to check if empty string incase it is background color and set as transparent
if (typeof object.selectedDynamicText?.[styleEditMode][propertyName] == "string") {
return object.selectedDynamicText?.[styleEditMode][propertyName];
}
if (typeof object.selectedColumn?.["style"][propertyName] == "string") {
return object.selectedColumn?.["style"][propertyName];
}
if (typeof object[styleEditMode][propertyName] == "string") {
return object[styleEditMode][propertyName];
}
if (typeof state.getGlobalStyleObject[propertyName] == "string") {
return state.getGlobalStyleObject[propertyName];
}
}
},
isOlderSchema: (state) => (currentVersion) => {
if (!state.old_schema_version) return false;
let formatVersion = state.old_schema_version.split(".");
if (currentVersion == formatVersion) return false;
currentVersion = currentVersion.split(".");
if (parseInt(formatVersion[0]) < parseInt(currentVersion[0])) {
return true;
} else if (
parseInt(formatVersion[0]) === parseInt(currentVersion[0]) &&
parseInt(formatVersion[1]) < parseInt(currentVersion[1])
) {
return true;
} else if (
parseInt(formatVersion[0]) === parseInt(currentVersion[0]) &&
parseInt(formatVersion[1]) === parseInt(currentVersion[1]) &&
parseInt(formatVersion[2]) < parseInt(currentVersion[2])
) {
return true;
} else {
return false;
}
},
},
actions: {
/**
* @param {'MousePointer'|'Text'|'Rectangle'|'Components'|'Image'|'Table'|'Barcode'} id
*/
setActiveControl(id) {
let control = this.controls[id];
this.activeControl = control.id;
this.cursor = control.cursor;
},
setPrintDesignName(name) {
this.printDesignName = name;
},
/**
* @param {Array} rules Accepts an array of JSON-encoded declarations
* @return {String} Id of CssRule
* @example
addStylesheetRules([
['h2', // Also accepts a second argument as an array of arrays instead
['color', 'red'],
['background-color', 'green', true] // 'true' for !important rules
],
['.myClass',
['background-color', 'yellow']
]
]);
*/
addStylesheetRules(rules, media = "screen") {
for (let i = 0; i < rules.length; i++) {
let j = 1,
rule = rules[i],
selector = rule[0],
propStr = "";
// If the second argument of a rule is an array of arrays, correct our variables.
if (Array.isArray(rule[1][0])) {
rule = rule[1];
j = 0;
}
for (let pl = rule.length; j < pl; j++) {
const prop = rule[j];
prop[0] = prop[0]
?.replace(/([a-z])([A-Z])/g, "$1-$2")
.replace(/[\s_]+/g, "-")
.toLowerCase();
propStr += `${prop[0]}: ${prop[1]}${prop[2] ? " !important" : ""};\n`;
}
// Insert CSS Rule
let styleSheet = this.printStyleSheet;
if (media == "screen") {
styleSheet = this.screenStyleSheet;
}
return styleSheet.insertRule(
`${selector}{${propStr}}`,
styleSheet.cssRules.length
);
}
},
addGlobalRules() {
Object.entries(this.globalStyles).forEach((element) => {
if (!element[1].mainCssRule) {
let mainSelector = element[1].mainRuleSelector;
const id = this.addStylesheetRules([
[mainSelector, [...Object.entries(element[1].style)]],
]);
element[1].mainCssRule = markRaw(this.screenStyleSheet.cssRules[id]);
}
if (!element[1].labelCssRule) {
let labelSelector = element[1].labelRuleSelector;
if (labelSelector) {
const id = this.addStylesheetRules([
[labelSelector, [...Object.entries(element[1].labelStyle)]],
]);
element[1].labelCssRule = markRaw(this.screenStyleSheet.cssRules[id]);
}
}
if (!element[1].headerCssRule) {
let headerSelector = element[1].headerRuleSelector;
if (headerSelector) {
const id = this.addStylesheetRules([
[headerSelector, [...Object.entries(element[1].headerStyle)]],
]);
element[1].headerCssRule = markRaw(this.screenStyleSheet.cssRules[id]);
}
}
if (!element[1].altCssRule) {
let altSelector = element[1].altRuleSelector;
if (altSelector) {
const id = this.addStylesheetRules([
[altSelector, [...Object.entries(element[1].altStyle)]],
]);
element[1].altCssRule = markRaw(this.screenStyleSheet.cssRules[id]);
}
}
});
},
},
});
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/store/MainStore.js
|
JavaScript
|
agpl-3.0
| 17,917
|
import { watch, markRaw } from "vue";
import { useMainStore } from "./MainStore";
import { useElementStore } from "./ElementStore";
export const fetchMeta = async () => {
const MainStore = useMainStore();
MainStore.doctype = await getValue("Print Format", MainStore.printDesignName, "doc_type");
MainStore.rawMeta = await frappe.xcall(
"print_designer.print_designer.page.print_designer.print_designer.get_meta",
{ doctype: MainStore.doctype }
);
let metaFields = MainStore.rawMeta.fields.filter((df) => {
if (["Section Break", "Column Break", "Tab Break", "Image"].includes(df.fieldtype)) {
return false;
} else {
return true;
}
});
metaFields.map((field) => {
let obj = {};
["fieldname", "fieldtype", "label", "options", "print_hide"].forEach((attr) => {
obj[attr] = field[attr];
});
MainStore.metaFields.push({ ...obj });
});
metaFields.map((field) => {
if (field["fieldtype"] == "Table") {
getMeta(field.options, field.fieldname);
}
});
fetchDoc();
!MainStore.getTableMetaFields.length && (MainStore.controls.Table.isDisabled = true);
return;
};
export const getMeta = async (doctype, parentField) => {
const MainStore = useMainStore();
const parentMetaField = MainStore.metaFields.find((o) => o.fieldname == parentField);
if (MainStore.metaFields.find((o) => o.fieldname == parentField)["childfields"]) {
return MainStore.metaFields[parentField]["childfields"];
}
const exculdeFields = ["Section Break", "Column Break", "Tab Break", "HTML"];
if (parentMetaField.fieldtype != "Table") {
// Remove Link Field
exculdeFields.push("Link");
}
const result = await frappe.xcall(
"print_designer.print_designer.page.print_designer.print_designer.get_meta",
{ doctype }
);
let childfields = result.fields.filter((df) => {
if (
exculdeFields.includes(df.fieldtype) ||
(parentMetaField.fieldtype != "Table" && df.print_hide == 1)
) {
return false;
} else {
return true;
}
});
let fields = [];
childfields.map((field) => {
let obj = {};
[
"fieldname",
"fieldtype",
"label",
"options",
"print_hide",
"is_virtual",
"in_list_view",
].forEach((attr) => {
obj[attr] = field[attr];
});
fields.push({ ...obj });
});
childfields.sort((a, b) => a.print_hide - b.print_hide);
parentMetaField["childfields"] = fields;
return fields;
};
export const getValue = async (doctype, name, fieldname) => {
const result = await frappe.db.get_value(doctype, name, fieldname);
const value = await result.message[fieldname];
return value;
};
export const fetchDoc = async (id = null) => {
const MainStore = useMainStore();
const ElementStore = useElementStore();
let doctype = MainStore.doctype;
let doc;
await ElementStore.loadElements(MainStore.printDesignName);
if (MainStore.currentDoc == null) {
if (!id) {
let latestdoc = await frappe.db.get_list(doctype, {
fields: ["name"],
order_by: "modified desc",
limit: 1,
});
MainStore.currentDoc = latestdoc[0]?.name;
} else {
MainStore.currentDoc = id;
}
}
watch(
() => MainStore.currentDoc,
async () => {
if (
!(
MainStore.currentDoc &&
(await frappe.db.exists(MainStore.doctype, MainStore.currentDoc))
)
)
return;
doc = await frappe.db.get_doc(doctype, MainStore.currentDoc);
Object.keys(doc).forEach((element) => {
if (
!MainStore.metaFields.find((o) => o.fieldname == element) &&
["name"].indexOf(element) == -1
) {
delete doc[element];
}
});
MainStore.docData = doc;
},
{ immediate: true }
);
};
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/store/fetchMetaAndData.js
|
JavaScript
|
agpl-3.0
| 3,569
|
/**
*
* @param {String} inputText
* @param {'px'|'mm'|'cm'|'in'} defaultUnit px is considered by default
* @example
* parseFloatAndUnit("110.5 mm") => {
* value: 110.5,
* unit: "mm"
* };
* @returns {{value: number, unit: 'px'|'mm'|'cm'|'in' }}
*/
export const parseFloatAndUnit = (inputText, defaultUnit = "px") => {
if (typeof inputText == "number") {
return {
value: inputText,
unit: defaultUnit,
};
} else if (typeof inputText != "string") return;
const number = parseFloat(inputText.match(/[+-]?([0-9]*[.])?[0-9]+/g));
const validUnits = [/px/, /mm/, /cm/, /in/];
const unit = [];
validUnits.forEach(
(rx) =>
rx.test(inputText) &&
unit.indexOf(rx.exec(inputText)[0]) == -1 &&
unit.push(rx.exec(inputText)[0])
);
return {
value: number,
unit: unit.length == 1 ? unit[0] : defaultUnit,
};
};
import interact from "@interactjs/interact";
import { useMainStore } from "./store/MainStore";
import { useElementStore } from "./store/ElementStore";
import { useDraggable } from "./composables/Draggable";
import { useResizable } from "./composables/Resizable";
import { useDropZone } from "./composables/DropZone";
import { ref, isRef, nextTick } from "vue";
import { getValue } from "./store/fetchMetaAndData";
export const changeDraggable = (element) => {
if (element.relativeContainer || element.DOMRef == null) {
return;
}
if (
!element.isDraggable &&
interact.isSet(element.DOMRef) &&
interact(element.DOMRef).draggable().enabled
) {
interact(element.DOMRef).draggable().enabled = false;
} else if (
element.isDraggable &&
interact.isSet(element.DOMRef) &&
!interact(element.DOMRef).draggable().enabled
) {
interact(element.DOMRef).draggable().enabled = true;
} else if (element.isDraggable && !interact.isSet(element.DOMRef)) {
useDraggable({ element });
}
};
export const lockAxis = (element, toggle) => {
if (toggle) {
interact(element.DOMRef).options.drag.lockAxis = "start";
interact(element.DOMRef).options.resize.modifiers.push(
interact.modifiers.aspectRatio({
ratio: "preserve",
modifiers: [interact.modifiers.restrictSize({ max: "parent" })],
})
);
} else {
interact(element.DOMRef).options.drag.lockAxis = "xy";
interact(element.DOMRef).options.resize.modifiers = interact(
element.DOMRef
).options.resize.modifiers.filter((e) => e.name != "aspectRatio");
}
};
export const changeDropZone = (element) => {
if (
!element.isDropZone &&
interact.isSet(element.DOMRef) &&
interact(element.DOMRef).dropzone().enabled
) {
interact(element.DOMRef).dropzone().enabled = false;
} else if (
element.isDropZone &&
interact.isSet(element.DOMRef) &&
!interact(element.DOMRef).dropzone().enabled
) {
interact(element.DOMRef).dropzone().enabled = true;
} else if (element.isDropZone && !interact.isSet(element.DOMRef)) {
useDropZone({ element });
}
};
export const changeResizable = (element) => {
if (
!element.isResizable &&
interact.isSet(element.DOMRef) &&
interact(element.DOMRef).resizable().enabled
) {
interact(element.DOMRef).resizable().enabled = false;
} else if (
element.isResizable &&
interact.isSet(element.DOMRef) &&
!interact(element.DOMRef).resizable().enabled
) {
interact(element.DOMRef).resizable().enabled = true;
} else if (element.isResizable && !interact.isSet(element.DOMRef)) {
useResizable({ element });
}
};
export const postionalStyles = (startX, startY, width, height) => {
const MainStore = useMainStore();
return {
position: "absolute",
top: MainStore.convertToPageUOM(startY) + MainStore.page.UOM,
left: MainStore.convertToPageUOM(startX) + MainStore.page.UOM,
width: MainStore.convertToPageUOM(width) + MainStore.page.UOM,
height: MainStore.convertToPageUOM(height) + MainStore.page.UOM,
};
};
export const widthHeightStyle = (width, height) => {
const MainStore = useMainStore();
return {
width: MainStore.convertToPageUOM(width) + MainStore.page.UOM,
height: MainStore.convertToPageUOM(height) + MainStore.page.UOM,
};
};
export const setCurrentElement = (event, element) => {
const MainStore = useMainStore();
if (!event.shiftKey && !MainStore.getCurrentElementsValues.includes(element)) {
MainStore.getCurrentElementsId.forEach((element) => {
delete MainStore.currentElements[element];
});
}
if (MainStore.getCurrentElementsId.length < 2 && !MainStore.currentElements[element.id]) {
MainStore.currentElements[element.id] = element;
}
if (event.shiftKey && !event.metaKey && !event.ctrlKey) {
MainStore.currentElements[element.id] = element;
return;
} else if ((event.metaKey || event.ctrlKey) && event.shiftKey) {
delete MainStore.currentElements[element.id];
return;
}
};
const childrensCleanUp = (parentElement, element, isClone, isMainElement) => {
const MainStore = useMainStore();
!isMainElement && (element = { ...element });
!isClone && element && deleteSnapObjects(element);
element.id = frappe.utils.get_random(10);
element.index = null;
element.DOMRef = null;
!isMainElement && (element.parent = parentElement);
element.style = { ...element.style };
element.labelStyle && (element.labelStyle = { ...element.labelStyle });
element.headerStyle && (element.headerStyle = { ...element.headerStyle });
element.altStyle && (element.altStyle = { ...element.altStyle });
element.classes = [...element.classes];
element.snapPoints = [];
element.snapEdges = [];
if (
element.type == "table" ||
element.type == "barcode" ||
(["text", "image"].indexOf(element.type) != -1 && element.isDynamic)
) {
if (["text", "barcode"].indexOf(element.type) != -1) {
element.dynamicContent = [
...element.dynamicContent.map((el) => {
let clone_el = { ...el };
clone_el.style = { ...clone_el.style };
clone_el.labelStyle = { ...clone_el.labelStyle };
return clone_el;
}),
];
element.selectedDynamicText = null;
MainStore.dynamicData.push(...element.dynamicContent);
} else if (element.type === "table") {
element.columns = [
...element.columns.map((el) => {
return { ...el };
}),
];
element.columns.forEach((col) => {
if (!col.dynamicContent) return;
col.dynamicContent = [
...col.dynamicContent.map((el) => {
let clone_el = { ...el };
clone_el.style = { ...clone_el.style };
clone_el.labelStyle = { ...clone_el.labelStyle };
return clone_el;
}),
];
col.selectedDynamicText = null;
MainStore.dynamicData.push(...col.dynamicContent);
});
} else {
element.image = { ...element.image };
MainStore.dynamicData.push(element.image);
}
}
if (isMainElement && isClone) {
parentElement.parent.childrens.push(element);
} else if (!isMainElement) {
parentElement.childrens.push(element);
recursiveChildrens({ element, isClone, isMainElement: false });
}
};
export const recursiveChildrens = ({ element, isClone = false, isMainElement = true }) => {
const parentElement = element;
const childrensArray = parentElement.childrens;
isMainElement && childrensCleanUp(parentElement, element, isClone, isMainElement);
parentElement.childrens = [];
if (
parentElement.type == "rectangle" ||
(element.type == "page" && childrensArray.length > 0)
) {
childrensArray.forEach((element) => {
childrensCleanUp(parentElement, element, isClone, false);
});
}
};
export const updateElementParameters = (e) => {
const MainStore = useMainStore();
let parameters = MainStore.currentDrawListener.parameters;
let restrict = MainStore.currentDrawListener.restrict;
if (restrict && !e.metaKey && !e.ctrlKey) {
if (parameters.isReversedY) {
if (restrict.top > parameters.startY) {
MainStore.lastCreatedElement.startY = restrict.top;
MainStore.lastCreatedElement.height = Math.abs(
parameters.height - (restrict.top - parameters.startY)
);
} else {
MainStore.lastCreatedElement.startY = parameters.startY;
MainStore.lastCreatedElement.height = parameters.height;
}
} else {
if (restrict.bottom && restrict.bottom - parameters.startY < parameters.height) {
MainStore.lastCreatedElement.height = Math.abs(
restrict.bottom - parameters.startY
);
} else {
MainStore.lastCreatedElement.startY = parameters.startY;
MainStore.lastCreatedElement.height = parameters.height;
}
}
if (parameters.isReversedX) {
if (restrict.left > parameters.startX) {
MainStore.lastCreatedElement.startX = restrict.left;
MainStore.lastCreatedElement.width = Math.abs(
parameters.width - (restrict.left - parameters.startX)
);
} else {
MainStore.lastCreatedElement.startX = parameters.startX;
MainStore.lastCreatedElement.width = parameters.width;
}
} else {
if (restrict.right && restrict.right - parameters.startX < parameters.width) {
MainStore.lastCreatedElement.width = Math.abs(restrict.right - parameters.startX);
} else {
MainStore.lastCreatedElement.startX = parameters.startX;
MainStore.lastCreatedElement.width = parameters.width;
}
}
} else {
MainStore.lastCreatedElement.startX = parameters.startX;
MainStore.lastCreatedElement.startY = parameters.startY;
MainStore.lastCreatedElement.height = parameters.height;
MainStore.lastCreatedElement.width = parameters.width;
}
};
export const createHeaderFooterElement = (childrens, elementType) => {
const MainStore = useMainStore();
const ElementStore = useElementStore();
let id = frappe.utils.get_random(10);
const pageHeader = {
type: "rectangle",
childrens: [],
DOMRef: null,
id: id,
isDraggable: false,
isResizable: false,
isDropZone: true,
relativeContainer: true,
elementType: elementType,
startX: 0,
startY:
elementType == "header"
? 0
: MainStore.page.height -
MainStore.page.footerHeight -
MainStore.page.marginTop -
MainStore.page.marginBottom,
pageX: 0,
pageY: 0,
width: MainStore.page.width - MainStore.page.marginLeft - MainStore.page.marginRight,
height:
elementType == "header" ? MainStore.page.headerHeight : MainStore.page.footerHeight,
styleEditMode: "main",
style: { border: "none" },
classes: [],
};
pageHeader.childrens = childrens.map((el) => ElementStore.childrensSave(el));
ElementStore.setElementProperties(pageHeader);
return { ...pageHeader };
};
export const deleteSnapObjects = (element, recursive = false) => {
const MainStore = useMainStore();
if (!element || !element.snapPoints || !element.snapEdges) {
return;
}
element.snapPoints.forEach((point) => {
MainStore.snapPoints.splice(MainStore.snapPoints.indexOf(point), 1);
});
element.snapEdges.forEach((point) => {
MainStore.snapEdges.splice(MainStore.snapEdges.indexOf(point), 1);
});
if (
(recursive && element.type == "rectangle") ||
(element.type == "page" && element.childrens.length > 0)
) {
element.childrens.forEach((el) => {
deleteSnapObjects(el, recursive);
});
}
};
const deleteDynamicReferance = (curobj) => {
const MainStore = useMainStore();
if (curobj.type == "text" && curobj.isDynamic) {
curobj.dynamicContent.forEach((element) => {
MainStore.dynamicData.splice(MainStore.dynamicData.indexOf(element), 1);
});
} else if (curobj.type == "table") {
curobj.columns.forEach((element) => {
element?.dynamicContent?.forEach((el) => {
MainStore.dynamicData.splice(MainStore.dynamicData.indexOf(el), 1);
});
});
}
};
export const parseJinja = async (field, row) => {
if (field.value != "" && field.parseJinja) {
try {
// call render_user_text_withdoc method using frappe.call and return the result
const MainStore = useMainStore();
let result = await frappe.call({
method: "print_designer.print_designer.page.print_designer.print_designer.render_user_text_withdoc",
args: {
string: field.value,
doctype: MainStore.doctype,
docname: MainStore.currentDoc,
row: row,
send_to_jinja: MainStore.mainParsedJinjaData || {},
},
});
result = result.message;
if (result.success) {
return result.message;
} else {
console.error("Error From User Provided Jinja String\n\n", result.error);
}
} catch (error) {
console.error("Error in Jinja Template\n", { value_string: field.value, error });
frappe.show_alert(
{
message: "Unable Render Jinja Template. Please Check Console",
indicator: "red",
},
5
);
return field.value;
}
} else {
return field.value;
}
};
export const getFormattedValue = async (field, row = null) => {
const MainStore = useMainStore();
if (isRef(row)) {
row = row.value;
}
if (!row && field.tableName && Object.keys(MainStore.docData).length > 0) {
row = MainStore.docData[field.tableName][0];
}
const isDataAvailable = !!row || Object.keys(MainStore.docData).length > 0;
const formattedValue = ref(field.value);
if (field.is_static) {
if (field.parseJinja) {
formattedValue.value = await parseJinja(field, row);
}
} else if (row) {
if (field.fieldtype == "Image") {
formattedValue.value = frappe.format(
row[field.options],
{ fieldtype: "Image" },
{ inline: true },
row
);
formattedValue.value = `<img class="print-item-image" src="${formattedValue.value}" alt="">`;
} else if (isDataAvailable && typeof row[field.fieldname] != "undefined") {
formattedValue.value = frappe.format(
row[field.fieldname],
{ fieldtype: field.fieldtype, options: field.options },
{ inline: true },
row
);
} else {
formattedValue.value =
["Image, Attach Image"].indexOf(field.fieldtype) != -1
? null
: `{{ ${field.fieldname} }}`;
}
} else {
let rawValue = MainStore.docData[field.fieldname];
if (field.parentField) {
rawValue = await getValue(
field.doctype,
MainStore.docData[field.parentField],
field.fieldname
);
}
if (!(field.fieldtype == "Image") && !(field.fieldtype == "Attach Image")) {
formattedValue.value = frappe.format(
rawValue,
{ fieldtype: field.fieldtype, options: field.options },
{ inline: true },
MainStore.docData
);
} else {
formattedValue.value = rawValue;
}
if (!formattedValue.value) {
if (["Image", "Attach Image"].indexOf(field.fieldtype) != -1) {
formattedValue.value = null;
} else {
switch (field.fieldname) {
case "page":
formattedValue.value = "0";
break;
case "topage":
formattedValue.value = "999";
break;
case "date":
formattedValue.value = frappe.datetime.now_date();
break;
case "time":
formattedValue.value = frappe.datetime.now_time();
break;
default:
formattedValue.value = `{{ ${
field.parentField ? field.parentField + "." : ""
}${field.fieldname} }}`;
}
}
}
}
if (field.fieldtype == "Signature") {
formattedValue.value = `<img class="print-item-image" src="${formattedValue.value}" alt="">`;
}
return formattedValue.value;
};
export const updateDynamicData = async () => {
const MainStore = useMainStore();
if (!Object.keys(MainStore.docData).length) return;
MainStore.dynamicData.forEach(async (el) => {
if (el.is_static) return;
let row;
if (el.tableName) {
row = MainStore.docData[el.tableName];
row && (row = row[0]);
}
let value = await getFormattedValue(el, row);
if (typeof value == "string" && value.startsWith("<svg")) {
value.match(new RegExp(`data-barcode-value="(.*?)">`));
value = result[1];
}
if (!value) {
if (["Image, Attach Image"].indexOf(el.fieldtype) != -1) {
value = null;
} else {
switch (el.fieldname) {
case "page":
value = "0";
break;
case "topage":
value = "999";
break;
case "date":
value = frappe.datetime.now_date();
break;
case "time":
value = frappe.datetime.now_time();
break;
default:
value = `{{ ${el.parentField ? el.parentField + "." : ""}${
el.fieldname
} }}`;
}
}
}
el.value = value;
});
};
export const deleteCurrentElements = () => {
const MainStore = useMainStore();
const ElementStore = useElementStore();
if (MainStore.getCurrentElementsValues.length === 1) {
let curobj = MainStore.getCurrentElementsValues[0];
deleteDynamicReferance(curobj);
deleteSnapObjects(curobj.parent.childrens.splice(curobj.index, 1)[0], true);
} else {
MainStore.getCurrentElementsValues.forEach((element) => {
deleteSnapObjects(
element.parent.childrens.splice(element.parent.childrens.indexOf(element), 1)[0],
true
);
});
}
MainStore.lastCreatedElement = null;
MainStore.getCurrentElementsId.forEach((element) => {
delete MainStore.currentElements[element];
});
checkUpdateElementOverlapping();
};
export const cloneElement = () => {
const MainStore = useMainStore();
const clonedElements = {};
MainStore.getCurrentElementsValues.forEach((element) => {
const clonedElement = { ...element };
recursiveChildrens({ element: clonedElement, isClone: true });
clonedElements[clonedElement.id] = clonedElement;
});
MainStore.getCurrentElementsId.forEach((id) => {
delete MainStore.currentElements[id];
});
Object.entries(clonedElements).forEach((element) => {
MainStore.currentElements[element[0]] = element[1];
});
MainStore.lastCloned = clonedElements;
};
export const getSnapPointsAndEdges = (element) => {
const boundingRect = {};
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
boundingRect["x"] = entry.boundingClientRect.x;
boundingRect["y"] = entry.boundingClientRect.y;
}
observer.disconnect();
});
observer.observe(element.DOMRef);
const MainStore = useMainStore();
const rowSnapPoint = () => {
if (MainStore.getCurrentElementsId.indexOf(element.id) != -1) return;
return {
x: boundingRect.x + element.width,
y: boundingRect.y,
range: 10,
direction: "row-append",
};
};
MainStore.snapPoints.push(rowSnapPoint);
const columnSnapPoint = () => {
if (MainStore.getCurrentElementsId.indexOf(element.id) != -1) return;
observer.observe(element.DOMRef);
return {
x: boundingRect.x,
y: boundingRect.y + element.height,
range: 10,
direction: "column-append",
};
};
MainStore.snapPoints.push(columnSnapPoint);
const leftSnapEdge = () => {
if (MainStore.getCurrentElementsId.indexOf(element.id) != -1) return;
observer.observe(element.DOMRef);
return {
x: boundingRect.x,
range: 10,
direction: "row-append",
};
};
const rightSnapEdge = () => {
if (MainStore.getCurrentElementsId.indexOf(element.id) != -1) return;
observer.observe(element.DOMRef);
return {
x: boundingRect.x + element.width,
range: 10,
direction: "row-append",
};
};
MainStore.snapEdges.push(leftSnapEdge, rightSnapEdge);
const topSnapEdge = () => {
if (MainStore.getCurrentElementsId.indexOf(element.id) != -1) return;
observer.observe(element.DOMRef);
return {
y: boundingRect.y,
range: 10,
direction: "column-append",
};
};
const bottomSnapEdge = () => {
if (MainStore.getCurrentElementsId.indexOf(element.id) != -1) return;
observer.observe(element.DOMRef);
return {
y: boundingRect.y + element.height,
range: 10,
direction: "column-append",
};
};
MainStore.snapEdges.push(topSnapEdge, bottomSnapEdge);
return {
rowSnapPoint,
columnSnapPoint,
leftSnapEdge,
rightSnapEdge,
topSnapEdge,
bottomSnapEdge,
};
};
export const handleAlignIconClick = (value) => {
const MainStore = useMainStore();
let currentElements = MainStore.getCurrentElementsValues;
let parent;
MainStore.getCurrentElementsValues.forEach((element) => {
if (parent == null) {
if (element.parent.type == "page") {
parent = false;
return;
}
parent = element.parent;
} else if (parent != element.parent) {
parent = false;
return;
}
});
if (currentElements.length == 1) {
switch (value) {
case "alignTop":
MainStore.getCurrentElementsValues.forEach((element) => {
element.startY = 0;
});
break;
case "alignVerticalCenter":
MainStore.getCurrentElementsValues.forEach((element) => {
if (parent) {
element.startY = (element.parent.height - element.height) / 2;
} else {
element.startY =
(MainStore.page.height -
MainStore.page.marginTop -
MainStore.page.marginBottom -
element.height) /
2;
}
});
break;
case "alignBottom":
MainStore.getCurrentElementsValues.forEach((element) => {
if (parent) {
element.startY = element.parent.height - element.height;
} else {
element.startY =
MainStore.page.height -
MainStore.page.marginTop -
MainStore.page.marginBottom -
element.height;
}
});
break;
case "alignLeft":
MainStore.getCurrentElementsValues.forEach((element) => {
element.startX = 0;
});
break;
case "alignHorizontalCenter":
MainStore.getCurrentElementsValues.forEach((element) => {
if (parent) {
element.startX = (element.parent.width - element.width) / 2;
} else {
element.startX =
(MainStore.page.width -
MainStore.page.marginLeft -
MainStore.page.marginRight -
element.width) /
2;
}
});
break;
case "alignRight":
MainStore.getCurrentElementsValues.forEach((element) => {
if (parent) {
element.startX = element.parent.width - element.width;
} else {
element.startX =
MainStore.page.width -
MainStore.page.marginLeft -
MainStore.page.marginRight -
element.width;
}
});
break;
}
} else if (currentElements.length > 1) {
let parentRect = getParentPage(
MainStore.getCurrentElementsValues[0].parent
).DOMRef.getBoundingClientRect();
if (parent) {
parentRect = parent.DOMRef.getBoundingClientRect();
}
let offsetRect = MainStore.getCurrentElementsValues.reduce(
(offset, currentElement) => {
let currentElementRect = currentElement.DOMRef.getBoundingClientRect();
currentElementRect.left < offset.left && (offset.left = currentElementRect.left);
currentElementRect.top < offset.top && (offset.top = currentElementRect.top);
currentElementRect.right > offset.right &&
(offset.right = currentElementRect.right);
currentElementRect.bottom > offset.bottom &&
(offset.bottom = currentElementRect.bottom);
return offset;
},
{ left: 9999, top: 9999, right: 0, bottom: 0 }
);
(offsetRect.top -= parentRect.top), (offsetRect.left -= parentRect.left);
(offsetRect.right -= parentRect.left), (offsetRect.bottom -= parentRect.top);
switch (value) {
case "alignTop":
MainStore.getCurrentElementsValues.forEach((element) => {
element.startY = offsetRect.top;
});
break;
case "alignVerticalCenter":
MainStore.getCurrentElementsValues.forEach((element) => {
element.startY =
offsetRect.top +
(offsetRect.bottom - offsetRect.top) / 2 -
element.height / 2;
});
break;
case "alignBottom":
MainStore.getCurrentElementsValues.forEach((element) => {
element.startY = offsetRect.bottom - element.height;
});
break;
case "alignLeft":
MainStore.getCurrentElementsValues.forEach((element) => {
element.startX = offsetRect.left;
});
break;
case "alignHorizontalCenter":
MainStore.getCurrentElementsValues.forEach((element) => {
element.startX =
offsetRect.left +
(offsetRect.right - offsetRect.left) / 2 -
element.width / 2;
});
break;
case "alignRight":
MainStore.getCurrentElementsValues.forEach((element) => {
element.startX = offsetRect.right - element.width;
});
break;
}
}
};
export const handleBorderIconClick = (element, icon) => {
if (icon == "borderAll") {
if (
["borderTopStyle", "borderBottomStyle", "borderLeftStyle", "borderRightStyle"].every(
(side) => element[side] != "hidden"
)
) {
element["borderTopStyle"] = "hidden";
element["borderBottomStyle"] = "hidden";
element["borderLeftStyle"] = "hidden";
element["borderRightStyle"] = "hidden";
} else {
delete element["borderTopStyle"];
delete element["borderBottomStyle"];
delete element["borderLeftStyle"];
delete element["borderRightStyle"];
}
} else {
if (element[icon] != "hidden") {
element[icon] = "hidden";
} else {
delete element[icon];
}
}
};
export const getParentPage = (element) => {
if (!element) return;
if (element.type == "page") {
return element;
} else {
if (element.parent) {
return getParentPage(element.parent);
}
return;
}
};
export const isInHeaderFooter = (element) => {
if (!element) return false;
if (!element.parent) return false;
if (element.elementType == "header") {
return true;
} else {
return isInHeaderFooter(element.parent);
}
};
const getGlobalStyleObject = (object = null, checkProperty = null) => {
const MainStore = useMainStore();
let globalStyleName = MainStore.activeControl;
if (globalStyleName == "text") {
if (MainStore.textControlType == "dynamic") {
globalStyleName = "dynamicText";
} else {
globalStyleName = "staticText";
}
}
if (object) {
globalStyleName = object.type;
if (globalStyleName == "text") {
if (object.isDynamic) {
globalStyleName = "dynamicText";
} else {
globalStyleName = "staticText";
}
}
}
switch (MainStore.globalStyles[globalStyleName].styleEditMode) {
case "main":
return MainStore.globalStyles[globalStyleName].style;
case "label":
return MainStore.globalStyles[globalStyleName].labelStyle;
case "header":
return MainStore.globalStyles[globalStyleName].headerStyle;
case "alt":
if (checkProperty && MainStore.globalStyles[globalStyleName].altStyle[checkProperty]) {
return MainStore.globalStyles[globalStyleName].altStyle;
} else {
return MainStore.globalStyles[globalStyleName].style;
}
}
};
export const getConditonalObject = (field) => {
let object = field.reactiveObject;
let property = field.property;
if (typeof object == "function") {
object = object();
}
isRef(object) && (object = object.value);
let orignalObject = object;
if (field.isStyle) {
if (object) {
switch (object.styleEditMode) {
case "main":
if (field.isFontStyle) {
object =
object.selectedDynamicText?.style ||
object.selectedColumn?.style ||
object.style;
} else {
object = object.selectedColumn?.style || object.style;
}
break;
case "label":
if (field.isFontStyle) {
object = object.selectedDynamicText?.labelStyle || object.labelStyle;
} else {
object = object.labelStyle;
}
break;
case "header":
if (field.isFontStyle) {
object = object.selectedDynamicText?.headerStyle || object.headerStyle;
} else {
object = object.headerStyle;
}
break;
case "alt":
if (field.isFontStyle) {
// This is not implemented yet but will be implemented in future if user requests it.
object = object.selectedDynamicText?.altStyle || object.altStyle;
} else {
object = object.altStyle;
}
// Incase There is no Alternate Style Fallback to All Row/Main Style
if (property && !object[property]) {
object = orignalObject.style;
}
break;
}
if (property) {
if (object[property]) return object[property];
return getGlobalStyleObject(orignalObject, property)[property];
}
} else {
return getGlobalStyleObject();
}
}
if (property) {
return object[property];
}
return object;
};
export const handlePrintFonts = (element, printFonts) => {
const MainStore = useMainStore();
const pushFonts = ({ el = null, styleEditMode, globalStyleName }) => {
let fontFamily =
el?.[styleEditMode]?.["fontFamily"] ||
element[styleEditMode]["fontFamily"] ||
MainStore.globalStyles[globalStyleName][styleEditMode]["fontFamily"];
let fontWeight =
el?.[styleEditMode]?.["fontWeight"] ||
element[styleEditMode]["fontWeight"] ||
MainStore.globalStyles[globalStyleName][styleEditMode]["fontWeight"];
let fontStyle =
el?.[styleEditMode]?.["fontStyle"] ||
element[styleEditMode]["fontStyle"] ||
MainStore.globalStyles[globalStyleName][styleEditMode]["fontStyle"];
// fallback to main style if not available in altstyle
if (styleEditMode == "altStyle") {
if (!fontFamily) {
fontFamily =
el?.["style"]?.["fontFamily"] ||
element["style"]["fontFamily"] ||
MainStore.globalStyles[globalStyleName]["style"]["fontFamily"];
}
if (!fontWeight) {
fontWeight =
el?.["style"]?.["fontWeight"] ||
element["style"]["fontWeight"] ||
MainStore.globalStyles[globalStyleName]["style"]["fontWeight"];
}
if (!fontStyle) {
fontStyle =
el?.["style"]?.["fontStyle"] ||
element["style"]["fontStyle"] ||
MainStore.globalStyles[globalStyleName]["style"]["fontStyle"];
}
}
if (!fontFamily || !fontWeight || !fontStyle) return;
if (!printFonts[fontFamily]) {
printFonts[fontFamily] = {
weight: [],
italic: [],
};
}
let weightArray = fontStyle == "italic" ? "italic" : "weight";
if (printFonts[fontFamily][weightArray].indexOf(parseInt(fontWeight)) == -1) {
printFonts[fontFamily][weightArray].push(parseInt(fontWeight));
printFonts[fontFamily][weightArray].sort();
}
};
let styleModes = ["style"];
if (element.type == "text" && element.isDynamic) {
styleModes.push("labelStyle");
}
if (element.type == "table") {
styleModes.push("headerStyle");
styleModes.push("altStyle");
}
styleModes.forEach((styleEditMode) => {
let globalStyleName = element.type;
if (globalStyleName == "text") {
if (element.isDynamic) {
globalStyleName = "dynamicText";
} else {
globalStyleName = "staticText";
}
}
pushFonts({ styleEditMode, globalStyleName });
if (element.dynamicContent) {
element.dynamicContent.forEach((el) => {
if (["headerStyle", "altStyle"].indexOf(styleEditMode) == -1) {
pushFonts({ el, styleEditMode, globalStyleName });
}
});
} else if (element.columns) {
if (["headerStyle", "altStyle"].indexOf(styleEditMode) != -1) {
pushFonts({ el: element, styleEditMode, globalStyleName });
} else {
element.columns.forEach((col) => {
col.dynamicContent?.forEach((el) => {
pushFonts({ el, styleEditMode, globalStyleName });
});
});
}
}
});
};
export const selectElementContents = (el) => {
const range = document.createRange();
range.selectNodeContents(el);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
};
export const checkUpdateElementOverlapping = (element = null) => {
const MainStore = useMainStore();
const ElementStore = useElementStore();
nextTick(() => {
if (!element || element.parent.type != "page") return;
isOlderSchema = MainStore.isOlderSchema("1.1.0");
element.parent.childrens.forEach((el) => {
const isElementOverlapping = ElementStore.isElementOverlapping(el);
if (el.isElementOverlapping != isElementOverlapping) {
el.isElementOverlapping = isElementOverlapping;
}
if (isOlderSchema && el.type == "table" && !isElementOverlapping) {
el.heightType = "auto";
}
});
}, {});
};
|
2302_79757062/print_designer
|
print_designer/public/js/print_designer/utils.js
|
JavaScript
|
agpl-3.0
| 31,240
|
import frappe
from print_designer.custom_fields import CUSTOM_FIELDS
def delete_custom_fields(custom_fields):
"""
:param custom_fields: a dict like `{'Sales Invoice': [{fieldname: 'test', ...}]}`
"""
for doctypes, fields in custom_fields.items():
if isinstance(fields, dict):
# only one field
fields = [fields]
if isinstance(doctypes, str):
# only one doctype
doctypes = (doctypes,)
for doctype in doctypes:
frappe.db.delete(
"Custom Field",
{
"fieldname": ("in", [field["fieldname"] for field in fields]),
"dt": doctype,
},
)
frappe.clear_cache(doctype=doctype)
def before_uninstall():
delete_custom_fields(CUSTOM_FIELDS)
|
2302_79757062/print_designer
|
print_designer/uninstall.py
|
Python
|
agpl-3.0
| 686
|
#!bin/bash
set -e
if [[ -f "/workspaces/frappe_codespace/frappe-bench/apps/frappe" ]]
then
echo "Bench already exists, skipping init"
exit 0
fi
rm -rf /workspaces/frappe_codespace/.git
source /home/frappe/.nvm/nvm.sh
nvm alias default 18
nvm use 18
echo "nvm use 18" >> ~/.bashrc
cd /workspace
bench init \
--ignore-exist \
--skip-redis-config-generation \
frappe-bench
cd frappe-bench
# Use containers instead of localhost
bench set-mariadb-host mariadb
bench set-redis-cache-host redis-cache:6379
bench set-redis-queue-host redis-queue:6379
bench set-redis-socketio-host redis-socketio:6379
# Remove redis from Procfile
sed -i '/redis/d' ./Procfile
bench new-site dev.localhost \
--mariadb-root-password 123 \
--admin-password admin \
--no-mariadb-socket
bench --site dev.localhost set-config developer_mode 1
bench --site dev.localhost clear-cache
bench use dev.localhost
bench get-app print_designer
bench --site dev.localhost install-app print_designer
|
2302_79757062/print_designer
|
scripts/init.sh
|
Shell
|
agpl-3.0
| 977
|