rename to templates

This commit is contained in:
Alex Turchyn
2023-05-31 23:19:20 +03:00
parent 98fc9d964a
commit 4a303cb423
59 changed files with 248 additions and 264 deletions
+102
View File
@@ -0,0 +1,102 @@
<template>
<div
class="bg-red-100 absolute opacity-70"
:style="positionStyle"
@mousedown="startDrag"
>
<div
v-if="field"
class="flex items-center justify-center h-full w-full"
>
{{ field?.name || field.type }}
</div>
<span
class="h-2 w-2 right-0 bottom-0 bg-red-900 absolute cursor-nwse-resize"
@mousedown.stop="startResize"
/>
</div>
</template>
<script>
export default {
name: 'FieldArea',
props: {
bounds: {
type: Object,
required: false,
default () {
return {
x: 0,
y: 0,
w: 0,
h: 0
}
}
},
field: {
type: Object,
required: false,
default: null
}
},
emits: ['start-resize', 'stop-resize', 'start-drag', 'stop-drag'],
data () {
return {
isResize: false,
dragFrom: { x: 0, y: 0 }
}
},
computed: {
positionStyle () {
const { x, y, w, h } = this.bounds
return {
top: y * 100 + '%',
left: x * 100 + '%',
width: w * 100 + '%',
height: h * 100 + '%'
}
}
},
methods: {
resize (e) {
this.bounds.w = e.layerX / e.toElement.clientWidth - this.bounds.x
this.bounds.h = e.layerY / e.toElement.clientHeight - this.bounds.y
},
drag (e) {
if (e.toElement.id === 'mask') {
this.bounds.x = (e.layerX - this.dragFrom.x) / e.toElement.clientWidth
this.bounds.y = (e.layerY - this.dragFrom.y) / e.toElement.clientHeight
}
},
startDrag (e) {
const rect = e.target.getBoundingClientRect()
this.dragFrom = { x: e.clientX - rect.left, y: e.clientY - rect.top }
document.addEventListener('mousemove', this.drag)
document.addEventListener('mouseup', this.stopDrag)
this.$emit('start-drag')
},
stopDrag () {
document.removeEventListener('mousemove', this.drag)
document.removeEventListener('mouseup', this.stopDrag)
this.$emit('stop-drag')
},
startResize () {
document.addEventListener('mousemove', this.resize)
document.addEventListener('mouseup', this.stopResize)
this.$emit('start-resize')
},
stopResize () {
document.removeEventListener('mousemove', this.resize)
document.removeEventListener('mouseup', this.stopResize)
this.$emit('stop-resize')
}
}
}
</script>
+252
View File
@@ -0,0 +1,252 @@
<template>
<div
style="max-width: 1600px"
class="mx-auto px-4"
>
<div class="flex justify-between py-1.5 items-center">
<Contenteditable
:model-value="template.name"
class="text-3xl focus:text-clip"
@update:model-value="updateName"
/>
<div class="space-x-3 flex items-center">
<a
:href="`/templates/${template.id}/submissions`"
class="btn btn-primary"
>
<IconUsersPlus
width="20"
class="mr-2 inline"
/>
Recipients
</a>
<a
:href="`/`"
class="base-button"
v-bind="isSaving ? { disabled: true } : {}"
@click.prevent="onSaveClick"
><IconDeviceFloppy
width="20"
class="mr-2"
/>Save</a>
</div>
</div>
<div
class="flex"
style="max-height: calc(100vh - 60px)"
>
<div
ref="previews"
class="overflow-auto w-52 flex-none pr-4 mt-0.5 pt-0.5"
>
<DocumentPreview
v-for="(item, index) in template.schema"
:key="index"
:with-arrows="template.schema.length > 1"
:item="item"
:document="sortedDocuments[index]"
@scroll-to="scrollIntoDocument(item)"
@remove="onDocumentRemove"
@up="moveDocument(item, -1)"
@down="moveDocument(item, 1)"
@change="save"
/>
<div class="sticky bottom-0 bg-base-100 py-2">
<Upload
:template-id="template.id"
@success="updateFromUpload"
/>
</div>
</div>
<div class="w-full overflow-y-auto overflow-x-hidden mt-0.5 pt-0.5">
<div class="px-3">
<Document
v-for="document in sortedDocuments"
:key="document.uuid"
:ref="setDocumentRefs"
:areas-index="fieldAreasIndex[document.uuid]"
:document="document"
:is-draw="!!drawField"
:is-drag="!!dragFieldType"
@draw="onDraw"
@drop-field="onDropfield"
/>
</div>
</div>
<div
class="relative w-72 flex-none"
:class="drawField ? 'overflow-hidden' : 'overflow-auto'"
>
<div
v-if="drawField"
class="sticky inset-0 bg-white h-full"
>
Draw {{ drawField.name }} field on the page
<button @click="drawField = false">
Cancel
</button>
</div>
<div>
FIelds
<Fields
ref="fields"
v-model:fields="template.fields"
@set-draw="drawField = $event"
@set-drag="dragFieldType = $event"
@drag-end="dragFieldType = null"
/>
</div>
</div>
</div>
</div>
</template>
<script>
import Upload from './upload'
import Fields from './fields'
import Document from './document'
import Contenteditable from './contenteditable'
import DocumentPreview from './preview'
import { IconUsersPlus, IconDeviceFloppy } from '@tabler/icons-vue'
export default {
name: 'TemplateBuilder',
components: {
Upload,
Document,
Fields,
DocumentPreview,
Contenteditable,
IconUsersPlus,
IconDeviceFloppy
},
props: {
template: {
type: Object,
required: true
}
},
data () {
return {
documentRefs: [],
isSaving: false,
drawField: null,
dragFieldType: null
}
},
computed: {
fieldAreasIndex () {
const areas = {}
this.template.fields.forEach((f) => {
(f.areas || []).forEach((a) => {
areas[a.attachment_uuid] ||= {}
const acc = (areas[a.attachment_uuid][a.page] ||= [])
acc.push({ area: a, field: f })
})
})
return areas
},
sortedDocuments () {
return this.template.schema.map((item) => {
return this.template.documents.find(doc => doc.uuid === item.attachment_uuid)
})
}
},
mounted () {
document.addEventListener('keyup', this.disableDrawOnEsc)
},
unmounted () {
document.removeEventListener('keyup', this.disableDrawOnEsc)
},
beforeUpdate () {
this.documentRefs = []
},
methods: {
setDocumentRefs (el) {
if (el) {
this.documentRefs.push(el)
}
},
scrollIntoDocument (item) {
const ref = this.documentRefs.find((e) => e.document.uuid === item.attachment_uuid)
ref.$el.scrollIntoView({ behavior: 'smooth', block: 'start' })
},
disableDrawOnEsc (e) {
if (e.code === 'Escape') {
this.drawField = null
}
},
onDraw (area) {
this.drawField.areas ||= []
this.drawField.areas.push(area)
this.drawField = null
},
onDropfield (area) {
this.$refs.fields.addField(this.dragFieldType, area)
},
updateFromUpload ({ schema, documents }) {
this.template.schema.push(...schema)
this.template.documents.push(...documents)
this.$nextTick(() => {
this.$refs.previews.scrollTop = this.$refs.previews.scrollHeight
this.scrollIntoDocument(schema[0])
})
this.save()
},
updateName (value) {
this.template.name = value
this.save()
},
onDocumentRemove (item) {
if (window.confirm('Are you sure?')) {
this.template.schema.splice(this.template.schema.indexOf(item), 1)
}
this.save()
},
moveDocument (item, direction) {
const currentIndex = this.template.schema.indexOf(item)
this.template.schema.splice(currentIndex, 1)
if (currentIndex + direction > this.template.schema.length) {
this.template.schema.unshift(item)
} else if (currentIndex + direction < 0) {
this.template.schema.push(item)
} else {
this.template.schema.splice(currentIndex + direction, 0, item)
}
this.save()
},
onSaveClick () {
this.isSaving = true
this.save().then(() => {
window.Turbo.visit('/')
}).finally(() => {
this.isSaving = false
})
},
save () {
return fetch(`/api/templates/${this.template.id}`, {
method: 'PUT',
body: JSON.stringify({ template: this.template }),
headers: { 'Content-Type': 'application/json' }
}).then((resp) => {
console.log(resp)
})
}
}
}
</script>
@@ -0,0 +1,71 @@
<template>
<div class="group flex items-center relative overflow-visible">
<div
ref="contenteditable"
contenteditable
style="min-width: 2px"
class="peer outline-none"
@keydown.enter.prevent="onEnter"
@blur="onBlur"
>
{{ value }}
</div>
<IconPencil
contenteditable="false"
class="absolute ml-1 cursor-pointer inline opacity-0 group-hover:opacity-100 peer-focus:opacity-0 align-middle"
:style="{ right: -(1.1 * iconWidth) + 'px' }"
:width="iconWidth"
@click="onPencilClick"
/>
</div>
</template>
<script>
import { IconPencil } from '@tabler/icons-vue'
export default {
name: 'ContenteditableField',
components: {
IconPencil
},
props: {
modelValue: {
type: String,
required: false,
default: ''
},
iconWidth: {
type: Number,
required: false,
default: 30
}
},
emits: ['update:model-value'],
data () {
return {
value: ''
}
},
watch: {
modelValue: {
handler (value) {
this.value = value
},
immediate: true
}
},
methods: {
onBlur (e) {
this.value = this.$refs.contenteditable.innerText.trim() || this.modelValue
this.$emit('update:model-value', this.value)
},
onPencilClick () {
this.$refs.contenteditable.focus()
},
onEnter () {
this.$refs.contenteditable.blur()
}
}
}
</script>
@@ -0,0 +1,53 @@
<template>
<div>
<Page
v-for="(image, index) in sortedPreviewImages"
:key="image.id"
:number="index"
:areas="areasIndex[index]"
:is-draw="isDraw"
:is-drag="isDrag"
:class="{ 'cursor-crosshair': isDraw }"
:image="image"
@drop-field="$emit('drop-field', {...$event, attachment_uuid: document.uuid })"
@draw="$emit('draw', {...$event, attachment_uuid: document.uuid })"
/>
</div>
</template>
<script>
import Page from './page'
export default {
name: 'TemplateDocument',
components: {
Page
},
props: {
document: {
type: Object,
required: true
},
areasIndex: {
type: Object,
required: false,
default: () => ({})
},
isDraw: {
type: Boolean,
required: false,
default: false
},
isDrag: {
type: Boolean,
required: false,
default: false
}
},
emits: ['draw', 'drop-field'],
computed: {
sortedPreviewImages () {
return [...this.document.preview_images].sort((a, b) => parseInt(a.filename) - parseInt(b.filename))
}
}
}
</script>
+89
View File
@@ -0,0 +1,89 @@
<template>
<div>
<button @click="$emit('remove', field)">
Remove
</button>
<div>
{{ field.type }}
</div>
<div v-if="field.type !== 'signature'">
<label>Name</label>
<input
v-model="field.name"
type="text"
required
>
</div>
<div>
<div
v-for="(option, index) in field.options"
:key="index"
class="flex"
>
<input
v-model="field.options[index]"
type="text"
required
>
<button @click="field.options.splice(index, 1)">
Remove
</button>
</div>
<button
v-if="field.options"
@click="field.options.push('')"
>
Add option
</button>
</div>
<div>
<div
v-for="(area, index) in areas"
:key="index"
>
Area {{ index + 1 }}
<button @click="removeArea(area)">
&times;
</button>
</div>
<button
class="block"
@click="$emit('set-draw', field)"
>
Draw area
</button>
</div>
<div>
<input
:id="`field_required_${field.uuid}`"
v-model="field.required"
type="checkbox"
required
>
<label :for="`field_required_${field.uuid}`">Required</label>
</div>
</div>
</template>
<script>
export default {
name: 'TemplateField',
props: {
field: {
type: Object,
required: true
}
},
emits: ['set-draw', 'remove'],
computed: {
areas () {
return this.field.areas || []
}
},
methods: {
removeArea (area) {
this.field.areas.splice(this.field.areas.indexOf(area), 1)
}
}
}
</script>
+101
View File
@@ -0,0 +1,101 @@
<template>
<div class="space-y-2">
<Field
v-for="field in fields"
:key="field.uuid"
class="border"
:field="field"
@remove="fields.splice(fields.indexOf($event), 1)"
@set-draw="$emit('set-draw', $event)"
/>
</div>
<button
v-for="item in fieldTypes"
:key="item.type"
draggable="true"
class="w-full flex items-center justify-center"
@dragstart="onDragstart(item.value)"
@dragend="$emit('drag-end')"
@click="addField(item.value)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="cursor-move"
width="18"
height="18"
viewBox="0 0 24 24"
stroke-width="2"
stroke="currentColor"
fill="none"
stroke-linecap="round"
stroke-linejoin="round"
>
<path
stroke="none"
d="M0 0h24v24H0z"
fill="none"
/>
<path d="M4 6l16 0" />
<path d="M4 12l16 0" />
<path d="M4 18l16 0" />
</svg>
Add {{ item.label }}
&plus;
</button>
</template>
<script>
import Field from './field'
import { v4 } from 'uuid'
export default {
name: 'TemplateFields',
components: {
Field
},
props: {
fields: {
type: Array,
required: true
}
},
emits: ['set-draw', 'set-drag', 'drag-end'],
computed: {
fieldTypes () {
return [
{ label: 'Text', value: 'text' },
{ label: 'Signature', value: 'signature' },
{ label: 'Date', value: 'date' },
{ label: 'Image', value: 'image' },
{ label: 'Attachment', value: 'attachment' },
{ label: 'Select', value: 'select' },
{ label: 'Checkbox', value: 'checkbox' },
{ label: 'Radio Group', value: 'radio' }
]
}
},
methods: {
onDragstart (fieldType) {
this.$emit('set-drag', fieldType)
},
addField (type, area = null) {
const field = {
name: type === 'signature' ? 'Signature' : '',
uuid: v4(),
required: true,
type
}
if (['select', 'checkbox', 'radio'].includes(type)) {
field.options = ['']
}
if (area) {
field.areas = [area]
}
this.fields.push(field)
}
}
}
</script>
+149
View File
@@ -0,0 +1,149 @@
<template>
<div class="relative">
<img
ref="image"
:src="image.url"
:width="width"
class="shadow-md mb-4"
:height="height"
loading="lazy"
>
<div
class="top-0 bottom-0 left-0 right-0 absolute"
>
<FieldArea
v-for="(item, i) in areas"
:key="i"
:bounds="item.area"
:field="item.field"
@start-resize="showMask = true"
@stop-resize="showMask = false"
@start-drag="showMask = true"
@stop-drag="showMask = false"
/>
<FieldArea
v-if="newArea"
:bounds="newArea"
/>
</div>
<div
v-show="isDraw || isDrag || showMask"
id="mask"
ref="mask"
class="top-0 bottom-0 left-0 right-0 absolute"
@pointerdown="onPointerdown"
@pointermove="onPointermove"
@dragover.prevent
@drop="onDrop"
@pointerup="onPointerup"
/>
</div>
</template>
<script>
import FieldArea from './area'
export default {
name: 'TemplatePage',
components: {
FieldArea
},
props: {
image: {
type: Object,
required: true
},
areas: {
type: Array,
required: false,
default: () => []
},
isDraw: {
type: Boolean,
required: false,
default: false
},
isDrag: {
type: Boolean,
required: false,
default: false
},
number: {
type: Number,
required: true
}
},
emits: ['draw', 'drop-field'],
data () {
return {
showMask: false,
newArea: null
}
},
computed: {
width () {
return this.image.metadata.width
},
height () {
return this.image.metadata.height
}
},
methods: {
onDrop (e) {
this.$emit('drop-field', {
x: e.layerX / this.$refs.mask.clientWidth,
y: e.layerY / this.$refs.mask.clientHeight - (this.$refs.mask.clientWidth / 30 / this.$refs.mask.clientWidth) / 2,
w: this.$refs.mask.clientWidth / 5 / this.$refs.mask.clientWidth,
h: this.$refs.mask.clientWidth / 30 / this.$refs.mask.clientWidth,
page: this.number
})
},
onPointerdown (e) {
if (this.isDraw) {
this.newArea = {
initialX: e.layerX / this.$refs.mask.clientWidth,
initialY: e.layerY / this.$refs.mask.clientHeight,
x: e.layerX / this.$refs.mask.clientWidth,
y: e.layerY / this.$refs.mask.clientHeight,
w: 0,
h: 0
}
}
},
onPointermove (e) {
if (this.newArea) {
const dx = e.layerX / this.$refs.mask.clientWidth - this.newArea.initialX
const dy = e.layerY / this.$refs.mask.clientHeight - this.newArea.initialY
if (dx > 0) {
this.newArea.x = this.newArea.initialX
} else {
this.newArea.x = e.layerX / this.$refs.mask.clientWidth
}
if (dy > 0) {
this.newArea.y = this.newArea.initialY
} else {
this.newArea.y = e.layerY / this.$refs.mask.clientHeight
}
this.newArea.w = Math.abs(dx)
this.newArea.h = Math.abs(dy)
}
},
onPointerup (e) {
if (this.isDraw && this.newArea) {
this.$emit('draw', {
x: this.newArea.x,
y: this.newArea.y,
w: Math.max(this.newArea.w, this.$refs.mask.clientWidth / 5 / this.$refs.mask.clientWidth),
h: Math.max(this.newArea.h, this.$refs.mask.clientWidth / 30 / this.$refs.mask.clientWidth),
page: this.number
})
}
this.newArea = null
}
}
}
</script>
@@ -0,0 +1,94 @@
<template>
<div>
<div class="relative">
<img
:src="previewImage.url"
:width="previewImage.metadata.width"
:height="previewImage.metadata.height"
class="rounded border"
loading="lazy"
>
<div
class="group flex justify-end cursor-pointer top-0 bottom-0 left-0 right-0 absolute"
@click="$emit('scroll-to', item)"
>
<div
class="flex flex-col justify-between opacity-0 group-hover:opacity-100"
>
<div>
<button
class="px-1.5 rounded bg-white border border-red-400 text-red-400 hover:bg-red-50"
@click.stop="$emit('remove', item)"
>
&times;
</button>
</div>
<div
v-if="withArrows"
class="flex flex-col"
>
<button
class="px-1.5"
@click.stop="$emit('up', item)"
>
&uarr;
</button>
<button
class="px-1.5"
@click.stop="$emit('down', item)"
>
&darr;
</button>
</div>
</div>
</div>
</div>
<div class="flex py-2">
<Contenteditable
:model-value="item.name"
:icon-width="16"
class="mx-auto"
@update:model-value="onUpdateName"
/>
</div>
</div>
</template>
<script>
import Contenteditable from './contenteditable'
export default {
name: 'DocumentPreview',
components: {
Contenteditable
},
props: {
item: {
type: Object,
required: true
},
document: {
type: Object,
required: true
},
withArrows: {
type: Boolean,
required: false,
default: true
}
},
emits: ['scroll-to', 'change', 'remove', 'up', 'down'],
computed: {
previewImage () {
return this.document.preview_images[0]
}
},
methods: {
onUpdateName (value) {
this.item.name = value
this.$emit('change')
}
}
}
</script>
@@ -0,0 +1,92 @@
<template>
<div>
<label
:for="inputId"
class="btn btn-outline w-full"
:class="{ 'btn-disabled': isLoading }"
>
<IconUpload
width="20"
class="mr-2"
/>
Add Document
</label>
<input
:id="inputId"
ref="input"
type="file"
class="hidden"
multiple
@change="upload"
>
</div>
</template>
<script>
import { DirectUpload } from '@rails/activestorage'
import { IconUpload } from '@tabler/icons-vue'
export default {
name: 'DocumentsUpload',
components: {
IconUpload
},
props: {
templateId: {
type: [Number, String],
required: true
}
},
emits: ['success'],
data () {
return {
isLoading: false
}
},
computed: {
inputId () {
return 'el' + Math.random().toString(32).split('.')[1]
}
},
methods: {
async upload () {
this.isLoading = true
const blobs = await Promise.all(
Array.from(this.$refs.input.files).map(async (file) => {
const upload = new DirectUpload(
file,
'/direct_uploads',
this.$refs.input
)
return new Promise((resolve, reject) => {
upload.create((error, blob) => {
if (error) {
console.error(error)
return reject(error)
} else {
return resolve(blob)
}
})
}).catch((error) => {
console.error(error)
})
})
)
fetch(`/api/templates/${this.templateId}/documents`, {
method: 'POST',
body: JSON.stringify({ blobs }),
headers: { 'Content-Type': 'application/json' }
}).then(resp => resp.json()).then((data) => {
this.$emit('success', data)
this.$refs.input.value = ''
}).finally(() => {
this.isLoading = false
})
}
}
}
</script>