initial commit

This commit is contained in:
Alex Turchyn
2023-05-21 17:59:36 +03:00
commit 97c462ead2
159 changed files with 10987 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
import '@hotwired/turbo-rails'
import { createApp } from 'vue'
import ToggleVisible from './elements/toggle_visible'
import DisableHidden from './elements/disable_hidden'
import TurboModal from './elements/turbo_modal'
import FlowArea from './elements/flow_area'
import FlowView from './elements/flow_view'
import Builder from './components/builder'
window.customElements.define('toggle-visible', ToggleVisible)
window.customElements.define('disable-hidden', DisableHidden)
window.customElements.define('turbo-modal', TurboModal)
window.customElements.define('flow-view', FlowView)
window.customElements.define('flow-area', FlowArea)
window.customElements.define('flow-builder', class extends HTMLElement {
connectedCallback () {
this.appElem = document.createElement('div')
this.app = createApp(Builder, {
dataFlow: this.dataset.flow
})
this.app.mount(this.appElem)
this.appendChild(this.appElem)
}
disconnectedCallback () {
this.app?.unmount()
this.appElem?.remove()
}
})
+32
View File
@@ -0,0 +1,32 @@
@config "../../tailwind.application.config.js";
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
a[href],
input[type='checkbox'],
input[type='submit'],
input[type='image'],
input[type='radio'],
label[for],
select,
button {
cursor: pointer;
}
button .disabled {
display: none;
}
button[disabled] .disabled {
display: initial;
}
button .enabled {
display: initial;
}
button[disabled] .enabled {
display: none;
}
+107
View File
@@ -0,0 +1,107 @@
<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: {
scale: {
type: Number,
required: false,
default: 1
},
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: this.scale * y + 'px',
left: this.scale * x + 'px',
width: this.scale * w + 'px',
height: this.scale * h + 'px'
}
}
},
methods: {
resize (e) {
this.bounds.w = e.layerX / this.scale - this.bounds.x
this.bounds.h = e.layerY / this.scale - this.bounds.y
},
drag (e) {
if (e.toElement.id === 'mask') {
this.bounds.x = (e.layerX - this.dragFrom.x) / this.scale
this.bounds.y = (e.layerY - this.dragFrom.y) / this.scale
}
},
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>
+154
View File
@@ -0,0 +1,154 @@
<template>
<div
class="flex"
style="max-height: calc(100vh - 24px)"
>
<div
class="overflow-auto w-full"
style="max-width: 280px"
>
Show documents preview (not pages but documents)
Allow to edit name
Allow to reorder
{{ flow.schema }}
<Upload
:flow-id="flow.id"
@success="updateFromUpload"
/>
<button
class="bg-green-300"
@click="save"
>
Save changes
</button>
<a
:href="`/flows/${flow.id}/submissions`"
>
Add Recepients
</a>
</div>
<div class="w-full overflow-auto">
<Document
v-for="document in sortedDocuments"
:key="document.uuid"
:areas-index="fieldAreasIndex[document.uuid]"
:document="document"
:is-draw="!!drawField"
@draw="onDraw"
/>
</div>
<div
class="w-full relative"
:class="drawField ? 'overflow-hidden' : 'overflow-auto'"
style="max-width: 280px"
>
<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
v-model:fields="flow.fields"
@set-draw="drawField = $event"
/>
</div>
</div>
</div>
</template>
<script>
import Upload from './upload'
import Fields from './fields'
import Document from './document'
export default {
name: 'FlowBuilder',
components: {
Upload,
Document,
Fields
},
props: {
dataFlow: {
type: String,
default: '{}'
}
},
data () {
return {
drawField: null,
flow: {
name: '',
schema: [],
documents: [],
fields: []
}
}
},
computed: {
fieldAreasIndex () {
const areas = {}
this.flow.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.flow.schema.map((item) => {
return this.flow.documents.find(doc => doc.uuid === item.attachment_uuid)
})
}
},
mounted () {
this.flow = JSON.parse(this.dataFlow)
document.addEventListener('keyup', this.disableDrawOnEsc)
},
unmounted () {
document.removeEventListener('keyup', this.disableDrawOnEsc)
},
methods: {
disableDrawOnEsc (e) {
if (e.code === 'Escape') {
this.drawField = null
}
},
onDraw (area) {
this.drawField.areas ||= []
this.drawField.areas.push(area)
this.drawField = null
},
updateFromUpload ({ schema, documents }) {
this.flow.schema.push(...schema)
this.flow.documents.push(...documents)
this.save()
},
save () {
return fetch(`/api/flows/${this.flow.id}`, {
method: 'PUT',
body: JSON.stringify({ flow: this.flow }),
headers: { 'Content-Type': 'application/json' }
}).then((resp) => {
console.log(resp)
})
}
}
}
</script>
+44
View File
@@ -0,0 +1,44 @@
<template>
<Page
v-for="(image, index) in sortedPreviewImages"
:key="image.id"
:number="index"
:areas="areasIndex[index]"
:is-draw="isDraw"
:class="{ 'cursor-crosshair': isDraw }"
:image="image"
@draw="$emit('draw', {...$event, attachment_uuid: document.uuid })"
/>
</template>
<script>
import Page from './page'
export default {
name: 'FlowDocument',
components: {
Page
},
props: {
document: {
type: Object,
required: true
},
areasIndex: {
type: Object,
required: false,
default: () => ({})
},
isDraw: {
type: Boolean,
required: false,
default: false
}
},
emits: ['draw'],
computed: {
sortedPreviewImages () {
return [...this.document.preview_images].sort((a, b) => parseInt(a.filename) - parseInt(b.filename))
}
}
}
</script>
+81
View File
@@ -0,0 +1,81 @@
<template>
<div>
{{ field.type }}
<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 @click="field.options.push('')">
Add option
</button>
</div>
<div>
<div
v-for="(area, index) in areas"
:key="index"
>
{{ area }}
<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: 'FlowField',
props: {
field: {
type: Object,
required: true
}
},
emits: ['set-draw'],
computed: {
areas () {
return this.field.areas || []
}
},
methods: {
removeArea (area) {
this.field.areas.splice(this.field.areas.indexOf(area), 1)
}
}
}
</script>
+68
View File
@@ -0,0 +1,68 @@
<template>
<div class="space-y-2">
<Field
v-for="field in fields"
:key="field.uuid"
class="border"
:field="field"
@set-draw="$emit('set-draw', $event)"
/>
</div>
<button
v-for="item in fieldTypes"
:key="item.type"
class="block w-full"
@click="addField(item.value)"
>
Add {{ item.label }}
</button>
</template>
<script>
import Field from './field'
import { v4 } from 'uuid'
export default {
name: 'FlowFields',
components: {
Field
},
props: {
fields: {
type: Array,
required: true
}
},
emits: ['set-draw'],
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: {
addField (type) {
const field = {
name: type === 'signature' ? 'Signature' : '',
uuid: v4(),
required: true,
type
}
if (['select', 'checkbox', 'radio'].includes(type)) {
field.options = ['']
}
this.fields.push(field)
}
}
}
</script>
+146
View File
@@ -0,0 +1,146 @@
<template>
<div class="relative">
<img
ref="image"
:src="image.url"
:width="width"
:height="height"
loading="lazy"
>
<div
class="top-0 bottom-0 left-0 right-0 absolute"
>
<FieldArea
v-for="(item, i) in areas"
:key="i"
:scale="scale"
: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"
:scale="scale"
:bounds="newArea"
/>
</div>
<div
v-show="isDraw || showMask"
id="mask"
ref="mask"
class="top-0 bottom-0 left-0 right-0 absolute"
@pointerdown="onPointerdown"
@pointermove="onPointermove"
@pointerup="onPointerup"
/>
</div>
</template>
<script>
import FieldArea from './area'
export default {
name: 'FlowPage',
components: {
FieldArea
},
props: {
image: {
type: Object,
required: true
},
areas: {
type: Array,
required: false,
default: () => []
},
isDraw: {
type: Boolean,
required: false,
default: false
},
number: {
type: Number,
required: true
}
},
emits: ['draw'],
data () {
return {
scale: 1,
showMask: false,
newArea: null
}
},
computed: {
width () {
return this.image.metadata.width
},
height () {
return this.image.metadata.height
}
},
mounted () {
this.resizeObserver = new ResizeObserver(this.onResize)
this.resizeObserver.observe(this.$refs.image)
},
beforeUnmount () {
this.resizeObserver.unobserve(this.$refs.image)
},
methods: {
onResize () {
this.scale = this.$refs.image.clientWidth / this.image.metadata.width
},
onPointerdown (e) {
if (this.isDraw) {
this.newArea = {
initialX: e.layerX / this.scale,
initialY: e.layerY / this.scale,
x: e.layerX / this.scale,
y: e.layerY / this.scale,
w: 0,
h: 0
}
}
},
onPointermove (e) {
if (this.newArea) {
const dx = e.layerX / this.scale - this.newArea.initialX
const dy = e.layerY / this.scale - this.newArea.initialY
if (dx > 0) {
this.newArea.x = this.newArea.initialX
} else {
this.newArea.x = e.layerX / this.scale
}
if (dy > 0) {
this.newArea.y = this.newArea.initialY
} else {
this.newArea.y = e.layerY / this.scale
}
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, 50),
h: Math.max(this.newArea.h, 40),
page: this.number
})
}
this.newArea = null
}
}
}
</script>
+59
View File
@@ -0,0 +1,59 @@
<template>
<input
ref="input"
type="file"
multiple
@change="upload"
>
</template>
<script>
import { DirectUpload } from '@rails/activestorage'
export default {
name: 'DocumentsUpload',
props: {
flowId: {
type: [Number, String],
required: true
}
},
emits: ['success'],
methods: {
async upload () {
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/flows/${this.flowId}/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 = ''
})
}
}
}
</script>
+38
View File
@@ -0,0 +1,38 @@
export default class extends HTMLElement {
static observedAttributes = ['class']
connectedCallback () {
this.trigger()
}
attributeChangedCallback (attributeName, oldValue, newValue) {
if (attributeName === 'class' && oldValue !== newValue) {
this.trigger()
}
}
trigger () {
const hasHiddenClass = this.classList.contains('hidden')
const elements = this.querySelectorAll('input, textarea, select')
elements.forEach((element) => {
if (hasHiddenClass) {
element.disabled = true
if (!element.dataset.wasRequired) {
element.dataset.wasRequired = element.required
}
element.required = false
} else {
element.disabled = false
if (element.dataset.wasRequired) {
element.required = element.dataset.wasRequired === 'true'
delete element.dataset.wasRequired
}
}
})
}
}
+76
View File
@@ -0,0 +1,76 @@
import { DirectUpload } from '@rails/activestorage'
import { actionable } from '@github/catalyst/lib/actionable'
import { target, targetable } from '@github/catalyst/lib/targetable'
export default actionable(targetable(class extends HTMLElement {
static [target.static] = [
'loading',
'input'
]
connectedCallback () {
this.addEventListener('drop', this.onDrop)
this.addEventListener('dragover', (e) => e.preventDefault())
}
onDrop (e) {
e.preventDefault()
this.uploadFiles(e.dataTransfer.files)
}
onSelectFiles (e) {
e.preventDefault()
this.uploadFiles(this.input.files).then(() => {
this.input.value = ''
})
}
async uploadFiles (files) {
const blobs = await Promise.all(
Array.from(files).map(async (file) => {
const upload = new DirectUpload(
file,
'/direct_uploads',
this.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)
})
})
)
await Promise.all(
blobs.map((blob) => {
return fetch('/api/attachments', {
method: 'POST',
body: JSON.stringify({
name: 'attachments',
blob_signed_id: blob.signed_id,
submission_slug: this.dataset.submissionSlug
}),
headers: { 'Content-Type': 'application/json' }
}).then(resp => resp.json()).then((data) => {
return data
})
})).then((result) => {
result.forEach((attachment) => {
this.dispatchEvent(new CustomEvent('upload', { detail: attachment }))
})
})
}
}))
+16
View File
@@ -0,0 +1,16 @@
import { actionable } from '@github/catalyst/lib/actionable'
import { targets, targetable } from '@github/catalyst/lib/targetable'
export default actionable(targetable(class extends HTMLElement {
static [targets.static] = [
'items'
]
add (e) {
const elem = document.createElement('input')
elem.value = e.detail.uuid
elem.name = `values[${this.dataset.fieldUuid}][]`
this.prepend(elem)
}
}))
+5
View File
@@ -0,0 +1,5 @@
export default class extends HTMLElement {
setValue (value) {
this.innerHTML = value
}
}
+93
View File
@@ -0,0 +1,93 @@
import { targets, target, targetable } from '@github/catalyst/lib/targetable'
import { actionable } from '@github/catalyst/lib/actionable'
export default actionable(targetable(class extends HTMLElement {
static observedAttributes = ['data-scale']
static [target.static] = [
'form',
'completed',
'submitButton'
]
static [targets.static] = [
'areas',
'fields',
'steps'
]
passValueToArea (e) {
return (this.areas || []).forEach((area) => {
if (area.dataset.fieldUuid === e.target.id) {
area.setValue(e.target.value)
}
})
}
submitSignature () {
this.submitButton.click()
}
setVisibleStep (uuid) {
this.steps.forEach((step) => {
step.classList.toggle('hidden', step.dataset.fieldUuid !== uuid)
})
this.fields.find(f => f.id === uuid).focus()
}
submitForm (e) {
e.preventDefault()
e.submitter.setAttribute('disabled', true)
fetch(this.form.action, {
method: this.form.method,
body: new FormData(this.form)
}).then(response => {
console.log('Form submitted successfully!', response)
this.moveNextStep()
}).catch(error => {
console.error('Error submitting form:', error)
}).finally(() => {
e.submitter.removeAttribute('disabled')
})
}
moveStepBack (e) {
e.preventDefault()
const currentStepIndex = this.steps.findIndex((el) => !el.classList.contains('hidden'))
const previousStep = this.steps[currentStepIndex - 1]
if (previousStep) {
this.setVisibleStep(previousStep.dataset.fieldUuid)
}
}
moveNextStep () {
const currentStepIndex = this.steps.findIndex((el) => !el.classList.contains('hidden'))
const nextStep = this.steps[currentStepIndex + 1]
if (nextStep) {
this.setVisibleStep(nextStep.dataset.fieldUuid)
} else {
this.form.classList.add('hidden')
this.completed.classList.remove('hidden')
}
}
focusField ({ target }) {
this.setVisibleStep(target.dataset.fieldUuid)
}
focusArea ({ target }) {
const area = this.areas.find(a => target.id === a.dataset.fieldUuid)
if (area) {
area.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
}
}))
+48
View File
@@ -0,0 +1,48 @@
import SignaturePad from 'signature_pad'
import { target, targetable } from '@github/catalyst/lib/targetable'
import { actionable } from '@github/catalyst/lib/actionable'
import { DirectUpload } from '@rails/activestorage'
export default actionable(targetable(class extends HTMLElement {
static [target.static] = [
'canvas',
'input'
]
connectedCallback () {
this.pad = new SignaturePad(this.canvas)
}
submit (e) {
e?.preventDefault()
this.canvas.toBlob((blob) => {
const file = new File([blob], 'signature.jpg', { type: 'image/jpg' })
new DirectUpload(
file,
'/direct_uploads'
).create((_error, data) => {
fetch('/api/attachments', {
method: 'POST',
body: JSON.stringify({
submission_slug: this.dataset.submissionSlug,
blob_signed_id: data.signed_id,
name: 'signatures'
}),
headers: { 'Content-Type': 'application/json' }
}).then((resp) => resp.json()).then((attachment) => {
this.input.value = attachment.uuid
this.dispatchEvent(new CustomEvent('upload', { details: attachment }))
})
})
}, 'image/jpeg', 0.95)
}
clear (e) {
e?.preventDefault()
this.pad.clear()
}
}))
+11
View File
@@ -0,0 +1,11 @@
import { actionable } from '@github/catalyst/lib/actionable'
export default actionable(class extends HTMLElement {
trigger (event) {
const elementIds = JSON.parse(this.dataset.elementIds)
elementIds.forEach((elementId) => {
document.getElementById(elementId).classList.toggle('hidden', event.target.value !== elementId)
})
}
})
+37
View File
@@ -0,0 +1,37 @@
import { actionable } from '@github/catalyst/lib/actionable'
export default actionable(class extends HTMLElement {
connectedCallback () {
document.body.classList.add('overflow-hidden')
document.addEventListener('keyup', this.onEscKey)
document.addEventListener('turbo:submit-end', this.onSubmit)
document.addEventListener('turbo:before-cache', this.close)
}
disconnectedCallback () {
document.body.classList.remove('overflow-hidden')
document.removeEventListener('keyup', this.onEscKey)
document.removeEventListener('turbo:submit-end', this.handleSubmit)
document.removeEventListener('turbo:before-cache', this.close)
}
onSubmit = (e) => {
if (e.detail.success) {
this.close()
}
}
onEscKey = (e) => {
if (e.code === 'Escape') {
this.close()
}
}
close = (e) => {
e?.preventDefault()
this.remove()
}
})
+13
View File
@@ -0,0 +1,13 @@
import FlowArea from './elements/flow_area'
import FlowView from './elements/flow_view'
import DisableHidden from './elements/disable_hidden'
import FileDropzone from './elements/file_dropzone'
import SignaturePad from './elements/signature_pad'
import FilesList from './elements/files_list'
window.customElements.define('flow-view', FlowView)
window.customElements.define('flow-area', FlowArea)
window.customElements.define('disable-hidden', DisableHidden)
window.customElements.define('file-dropzone', FileDropzone)
window.customElements.define('signature-pad', SignaturePad)
window.customElements.define('files-list', FilesList)
+32
View File
@@ -0,0 +1,32 @@
@config "../../tailwind.flow.config.js";
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
a[href],
input[type='checkbox'],
input[type='submit'],
input[type='image'],
input[type='radio'],
label[for],
select,
button {
cursor: pointer;
}
button .disabled {
display: none;
}
button[disabled] .disabled {
display: initial;
}
button .enabled {
display: initial;
}
button[disabled] .enabled {
display: none;
}