1
0
Fork 0

print layout renders and remembers changes

This commit is contained in:
Enoch Riese 2022-10-28 15:03:04 -05:00
parent 8dfc54e141
commit 2e2cbf70d2
6 changed files with 445 additions and 402 deletions

View file

@ -1,13 +1,14 @@
import Part from './part' import Part from './part'
import { getProps } from './utils' import { getProps } from './utils'
const Stack = props => { const Stack = (props) => {
const { stack, gist, app, updateGist, unsetGist, showInfo } = props const { stack, gist, updateGist, unsetGist, showInfo } = props
return ( return (
<g {...getProps(stack)}> <g {...getProps(stack)}>
{[...stack.parts].map((part) => ( {[...stack.parts].map((part) => (
<Part {...{ app, gist, updateGist, unsetGist, showInfo }} <Part
{...{ gist, updateGist, unsetGist, showInfo }}
key={part.name} key={part.name}
partName={part.name} partName={part.name}
part={part} part={part}

View file

@ -1,8 +1,9 @@
import { SizeMe } from 'react-sizeme' import { SizeMe } from 'react-sizeme'
import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch" import { TransformWrapper, TransformComponent } from 'react-zoom-pan-pinch'
import Svg from './svg' import Svg from './svg'
import Defs from './defs' import Defs from './defs'
import Stack from './stack' import Stack from './stack'
import { forwardRef } from 'react'
/* What's with all the wrapping? /* What's with all the wrapping?
* *
@ -25,37 +26,45 @@ import Stack from './stack'
* Also still to see how this will work with SSR * Also still to see how this will work with SSR
*/ */
const SvgWrapper = props => { const SvgWrapper = forwardRef((props, ref) => {
const { patternProps=false, gist, app, updateGist, unsetGist, showInfo } = props const { patternProps = false, gist, updateGist, unsetGist, showInfo, viewBox } = props
if (!patternProps) return null if (!patternProps) return null
console.log(props.children)
return <SizeMe>{({ size }) => ( return (
<TransformWrapper <SizeMe>
minScale={0.1} {({ size }) => (
centerZoomedOut={true} <TransformWrapper
wheel={{ activationKeys: ['Control'] }} minScale={0.1}
> centerZoomedOut={true}
<TransformComponent> wheel={{ activationKeys: ['Control'] }}
<div style={{ width: size.width+'px', }}> >
<Svg {...patternProps} embed={gist.embed}> <TransformComponent>
<Defs {...patternProps} /> <div style={{ width: size.width + 'px' }}>
<style>{`:root { --pattern-scale: ${gist.scale || 1}} ${patternProps.svg.style}`}</style> <Svg {...patternProps} viewBox={viewBox} embed={gist.embed} ref={ref}>
<g> <Defs {...patternProps} />
{Object.keys(patternProps.stacks).map((stackName) => ( <style>{`:root { --pattern-scale: ${gist.scale || 1}} ${
<Stack {...{ app, gist, updateGist, unsetGist, showInfo, patternProps }} patternProps.svg.style
key={stackName} }`}</style>
stackName={stackName} <g>
stack={patternProps.stacks[stackName]} {props.children ||
/> Object.keys(patternProps.stacks).map((stackName) => (
))} <Stack
</g> {...{ gist, updateGist, unsetGist, showInfo, patternProps }}
</Svg> key={stackName}
</div> stackName={stackName}
</TransformComponent> stack={patternProps.stacks[stackName]}
</TransformWrapper> />
)}</SizeMe> ))}
} </g>
</Svg>
</div>
</TransformComponent>
</TransformWrapper>
)}
</SizeMe>
)
})
export default SvgWrapper export default SvgWrapper

View file

@ -1,35 +1,43 @@
import { useRef} from 'react' import { useRef } from 'react'
import Svg from '../../draft/svg' import Svg from '../../draft/svg'
import Defs from '../../draft/defs' import Defs from '../../draft/defs'
import Part from './part' import Stack from './part'
import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch" import SvgWrapper from '../../draft/svg-wrapper'
import { getProps } from '../../draft/utils'
const Draft = props => { const Draft = (props) => {
const { draft, patternProps, gist, updateGist, app, bgProps={}, fitLayoutPart = false, layoutType="printingLayout"} = props const {
draft,
patternProps,
gist,
updateGist,
app,
bgProps = {},
fitLayoutPart = false,
layoutType = 'printingLayout',
} = props
const svgRef = useRef(null); const svgRef = useRef(null)
if (!patternProps) return null if (!patternProps) return null
// keep a fresh copy of the layout because we might manipulate it without saving to the gist // keep a fresh copy of the layout because we might manipulate it without saving to the gist
let layout = draft.settings.layout === true ? { let layout = draft.settings[0].layouts?.printingLayout || {
...patternProps.autoLayout, ...patternProps.autoLayout,
width: patternProps.width, width: patternProps.width,
height: patternProps.height height: patternProps.height,
} : {...draft.settings.layout} }
// Helper method to update part layout and re-calculate width * height // Helper method to update part layout and re-calculate width * height
const updateLayout = (name, config, history=true) => { const updateLayout = (name, config, history = true) => {
// Start creating new layout // Start creating new layout
const newLayout = {...layout} const newLayout = { ...layout }
newLayout.parts[name] = config newLayout.stacks[name] = config
// Pattern topLeft and bottomRight // Pattern topLeft and bottomRight
let topLeft = {x: 0, y: 0} let topLeft = { x: 0, y: 0 }
let bottomRight = {x: 0, y: 0} let bottomRight = { x: 0, y: 0 }
for (const [pname, part] of Object.entries(patternProps.parts)) { for (const [pname, part] of Object.entries(patternProps.stacks)) {
if (pname == props.layoutPart && !fitLayoutPart) continue if (pname == props.layoutPart && !fitLayoutPart) continue
let partLayout = newLayout.parts[pname]; let partLayout = newLayout.stacks[pname]
// Pages part does not have its topLeft and bottomRight set by core since it's added post-draft // Pages part does not have its topLeft and bottomRight set by core since it's added post-draft
if (partLayout?.tl) { if (partLayout?.tl) {
@ -37,7 +45,7 @@ const Draft = props => {
topLeft.x = Math.min(topLeft.x, partLayout.tl.x) topLeft.x = Math.min(topLeft.x, partLayout.tl.x)
topLeft.y = Math.min(topLeft.y, partLayout.tl.y) topLeft.y = Math.min(topLeft.y, partLayout.tl.y)
bottomRight.x = Math.max(bottomRight.x, partLayout.br.x) bottomRight.x = Math.max(bottomRight.x, partLayout.br.x)
bottomRight.y = Math.max(bottomRight.y, partLayout.br.y); bottomRight.y = Math.max(bottomRight.y, partLayout.br.y)
} }
} }
@ -54,52 +62,41 @@ const Draft = props => {
} }
} }
// We need to make sure the `pages` part is at the bottom of the pile // We need to make sure the `pages` part is at the bottom of the pile
// so we can drag-drop all parts on top of it. // so we can drag-drop all parts on top of it.
// Bottom in SVG means we need to draw it first // Bottom in SVG means we need to draw it first
const partList = Object.keys(patternProps.parts) const viewBox = layout.topLeft
? `${layout.topLeft.x} ${layout.topLeft.y} ${layout.width} ${layout.height}`
: false
const stacks = []
for (var stackName in patternProps.stacks) {
let stack = patternProps.stacks[stackName]
const stackPart = (
<Stack
{...{
key: stackName,
stackName,
stack,
layout,
app,
gist,
updateLayout,
isLayoutPart: stackName === props.layoutPart,
}}
/>
)
stacks[stack === props.layoutPart ? 'unshift' : 'push'](stackPart)
}
return ( return (
<div className="my-8 w-11/12 m-auto border-2 border-dotted border-base-content shadow"> <SvgWrapper {...{ patternProps, gist, viewBox }} ref={svgRef}>
<TransformWrapper <rect x="0" y="0" width={layout.width} height={layout.height} {...bgProps} />
minScale={0.1} {stacks}
centerZoomedOut={true} </SvgWrapper>
wheel={{ activationKeys: ['Control'] }}
>
<TransformComponent>
<Svg {...patternProps}
embed={gist.embed}
ref={svgRef}
viewBox={layout.topLeft ? `${layout.topLeft.x} ${layout.topLeft.y} ${layout.width} ${layout.height}` : false}
style={{height: '90vh'}}
>
<Defs {...patternProps} />
<style>{`:root { --pattern-scale: ${gist.scale || 1}}`}</style>
<g>
<rect x="0" y="0" width={layout.width} height={layout.height} {...bgProps} />
{[
partList.filter(name => name === props.layoutPart),
partList.filter(name => name !== props.layoutPart),
].map(list => list.map(name => (
<Part {...{
key:name,
partName: name,
part: patternProps.parts[name],
layout,
app,
gist,
updateLayout,
isLayoutPart: name === props.layoutPart
}}/>
)))}
</g>
</Svg>
</TransformComponent>
</TransformWrapper>
</div>
) )
} }
export default Draft export default Draft

View file

@ -43,25 +43,24 @@
* I've sort of left it at this because I'm starting to wonder if we should perhaps re-think * I've sort of left it at this because I'm starting to wonder if we should perhaps re-think
* how custom layouts are supported in the core. And I would like to discuss this with the core team. * how custom layouts are supported in the core. And I would like to discuss this with the core team.
*/ */
import {PartInner} from '../../draft/part' import Part from '../../draft/part'
import { generatePartTransform } from '@freesewing/core' import { generateStackTransform } from '@freesewing/core'
import { getProps, angle } from '../../draft/utils' import { getProps, angle } from '../../draft/utils'
import { drag } from 'd3-drag' import { drag } from 'd3-drag'
import { select } from 'd3-selection' import { select } from 'd3-selection'
import { useRef, useState, useEffect} from 'react' import { useRef, useState, useEffect } from 'react'
import Buttons from './buttons' import Buttons from './buttons'
const Stack = (props) => {
const { layout, stack, stackName, gist } = props
const Part = props => { const stackLayout = layout.stacks?.[stackName]
const { layout, part, partName} = props
const partLayout = layout.parts?.[partName] // // Don't just assume this makes sense
if (typeof stackLayout?.move?.x === 'undefined') return null
// Don't just assume this makes sense
if (typeof partLayout?.move?.x === 'undefined') return null
// Use a ref for direct DOM manipulation // Use a ref for direct DOM manipulation
const partRef = useRef(null) const stackRef = useRef(null)
const centerRef = useRef(null) const centerRef = useRef(null)
const innerRef = useRef(null) const innerRef = useRef(null)
@ -71,81 +70,81 @@ const Part = props => {
// update the layout on mount // update the layout on mount
useEffect(() => { useEffect(() => {
// only update if there's a rendered part and it's not the pages or fabric part // only update if there's a rendered part and it's not the pages or fabric part
if (partRef.current && !props.isLayoutPart) { if (stackRef.current && !props.isLayoutPart) {
updateLayout(false) updateLayout(false)
} }
}, [partRef, partLayout]) }, [stackRef, stackLayout])
// Initialize drag handler // Initialize drag handler
useEffect(() => { useEffect(() => {
// don't drag the pages // don't drag the pages
if (props.isLayoutPart) return if (props.isLayoutPart) return
handleDrag(select(partRef.current)) handleDrag(select(stackRef.current))
}, [rotate, partRef, partLayout]) }, [rotate, stackRef, stackLayout])
// These are kept as vars because re-rendering on drag would kill performance // These are kept as vars because re-rendering on drag would kill performance
// Managing the difference between re-render and direct DOM updates makes this // Managing the difference between re-render and direct DOM updates makes this
// whole thing a bit tricky to wrap your head around // whole thing a bit tricky to wrap your head around
let translateX = partLayout.move.x let translateX = stackLayout.move.x
let translateY = partLayout.move.y let translateY = stackLayout.move.y
let partRotation = partLayout.rotate || 0; let stackRotation = stackLayout.rotate || 0
let rotation = partRotation; let rotation = stackRotation
let flipX = !!partLayout.flipX let flipX = !!stackLayout.flipX
let flipY = !!partLayout.flipY let flipY = !!stackLayout.flipY
const center = { const center = {
x: part.topLeft.x + (part.bottomRight.x - part.topLeft.x)/2, x: stack.topLeft.x + (stack.bottomRight.x - stack.topLeft.x) / 2,
y: part.topLeft.y + (part.bottomRight.y - part.topLeft.y)/2, y: stack.topLeft.y + (stack.bottomRight.y - stack.topLeft.y) / 2,
} }
/** get the delta rotation from the start of the drag event to now */ /** get the delta rotation from the start of the drag event to now */
const getRotation = (event) => angle(center, event.subject) - angle(center, { x:event.x, y: event.y }); const getRotation = (event) =>
angle(center, event.subject) - angle(center, { x: event.x, y: event.y })
const setTransforms = () => { const setTransforms = () => {
// get the transform attributes // get the transform attributes
const transforms = generatePartTransform(translateX, translateY, rotation, flipX, flipY, part); const transforms = generateStackTransform(translateX, translateY, rotation, flipX, flipY, stack)
const me = select(partRef.current); const me = select(stackRef.current)
for (var t in transforms) { for (var t in transforms) {
me.attr(t, transforms[t]) me.attr(t, transforms[t])
} }
} }
let didDrag = false; let didDrag = false
const handleDrag = drag() const handleDrag = drag()
// subject allows us to save data from the start of the event to use throughout event handing // subject allows us to save data from the start of the event to use throughout event handing
.subject(function(event) { .subject(function (event) {
return rotate ? return rotate
// if we're rotating, the subject is the mouse position ? // if we're rotating, the subject is the mouse position
{ x: event.x, y: event.y } : { x: event.x, y: event.y }
// if we're moving, the subject is the part's x,y coordinates : // if we're moving, the subject is the part's x,y coordinates
{x: translateX, y: translateY} { x: translateX, y: translateY }
}) })
.on('drag', function(event) { .on('drag', function (event) {
if (!event.dx && !event.dy) return if (!event.dx && !event.dy) return
if (rotate) { if (rotate) {
let newRotation = getRotation(event); let newRotation = getRotation(event)
// shift key to snap the rotation // shift key to snap the rotation
if (event.sourceEvent.shiftKey) { if (event.sourceEvent.shiftKey) {
newRotation = Math.ceil(newRotation/15) * 15 newRotation = Math.ceil(newRotation / 15) * 15
} }
// reverse the rotation direction one time per flip. if we're flipped both directions, rotation will be positive again // reverse the rotation direction one time per flip. if we're flipped both directions, rotation will be positive again
if (flipX) newRotation *= -1 if (flipX) newRotation *= -1
if (flipY) newRotation *= -1 if (flipY) newRotation *= -1
rotation = partRotation + newRotation rotation = stackRotation + newRotation
} } else {
else {
translateX = event.x translateX = event.x
translateY = event.y translateY = event.y
} }
// a drag happened, so we should update the layout when we're done // a drag happened, so we should update the layout when we're done
didDrag = true; didDrag = true
setTransforms() setTransforms()
}) })
.on('end', function(event) { .on('end', function (event) {
// save to gist if anything actually changed // save to gist if anything actually changed
if (didDrag) updateLayout() if (didDrag) updateLayout()
@ -163,49 +162,55 @@ const Part = props => {
/** toggle between dragging and rotating */ /** toggle between dragging and rotating */
const toggleDragRotate = () => { const toggleDragRotate = () => {
// only respond if the part should be able to drag/rotate // only respond if the part should be able to drag/rotate
if (!partRef.current || props.isLayoutPart) {return} if (!stackRef.current || props.isLayoutPart) {
return
}
setRotate(!rotate) setRotate(!rotate)
} }
/** update the layout either locally or in the gist */ /** update the layout either locally or in the gist */
const updateLayout = (history=true) => { const updateLayout = (history = true) => {
/** don't mess with what we don't lay out */ /** don't mess with what we don't lay out */
if (!partRef.current || props.isLayoutPart) return if (!stackRef.current || props.isLayoutPart) return
// set the transforms on the part in order to calculate from the latest position // set the transforms on the part in order to calculate from the latest position
setTransforms() setTransforms()
// get the bounding box and the svg's current transform matrix // get the bounding box and the svg's current transform matrix
const partRect = innerRef.current.getBoundingClientRect(); const stackRect = innerRef.current.getBoundingClientRect()
const matrix = innerRef.current.ownerSVGElement.getScreenCTM().inverse(); const matrix = innerRef.current.ownerSVGElement.getScreenCTM().inverse()
// a function to convert dom space to svg space // a function to convert dom space to svg space
const domToSvg = (point) => { const domToSvg = (point) => {
const {x, y} = DOMPointReadOnly.fromPoint(point).matrixTransform(matrix) const { x, y } = DOMPointReadOnly.fromPoint(point).matrixTransform(matrix)
return {x, y} return { x, y }
} }
// include the new top left and bottom right to ease calculating the pattern width and height // include the new top left and bottom right to ease calculating the pattern width and height
const tl = domToSvg({x: partRect.left, y: partRect.top}); const tl = domToSvg({ x: stackRect.left, y: stackRect.top })
const br = domToSvg({x: partRect.right, y: props.isLayoutPart ? 0 : partRect.bottom}); const br = domToSvg({ x: stackRect.right, y: props.isLayoutPart ? 0 : stackRect.bottom })
// update it on the draft component // update it on the draft component
props.updateLayout(partName, { props.updateLayout(
move: { stackName,
x: translateX, {
y: translateY, move: {
x: translateX,
y: translateY,
},
rotate: rotation % 360,
flipX,
flipY,
tl,
br,
}, },
rotate: rotation % 360, history
flipX, )
flipY,
tl,
br
}, history)
} }
/** Method to flip (mirror) the part along the X or Y axis */ /** Method to flip (mirror) the part along the X or Y axis */
const flip = axis => { const flip = (axis) => {
if (axis === 'x') flipX = !flipX if (axis === 'x') flipX = !flipX
else flipY = !flipY else flipY = !flipY
updateLayout() updateLayout()
@ -222,39 +227,42 @@ const Part = props => {
} }
// don't render if the part is empty // don't render if the part is empty
if (Object.keys(part.snippets).length === 0 && Object.keys(part.paths).length === 0) return null; // if (Object.keys(part.snippets).length === 0 && Object.keys(part.paths).length === 0) return null;
return ( return (
<g <g id={`stack-${stackName}`} {...getProps(stack)} ref={stackRef}>
id={`part-${partName}`} <g id={`stack-inner-${stackName}`} ref={innerRef}>
ref={partRef} {stack.parts.map((part) => (
{...getProps(part)} <Part {...{ part, partName: part.name, gist }} key={part.name}></Part>
> ))}
<PartInner {...props} ref={innerRef}/> </g>
{!props.isLayoutPart && <> {!props.isLayoutPart && (
<text x={center.x} y={center.y} ref={centerRef} /> <>
<rect <text x={center.x} y={center.y} ref={centerRef} />
ref={partRef} <rect
x={part.topLeft.x} x={stack.topLeft.x}
y={part.topLeft.y} y={stack.topLeft.y}
width={part.width} width={stack.width}
height={part.height} height={stack.height}
className={`layout-rect ${rotate ? 'rotate' : 'move'}`} className={`layout-rect ${rotate ? 'rotate' : 'move'}`}
id={`${partName}-layout-rect`} id={`${stackName}-layout-rect`}
onClick={toggleDragRotate} onClick={toggleDragRotate}
/> />
<Buttons <Buttons
transform={`translate(${center.x}, ${center.y}) rotate(${-rotation}) scale(${flipX ? -1 : 1},${flipY ? -1 : 1})`} transform={`translate(${center.x}, ${center.y}) rotate(${-rotation}) scale(${
flip={flip} flipX ? -1 : 1
rotate={rotate} },${flipY ? -1 : 1})`}
setRotate={setRotate} flip={flip}
resetPart={resetPart} rotate={rotate}
rotate90={rotate90} setRotate={setRotate}
partName={partName} resetPart={resetPart}
/> rotate90={rotate90}
</>} partName={stackName}
/>
</>
)}
</g> </g>
) )
} }
export default Part export default Stack

View file

@ -2,17 +2,17 @@ import { useEffect, useState } from 'react'
import { useTranslation } from 'next-i18next' import { useTranslation } from 'next-i18next'
import Settings from './settings' import Settings from './settings'
import Draft from '../draft/index' import Draft from '../draft/index'
import {pagesPlugin} from './plugin' import { pagesPlugin } from './plugin'
import {handleExport, defaultPdfSettings} from 'shared/components/workbench/exporting/export-handler' import {
handleExport,
defaultPdfSettings,
} from 'shared/components/workbench/exporting/export-handler'
import Popout from 'shared/components/popout' import Popout from 'shared/components/popout'
const PrintLayout = props => { const PrintLayout = (props) => {
// disable xray // disable xray
useEffect(() => { useEffect(() => {
if (props.gist?._state?.xray?.enabled) props.updateGist( if (props.gist?._state?.xray?.enabled) props.updateGist(['_state', 'xray', 'enabled'], false)
['_state', 'xray', 'enabled'],
false
)
}, []) }, [])
const { t } = useTranslation(['workbench']) const { t } = useTranslation(['workbench'])
@ -23,45 +23,44 @@ const PrintLayout = props => {
// add the pages plugin to the draft // add the pages plugin to the draft
const layoutSettings = { const layoutSettings = {
...defaultPdfSettings, ...defaultPdfSettings,
...props.gist?._state?.layout?.forPrinting?.page ...props.gist?._state?.layout?.forPrinting?.page,
} }
draft.use(pagesPlugin( draft.use(pagesPlugin(layoutSettings))
layoutSettings
))
let patternProps let patternProps
try { try {
// draft the pattern // draft the pattern
draft.draft() draft.draft()
patternProps = draft.getRenderProps() patternProps = draft.getRenderProps()
} catch(err) { console.log(patternProps)
} catch (err) {
console.log(err, props.gist) console.log(err, props.gist)
} }
const bgProps = { fill: "url(#page)" } const bgProps = { fill: 'url(#page)' }
const exportIt = () => { const exportIt = () => {
setError(false) setError(false)
handleExport('pdf', props.gist, props.design, t, props.app, (e) => setError(false), (e) => setError(true)) handleExport(
'pdf',
props.gist,
props.design,
t,
props.app,
(e) => setError(false),
(e) => setError(true)
)
} }
let name = props.design.designConfig.data.name let name = props.design.designConfig.data.name
name = name.replace('@freesewing/', '') name = name.replace('@freesewing/', '')
return ( return (
<div> <div>
<h2 className="capitalize"> <h2 className="capitalize">{t('layoutThing', { thing: name }) + ': ' + t('forPrinting')}</h2>
{
t('layoutThing', { thing: name })
+ ': '
+ t('forPrinting')
}
</h2>
<div className="m-4"> <div className="m-4">
<Settings {...{...props, exportIt, layoutSettings}} draft={draft}/> <Settings {...{ ...props, exportIt, layoutSettings }} draft={draft} />
{error && ( {error && (
<Popout warning compact> <Popout warning compact>
<span className="font-bold mr-4 uppercase text-sm"> <span className="font-bold mr-4 uppercase text-sm">{t('error')}:</span>
{t('error')}:
</span>
{t('somethingWentWrong')} {t('somethingWentWrong')}
</Popout> </Popout>
)} )}

View file

@ -1,13 +1,13 @@
const name = 'Pages Plugin' const name = 'Pages Plugin'
const version = '1.0.0' const version = '1.0.0'
export const sizes = { export const sizes = {
a4: [ 210, 297 ], a4: [210, 297],
a3: [ 297, 420 ], a3: [297, 420],
a2: [ 420, 594 ], a2: [420, 594],
a1: [ 594, 841 ], a1: [594, 841],
a0: [ 841, 1188 ], a0: [841, 1188],
letter: [ 215.9, 279.4 ], letter: [215.9, 279.4],
tabloid: [ 279.4, 431.8 ], tabloid: [279.4, 431.8],
} }
/** get a letter to represent an index less than 26*/ /** get a letter to represent an index less than 26*/
@ -19,32 +19,35 @@ const indexStr = (i) => {
let quotient = i / 26 let quotient = i / 26
let result let result
if (i <= 26) {return indexLetter(i)} //Number is within single digit bounds of our encoding letter alphabet if (i <= 26) {
return indexLetter(i)
} //Number is within single digit bounds of our encoding letter alphabet
if (quotient >= 1) { if (quotient >= 1) {
//This number was bigger than the alphabet, recursively perform this function until we're done //This number was bigger than the alphabet, recursively perform this function until we're done
if (index === 0) {quotient--} //Accounts for the edge case of the last letter in the dictionary string if (index === 0) {
result = indexStr(quotient) quotient--
} //Accounts for the edge case of the last letter in the dictionary string
result = indexStr(quotient)
} }
if (index === 0) {index = 26} //Accounts for the edge case of the final letter; avoids getting an empty string if (index === 0) {
index = 26
} //Accounts for the edge case of the final letter; avoids getting an empty string
return result + indexLetter(index) return result + indexLetter(index)
} }
/** /**
* A plugin to add printer pages * A plugin to add printer pages
* */ * */
export const pagesPlugin = ({ export const pagesPlugin = ({ size = 'a4', ...settings }) => {
size='a4',
...settings
}) => {
const ls = settings.orientation === 'landscape' const ls = settings.orientation === 'landscape'
let sheetHeight = sizes[size][ls ? 0 : 1] let sheetHeight = sizes[size][ls ? 0 : 1]
let sheetWidth = sizes[size][ls ? 1 : 0] let sheetWidth = sizes[size][ls ? 1 : 0]
sheetWidth -= settings.margin * 2 sheetWidth -= settings.margin * 2
sheetHeight -= settings.margin * 2 sheetHeight -= settings.margin * 2
return basePlugin({...settings, sheetWidth, sheetHeight}) return basePlugin({ ...settings, sheetWidth, sheetHeight })
} }
const doScanForBlanks = (parts, layout, x, y, w, h) => { const doScanForBlanks = (parts, layout, x, y, w, h) => {
@ -56,10 +59,10 @@ const doScanForBlanks = (parts, layout, x, y, w, h) => {
// get the position of the part // get the position of the part
let partLayout = layout.parts[p] let partLayout = layout.parts[p]
let partMinX = (partLayout.tl?.x || (partLayout.move.x + part.topLeft.x)) let partMinX = partLayout.tl?.x || partLayout.move.x + part.topLeft.x
let partMinY = (partLayout.tl?.y || (partLayout.move.y + part.topLeft.y)) let partMinY = partLayout.tl?.y || partLayout.move.y + part.topLeft.y
let partMaxX = (partLayout.br?.x || (partMinX + part.width)) let partMaxX = partLayout.br?.x || partMinX + part.width
let partMaxY = (partLayout.br?.y || (partMinY + part.height)) let partMaxY = partLayout.br?.y || partMinY + part.height
// check if the part overlaps the page extents // check if the part overlaps the page extents
if ( if (
@ -71,16 +74,17 @@ const doScanForBlanks = (parts, layout, x, y, w, h) => {
partMaxX > x && partMaxX > x &&
// and the bottom of the part is below the top to the page // and the bottom of the part is below the top to the page
partMaxY > y partMaxY > y
) { ) {
// the part has content inside the page // the part has content inside the page
hasContent = true; hasContent = true
// so we stop looking // so we stop looking
break; break
} }
} }
return hasContent return hasContent
} }
/** /**
* The base plugin for adding a layout helper part like pages or fabric * The base plugin for adding a layout helper part like pages or fabric
* sheetWidth: the width of the helper part * sheetWidth: the width of the helper part
@ -92,217 +96,242 @@ const doScanForBlanks = (parts, layout, x, y, w, h) => {
const basePlugin = ({ const basePlugin = ({
sheetWidth, sheetWidth,
sheetHeight, sheetHeight,
boundary=false, boundary = false,
partName="pages", partName = 'pages',
responsiveColumns=true, responsiveColumns = true,
printStyle=false, printStyle = false,
scanForBlanks=true, scanForBlanks = true,
renderBlanks=true, renderBlanks = true,
setPatternSize=false setPatternSize = false,
}) => ({ }) => ({
name, name,
version, version,
hooks: { hooks: {
postLayout: function(pattern) { preDraft: function (pattern) {
// Add part
pattern.parts[partName] = pattern.Part(partName)
// Keep part out of layout
pattern.parts[partName].layout = false
// But add the part to the autoLayout property // But add the part to the autoLayout property
pattern.autoLayout.parts[partName] = { // pattern.autoLayout.parts[partName] = {
move: { x: 0, y: 0 } // move: { x: 0, y: 0 }
} // }
// TODO migrate this to v3 parts adding // TODO migrate this to v3 parts adding
// Add pages // Add pages
const { macro } = pattern.parts[partName].shorthand() // const { macro } = pattern.config.parts[partName].shorthand()
let { height, width } = pattern let { height, width } = pattern
if (!responsiveColumns) width = sheetWidth; if (!responsiveColumns) width = sheetWidth
if (pattern.settings.layout?.topLeft) { if (pattern.settings.layout?.topLeft) {
height += pattern.settings.layout.topLeft.y height += pattern.settings.layout.topLeft.y
responsiveColumns && (width += pattern.settings.layout.topLeft.x) responsiveColumns && (width += pattern.settings.layout.topLeft.x)
} }
const layout = typeof pattern.settings.layout === 'object' ? pattern.settings.layout : pattern.autoLayout // Add part
pattern.addPart({
name: partName,
layout: false,
draft: (shorthand) => {
pluginMacros.addPages(
{ size: [sheetHeight, sheetWidth], height, width, layout },
shorthand
)
return shorthand.part
},
})
pattern.getConfig()
console.log(pattern.config, pattern.designConfig)
macro('addPages', { size: [sheetHeight,sheetWidth, ], height, width, layout }) const layout =
typeof pattern.settings.layout === 'object' ? pattern.settings.layout : pattern.autoLayout
if (boundary) pattern.parts[partName].boundary(); // macro('addPages', { size: [sheetHeight,sheetWidth, ], height, width, layout })
if (boundary) pattern.parts[partName].boundary()
if (setPatternSize) { if (setPatternSize) {
pattern.width = sheetWidth * pattern.parts[partName].pages.cols pattern.width = sheetWidth * pattern.parts[partName].pages.cols
pattern.height = sheetHeight * pattern.parts[partName].pages.rows pattern.height = sheetHeight * pattern.parts[partName].pages.rows
} }
} },
}, },
macros: { })
/** draft the pages */
addPages: function(so) {
const [h,w] = so.size
const cols = Math.ceil(so.width / w)
const rows = Math.ceil(so.height / h)
const { points, Point, paths, Path, macro } = this.shorthand()
let count = 0
let withContent = {}
// get the layout from the pattern
const {layout} = so;
for (let row=0;row<rows;row++) {
let y = row * h
withContent[row] = {}
for (let col=0;col<cols;col++) {
let x = col * w
let hasContent = true
if (scanForBlanks && layout) {
hasContent = doScanForBlanks(this.context.parts, layout, x, y, w, h)
}
withContent[row][col] = hasContent
if (!renderBlanks && !hasContent) continue
if (hasContent) count++
const pageName = `_pages__row${row}-col${col}`
points[`${pageName}-tl`] = new Point(x,y)
points[`${pageName}-tr`] = new Point(x+w,y)
points[`${pageName}-br`] = new Point(x+w,y+h)
points[`${pageName}-bl`] = new Point(x,y+h)
points[`${pageName}-circle`] = new Point(x+w/2,y+h/2)
.attr('data-circle', 56)
.attr('data-circle-class', 'stroke-4xl muted fabric')
.attr('data-circle-id', `${pageName}-circle`)
points[`${pageName}-text`] = new Point(x+w/2,y+h/2)
.attr('data-text', `${indexStr(col + 1)}${row + 1}`)
.attr('data-text-class', 'text-4xl center baseline-center bold muted fill-fabric')
.attr('data-text-id', `${pageName}-text`)
paths[pageName] = new Path() const pluginMacros = {
.attr('id', pageName) /** draft the pages */
.move(points[`${pageName}-tl`]) addPages: function (so, shorthand) {
.line(points[`${pageName}-bl`]) const [h, w] = so.size
.line(points[`${pageName}-br`]) const cols = Math.ceil(so.width / w)
.line(points[`${pageName}-tr`]) const rows = Math.ceil(so.height / h)
.close() const { points, Point, paths, Path, macro } = shorthand
let count = 0
let withContent = {}
// get the layout from the pattern
const { layout } = so
for (let row = 0; row < rows; row++) {
let y = row * h
withContent[row] = {}
for (let col = 0; col < cols; col++) {
let x = col * w
let hasContent = true
if (scanForBlanks && layout) {
hasContent = doScanForBlanks(this.context.parts, layout, x, y, w, h)
}
withContent[row][col] = hasContent
if (!renderBlanks && !hasContent) continue
if (hasContent) count++
const pageName = `_pages__row${row}-col${col}`
points[`${pageName}-tl`] = new Point(x, y)
points[`${pageName}-tr`] = new Point(x + w, y)
points[`${pageName}-br`] = new Point(x + w, y + h)
points[`${pageName}-bl`] = new Point(x, y + h)
points[`${pageName}-circle`] = new Point(x + w / 2, y + h / 2)
.attr('data-circle', 56)
.attr('data-circle-class', 'stroke-4xl muted fabric')
.attr('data-circle-id', `${pageName}-circle`)
points[`${pageName}-text`] = new Point(x + w / 2, y + h / 2)
.attr('data-text', `${indexStr(col + 1)}${row + 1}`)
.attr('data-text-class', 'text-4xl center baseline-center bold muted fill-fabric')
.attr('data-text-id', `${pageName}-text`)
if (!printStyle) { paths[pageName] = new Path()
paths[pageName].attr('class', 'fill-fabric') .attr('id', pageName)
.attr('style', `stroke-opacity: 0; fill-opacity: ${(col+row)%2===0 ? 0.03 : 0.09};`) .move(points[`${pageName}-tl`])
} .line(points[`${pageName}-bl`])
else { .line(points[`${pageName}-br`])
paths[pageName].attr('class', 'interfacing stroke-xs') .line(points[`${pageName}-tr`])
// add markers and rulers .close()
macro('addPageMarkers', {row, col, pageName, withContent})
macro('addRuler', {xAxis: true, pageName}) if (!printStyle) {
macro('addRuler', {xAxis: false, pageName}) paths[pageName]
} .attr('class', 'fill-fabric')
.attr(
'style',
`stroke-opacity: 0; fill-opacity: ${(col + row) % 2 === 0 ? 0.03 : 0.09};`
)
} else {
paths[pageName].attr('class', 'interfacing stroke-xs')
// add markers and rulers
pluginMacros.addPageMarkers({ row, col, pageName, withContent }, shorthand)
pluginMacros.addRuler({ xAxis: true, pageName }, shorthand)
pluginMacros.addRuler({ xAxis: false, pageName }, shorthand)
} }
} }
// Store page count in part }
this.pages = { cols, rows, count, withContent, width: w, height: h} // Store page count in part
shorthand.part.pages = { cols, rows, count, withContent, width: w, height: h }
},
/** add a ruler to the top left corner of the page */
addRuler({ xAxis, pageName }, shorthand) {
const { points, paths, Path } = shorthand
// arbitrary number of units for the ruler
const rulerLength = 2
const isMetric = this.context.settings.units === 'metric'
// distance to the end of the ruler
const endPointDist = [(isMetric ? 10 : 25.4) * rulerLength, 0]
}, const axisName = xAxis ? 'x' : 'y'
/** add a ruler to the top left corner of the page */ const rulerName = `${pageName}-${axisName}`
addRuler({xAxis, pageName}) { // start by making an endpoint for the ruler based on the axis
const { points, paths, Path } = this.shorthand() const endPoint = [endPointDist[xAxis ? 0 : 1], endPointDist[xAxis ? 1 : 0]]
// arbitrary number of units for the ruler points[`${rulerName}-ruler-end`] = points[`${pageName}-tl`].translate(endPoint[0], endPoint[1])
const rulerLength = 2 // also make a tick for the end of the ruler
const isMetric = this.context.settings.units === 'metric' points[`${rulerName}-ruler-tick`] = points[`${rulerName}-ruler-end`]
// distance to the end of the ruler .translate(xAxis ? 0 : 3, xAxis ? 3 : 0)
const endPointDist = [(isMetric ? 10 : 25.4) * rulerLength, 0] // add a label to it
.attr('data-text', rulerLength + (isMetric ? 'cm' : '"'))
// space the text properly from the end of the line
.attr('data-text-class', 'fill-interfacing baseline-center' + (xAxis ? ' center' : ''))
.attr(`data-text-d${xAxis ? 'y' : 'x'}`, xAxis ? 5 : 3)
// give the text an explicit id in case we need to hide it later
.attr('data-text-id', `${rulerName}-ruler-text`)
const axisName = xAxis ? 'x' : 'y' // start the path
const rulerName = `${pageName}-${axisName}` paths[`${rulerName}-ruler`] = new Path()
// start by making an endpoint for the ruler based on the axis .move(points[`${pageName}-tl`])
const endPoint = [endPointDist[xAxis ? 0 : 1], endPointDist[xAxis ? 1 : 0]] // give it an explicit id in case we need to hide it later
points[`${rulerName}-ruler-end`] = points[`${pageName}-tl`].translate(endPoint[0], endPoint[1]) .attr('id', `${rulerName}-ruler`)
// also make a tick for the end of the ruler .attr('class', 'interfacing stroke-xs')
points[`${rulerName}-ruler-tick`] = points[`${rulerName}-ruler-end`].translate(xAxis ? 0 : 3, xAxis ? 3 : 0)
// add a label to it
.attr('data-text', rulerLength + (isMetric ? 'cm' : '"'))
// space the text properly from the end of the line
.attr('data-text-class', 'fill-interfacing baseline-center' + (xAxis ? ' center' : ''))
.attr(`data-text-d${xAxis ? 'y' : 'x'}`, xAxis ? 5 : 3)
// give the text an explicit id in case we need to hide it later
.attr('data-text-id', `${rulerName}-ruler-text`)
// start the path // get the distance between the smaller ticks on the rule
paths[`${rulerName}-ruler`] = new Path() const division = (isMetric ? 0.1 : 0.125) / rulerLength
.move(points[`${pageName}-tl`]) // we're going to go by fraction, so we want to do this up to 1
// give it an explicit id in case we need to hide it later for (var d = division; d < 1; d += division) {
.attr('id', `${rulerName}-ruler`) // make a start point
.attr('class', 'interfacing stroke-xs') points[`${rulerName}-ruler-${d}-end`] = points[`${pageName}-tl`].shiftFractionTowards(
points[`${rulerName}-ruler-end`],
d
)
// get the distance between the smaller ticks on the rule // base tick size on whether this is a major interval or a minor one
const division = (isMetric ? 0.1 : 0.125) / rulerLength let tick = 1
// we're going to go by fraction, so we want to do this up to 1 // if this tick indicates a whole unit, extra long
for (var d = division; d < 1; d+= division) { if (d.toFixed(3) % (1 / rulerLength) === 0) tick = 3
// make a start point // if this tick indicates half a unit, long
points[`${rulerName}-ruler-${d}-end`] = points[`${pageName}-tl`].shiftFractionTowards(points[`${rulerName}-ruler-end`], d) else if (d.toFixed(3) % (0.5 / rulerLength) === 0) tick = 2
// base tick size on whether this is a major interval or a minor one // make a point for the end of the tick
let tick = 1; points[`${rulerName}-ruler-${d}-tick`] = points[`${rulerName}-ruler-${d}-end`].translate(
// if this tick indicates a whole unit, extra long xAxis ? 0 : tick,
if (d.toFixed(3) % (1/rulerLength) === 0) tick = 3 xAxis ? tick : 0
// if this tick indicates half a unit, long )
else if (d.toFixed(3) % (0.5/rulerLength) === 0) tick = 2
// make a point for the end of the tick // add the whole set to the ruler path
points[`${rulerName}-ruler-${d}-tick`] = points[`${rulerName}-ruler-${d}-end`].translate(xAxis ? 0 : tick, xAxis ? tick : 0)
// add the whole set to the ruler path
paths[`${rulerName}-ruler`]
.line(points[`${rulerName}-ruler-${d}-end`])
.line(points[`${rulerName}-ruler-${d}-tick`])
.line(points[`${rulerName}-ruler-${d}-end`])
}
// add the end
paths[`${rulerName}-ruler`] paths[`${rulerName}-ruler`]
.line(points[`${rulerName}-ruler-${d}-end`])
.line(points[`${rulerName}-ruler-${d}-tick`])
.line(points[`${rulerName}-ruler-${d}-end`])
}
// add the end
paths[`${rulerName}-ruler`]
.line(points[`${rulerName}-ruler-end`]) .line(points[`${rulerName}-ruler-end`])
.line(points[`${rulerName}-ruler-tick`]) .line(points[`${rulerName}-ruler-tick`])
}, },
/** add page markers to the given page */ /** add page markers to the given page */
addPageMarkers({row, col, pageName, withContent}) { addPageMarkers({ row, col, pageName, withContent }, shorthand) {
const {macro, points} = this.shorthand() const { macro, points } = shorthand
// these markers are placed on the top and left of the page, // these markers are placed on the top and left of the page,
// so skip markers for the top row or leftmost column // so skip markers for the top row or leftmost column
if (row !== 0 && withContent[row-1][col]) macro('addPageMarker', { if (row !== 0 && withContent[row - 1][col])
macro('addPageMarker', {
along: [points[`${pageName}-tl`], points[`${pageName}-tr`]], along: [points[`${pageName}-tl`], points[`${pageName}-tr`]],
label: '' + row, label: '' + row,
isRow: true, isRow: true,
pageName pageName,
}) })
if (col !== 0 && withContent[row][col-1]) macro('addPageMarker', { if (col !== 0 && withContent[row][col - 1])
macro('addPageMarker', {
along: [points[`${pageName}-tl`], points[`${pageName}-bl`]], along: [points[`${pageName}-tl`], points[`${pageName}-bl`]],
label: indexStr(col), label: indexStr(col),
isRow: false, isRow: false,
pageName pageName,
}) })
}, },
/** add a page marker for either the row of the column */ /** add a page marker for either the row of the column */
addPageMarker({along, label, isRow, pageName}) { addPageMarker({ along, label, isRow, pageName }) {
const {points, paths, Path} = this.shorthand() const { points, paths, Path } = this.shorthand()
const markerName = `${pageName}-${isRow ? 'row' : 'col'}-marker` const markerName = `${pageName}-${isRow ? 'row' : 'col'}-marker`
// get a point on the center of the appropriate side // get a point on the center of the appropriate side
points[`${markerName}-center`] = along[0].shiftFractionTowards(along[1], 0.5) points[`${markerName}-center`] = along[0]
// add the label to it .shiftFractionTowards(along[1], 0.5)
.attr('data-text', label) // add the label to it
.attr('data-text-class', 'text-sm center baseline-center bold') .attr('data-text', label)
// give it an explicit ID in case we need to hide it later .attr('data-text-class', 'text-sm center baseline-center bold')
.attr('data-text-id', markerName + '-text') // give it an explicit ID in case we need to hide it later
.attr('data-text-id', markerName + '-text')
// get points to make a diamond around the center point // get points to make a diamond around the center point
points[`${markerName}-r`] = points[`${markerName}-center`].translate(-5, 0) points[`${markerName}-r`] = points[`${markerName}-center`].translate(-5, 0)
points[`${markerName}-l`] = points[`${markerName}-center`].translate(5, 0) points[`${markerName}-l`] = points[`${markerName}-center`].translate(5, 0)
points[`${markerName}-t`] = points[`${markerName}-center`].translate(0, -5) points[`${markerName}-t`] = points[`${markerName}-center`].translate(0, -5)
points[`${markerName}-b`] = points[`${markerName}-center`].translate(0, 5) points[`${markerName}-b`] = points[`${markerName}-center`].translate(0, 5)
// make a path for the diamond // make a path for the diamond
paths[markerName] = new Path() paths[markerName] = new Path()
.move(points[`${markerName}-r`]) .move(points[`${markerName}-r`])
.line(points[`${markerName}-t`]) .line(points[`${markerName}-t`])
.line(points[`${markerName}-l`]) .line(points[`${markerName}-l`])
.line(points[`${markerName}-b`]) .line(points[`${markerName}-b`])
.close() .close()
.attr('class', 'fill-interfacing interfacing') .attr('class', 'fill-interfacing interfacing')
// give it an explicit ID in case we need to hide it later // give it an explicit ID in case we need to hide it later
.attr('id', markerName) .attr('id', markerName)
} },
} }
})