diff --git a/packages/i18n/src/locales/en/plugin/plugins/cutlist.yaml b/packages/i18n/src/locales/en/plugin/plugins/cutlist.yaml
deleted file mode 100644
index 103bc6c1e35..00000000000
--- a/packages/i18n/src/locales/en/plugin/plugins/cutlist.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-canvas: Canvas
-cut: Cut
-cuttingLayout: Suggested Cutting Layout
-fabric: Main Fabric
-fabricSize: "{length} of {width} wide material"
-heavyCanvas: Heavy Canvas
-interfacing: Interfacing
-lining: Lining
-lmhCanvas: Light to Medium Hair Canvas
-mirrored: mirrored
-onFoldLower: on the fold
-onFoldAndBias: folded on the bias
-onBias: on the bias
-plastic: Plastic
-ribbing: Ribbing
-edgeOfFabric: Edge of Fabric
diff --git a/packages/react-components/src/pattern/group.mjs b/packages/react-components/src/pattern/group.mjs
index 92d04df3de2..9eac8c43a21 100644
--- a/packages/react-components/src/pattern/group.mjs
+++ b/packages/react-components/src/pattern/group.mjs
@@ -1,3 +1,7 @@
-import React from 'react'
+import React, { forwardRef } from 'react'
-export const Group = (props) => {props.children}
+export const Group = forwardRef((props, ref) => (
+
+ {props.children}
+
+))
diff --git a/packages/react-components/src/pattern/index.mjs b/packages/react-components/src/pattern/index.mjs
index ce185800aa1..cd9da146dbd 100644
--- a/packages/react-components/src/pattern/index.mjs
+++ b/packages/react-components/src/pattern/index.mjs
@@ -1,4 +1,4 @@
-import React from 'react'
+import React, { forwardRef } from 'react'
// Components that can be swizzled
import { Svg as DefaultSvg } from './svg.mjs'
import { Defs as DefaultDefs } from './defs.mjs'
@@ -10,6 +10,7 @@ import { Snippet as DefaultSnippet } from './snippet.mjs'
import { Path as DefaultPath } from './path.mjs'
import { Grid as DefaultGrid } from './grid.mjs'
import { Text as DefaultText, TextOnPath as DefaultTextOnPath } from './text.mjs'
+import { Circle as DefaultCircle } from './circle.mjs'
/*
* Allow people to swizzle these components
@@ -26,55 +27,60 @@ const defaultComponents = {
Grid: DefaultGrid,
Text: DefaultText,
TextOnPath: DefaultTextOnPath,
+ Circle: DefaultCircle,
}
-export const Pattern = ({
- renderProps = false,
- t = (string) => string,
- components = {},
- children = false,
- className = 'freesewing pattern',
- ref = false,
-}) => {
- if (!renderProps) return null
+export const Pattern = forwardRef(
+ (
+ {
+ renderProps = false,
+ t = (string) => string,
+ components = {},
+ children = false,
+ className = 'freesewing pattern',
+ },
+ ref
+ ) => {
+ if (!renderProps) return null
- // Merge default and swizzled components
- components = {
- ...defaultComponents,
- ...components,
+ // Merge default and swizzled components
+ components = {
+ ...defaultComponents,
+ ...components,
+ }
+
+ const { Svg, Defs, Stack, Group } = components
+
+ const optionalProps = {}
+ if (className) optionalProps.className = className
+
+ return (
+
+ )
}
-
- const { Svg, Defs, Stack, Group } = components
-
- const optionalProps = {}
- if (ref) optionalProps.ref = ref
- if (className) optionalProps.className = className
-
- return (
-
- )
-}
+)
diff --git a/packages/react-components/src/pattern/part.mjs b/packages/react-components/src/pattern/part.mjs
index 9d56af4a682..ece24d2f8b3 100644
--- a/packages/react-components/src/pattern/part.mjs
+++ b/packages/react-components/src/pattern/part.mjs
@@ -13,7 +13,7 @@ export const PartInner = forwardRef(
path={part.paths[pathName]}
topLeft={part.topLeft}
bottomRight={part.bottomRight}
- units={settings.units}
+ units={settings[0].units}
{...{ stackName, partName, pathName, part, settings, components, t }}
/>
))}
diff --git a/sites/shared/components/workbench/exporting/export-handler.mjs b/sites/shared/components/workbench/exporting/export-handler.mjs
index 5b5b9dcf057..47bd160661c 100644
--- a/sites/shared/components/workbench/exporting/export-handler.mjs
+++ b/sites/shared/components/workbench/exporting/export-handler.mjs
@@ -2,39 +2,36 @@ import Worker from 'web-worker'
import fileSaver from 'file-saver'
import { themePlugin } from '@freesewing/plugin-theme'
import { pluginI18n } from '@freesewing/plugin-i18n'
-import { pagesPlugin, fabricPlugin } from '../layout/plugin-layout-part.mjs'
+import { pagesPlugin, materialPlugin } from 'shared/plugins/plugin-layout-part.mjs'
import { pluginAnnotations } from '@freesewing/plugin-annotations'
-import { cutLayoutPlugin } from '../layout/cut/plugin-cut-layout.mjs'
-import { fabricSettingsOrDefault } from '../layout/cut/index.mjs'
-import { useFabricLength } from '../layout/cut/settings.mjs'
+import { cutLayoutPlugin } from 'shared/plugins/plugin-cut-layout.mjs'
+import { materialSettingsOrDefault } from 'shared/components/workbench/views/cut/hooks.mjs'
+import { useMaterialLength } from 'shared/components/workbench/views/cut/hooks.mjs'
import { capitalize, formatMm } from 'shared/utils.mjs'
+import {
+ defaultPrintSettings,
+ printSettingsPath,
+} from 'shared/components/workbench/views/print/config.mjs'
import get from 'lodash.get'
+export const ns = ['cut', 'plugin', 'common']
export const exportTypes = {
exportForPrinting: ['a4', 'a3', 'a2', 'a1', 'a0', 'letter', 'tabloid'],
exportForEditing: ['svg', 'pdf'],
exportAsData: ['json', 'yaml', 'github gist'],
}
-export const defaultPdfSettings = {
- size: 'a4',
- orientation: 'portrait',
- margin: 10,
- coverPage: true,
- cutlist: true,
-}
-
/**
* Instantiate a pattern that uses plugins theme, i18n, and cutlist
- * @param {Design} design the design to construct the pattern from
- * @param {Object} gist the gist
- * @param {Object} overwrite settings to overwrite gist settings with
+ * @param {Design} Design the design to construct the pattern from
+ * @param {Object} settings the settings
+ * @param {Object} overwrite settings to overwrite settings settings with
* @param {string} format the export format this pattern will be prepared for
* @param {function} t the i18n function
* @return {Pattern} a pattern
*/
-const themedPattern = (design, gist, overwrite, format, t) => {
- const pattern = new design({ ...gist, ...overwrite })
+const themedPattern = (Design, settings, overwrite, format, t) => {
+ const pattern = new Design({ ...settings, ...overwrite })
// add the theme and translation to the pattern
pattern.use(themePlugin, { stripped: format !== 'svg', skipGrid: ['pages'] })
@@ -48,42 +45,42 @@ const themedPattern = (design, gist, overwrite, format, t) => {
* Generate svgs of all cutting layouts for the pattern
* @param {Pattern} pattern the pattern to generate cutting layouts for
* @param {Design} design the design constructor for the pattern
- * @param {Object} gist the gist
+ * @param {Object} settings the settings
* @param {string} format the export format this pattern will be prepared for
* @param {function} t the i18n function
- * @return {Object} a dictionary of svgs and related translation strings, keyed by fabric
+ * @return {Object} a dictionary of svgs and related translation strings, keyed by material
*/
-const generateCutLayouts = (pattern, design, gist, format, t) => {
- // get the fabrics from the already drafted base pattern
- const fabrics = pattern.setStores[pattern.activeSet].cutlist.getCutFabrics(
+const generateCutLayouts = (pattern, Design, settings, format, t, ui) => {
+ // get the materials from the already drafted base pattern
+ const materials = pattern.setStores[pattern.activeSet].cutlist.getCutFabrics(
pattern.settings[0]
) || ['fabric']
- if (!fabrics.length) return
+ if (!materials.length) return
- const isImperial = gist.units === 'imperial'
+ const isImperial = settings.units === 'imperial'
const cutLayouts = {}
- // each fabric
- fabrics.forEach((f) => {
- // get the settings and layout for that fabric
- const fabricSettings = fabricSettingsOrDefault(gist, f)
- const fabricLayout = get(gist, ['layouts', 'cuttingLayout', f], true)
+ // each material
+ materials.forEach((f) => {
+ // get the settings and layout for that material
+ const materialSettings = materialSettingsOrDefault(settings.units, ui, f)
+ const materialLayout = get(ui, ['layouts', 'cut', f], true)
// make a new pattern
- const fabricPattern = themedPattern(design, gist, { layout: fabricLayout }, format, t)
- // add cut layout plugin and fabric plugin
- .use(cutLayoutPlugin(f, fabricSettings.grainDirection))
- .use(fabricPlugin({ ...fabricSettings, printStyle: true, setPatternSize: 'width' }))
+ const materialPattern = themedPattern(Design, settings, { layout: materialLayout }, format, t)
+ // add cut layout plugin and material plugin
+ .use(cutLayoutPlugin(f, materialSettings.grainDirection))
+ .use(materialPlugin({ ...materialSettings, printStyle: true, setPatternSize: 'width' }))
// draft and render
- fabricPattern.draft()
- const svg = fabricPattern.render()
+ materialPattern.draft()
+ const svg = materialPattern.render()
// include translations
cutLayouts[f] = {
svg,
- title: t('plugin:' + f),
- dimensions: t('plugin:fabricSize', {
- width: formatMm(fabricSettings.sheetWidth, gist.units, 'notags'),
- length: useFabricLength(isImperial, fabricPattern.height, 'notags'),
+ title: t('cut:' + f),
+ dimensions: t('cut:materialSize', {
+ width: formatMm(materialSettings.sheetWidth, settings.units, 'notags'),
+ length: useMaterialLength(isImperial, materialPattern.height, 'notags'),
interpolation: { escapeValue: false },
}),
}
@@ -92,18 +89,28 @@ const generateCutLayouts = (pattern, design, gist, format, t) => {
return cutLayouts
}
/**
- * Handle exporting the draft or gist
+ * Handle exporting the draft or settings
* format: format to export to
- * gist: the gist
- * design: the pattern constructor for the design to be exported
+ * settings: the settings
+ * Design: the pattern constructor for the design to be exported
* t: a translation function to attach to the draft
- * app: an app instance
* onComplete: business to perform after a successful export
* onError: business to perform on error
* */
-export const handleExport = async (format, gist, design, t, app, onComplete, onError) => {
+export const handleExport = async ({
+ format,
+ settings,
+ Design,
+ design,
+ t,
+ startLoading,
+ stopLoading,
+ onComplete,
+ onError,
+ ui,
+}) => {
// start the loading indicator
- app.startLoading()
+ if (typeof startLoading === 'function') startLoading()
// get a worker going
const worker = new Worker(new URL('./export-worker.js', import.meta.url), { type: 'module' })
@@ -115,7 +122,7 @@ export const handleExport = async (format, gist, design, t, app, onComplete, onE
// save it out
if (e.data.blob) {
const fileType = exportTypes.exportForPrinting.indexOf(format) === -1 ? format : 'pdf'
- fileSaver.saveAs(e.data.blob, `freesewing-${gist.design || 'gist'}.${fileType}`)
+ fileSaver.saveAs(e.data.blob, `freesewing-${design || 'pattern'}.${fileType}`)
}
// do additional business
onComplete && onComplete(e)
@@ -127,29 +134,29 @@ export const handleExport = async (format, gist, design, t, app, onComplete, onE
}
// stop the loader
- app.stopLoading()
+ if (typeof stopLoading === 'function') stopLoading()
})
// pdf settings
- const settings = {
- ...defaultPdfSettings,
- ...(gist._state.layout?.forPrinting?.page || {}),
+ const pageSettings = {
+ ...defaultPrintSettings(settings.units),
+ ...get(ui, printSettingsPath, {}),
}
// arguments to pass to the worker
- const workerArgs = { format, gist, settings }
+ const workerArgs = { format, settings, pageSettings }
// data passed to the worker must be JSON serializable, so we can't pass functions or prototypes
// that means if it's not a data export there's more work to do before we can hand off to the worker
if (exportTypes.exportAsData.indexOf(format) === -1) {
- gist.embed = false
+ settings.embed = false
// make a pattern instance for export rendering
- const layout = gist.layouts?.printingLayout || gist.layout || true
- let pattern = themedPattern(design, gist, { layout }, format, t)
+ const layout = settings.layout || ui.layouts?.print || true
+ let pattern = themedPattern(Design, settings, { layout }, format, t)
- // a specified size should override the gist one
+ // a specified size should override the settings one
if (format !== 'pdf') {
- settings.size = format
+ pageSettings.size = format
}
try {
@@ -157,7 +164,7 @@ export const handleExport = async (format, gist, design, t, app, onComplete, onE
if (format !== 'svg') {
pattern.use(
pagesPlugin({
- ...settings,
+ ...pageSettings,
printStyle: true,
renderBlanks: false,
setPatternSize: true,
@@ -166,10 +173,10 @@ export const handleExport = async (format, gist, design, t, app, onComplete, onE
// add the strings that are used on the cover page
workerArgs.strings = {
- design: capitalize(pattern.designConfig.data.name.replace('@freesewing/', '')),
+ design: capitalize(design),
tagline: t('common:sloganCome') + '. ' + t('common:sloganStay'),
url: window.location.href,
- cuttingLayout: t('plugin:cuttingLayout'),
+ cuttingLayout: t('cut:cuttingLayout'),
}
}
@@ -181,15 +188,15 @@ export const handleExport = async (format, gist, design, t, app, onComplete, onE
workerArgs.pages = pattern.setStores[pattern.activeSet].get('pages')
// add cutting layouts if requested
- if (format !== 'svg' && settings.cutlist) {
- workerArgs.cutLayouts = generateCutLayouts(pattern, design, gist, format, t)
+ if (format !== 'svg' && pageSettings.cutlist) {
+ workerArgs.cutLayouts = generateCutLayouts(pattern, Design, settings, format, t, ui)
}
// post a message to the worker with all needed data
worker.postMessage(workerArgs)
} catch (err) {
console.log(err)
- app.stopLoading()
+ if (typeof stopLoading === 'function') stopLoading()
onError && onError(err)
}
}
diff --git a/sites/shared/components/workbench/exporting/export-worker.js b/sites/shared/components/workbench/exporting/export-worker.js
index 4d83a5e90bd..c2ac2040a27 100644
--- a/sites/shared/components/workbench/exporting/export-worker.js
+++ b/sites/shared/components/workbench/exporting/export-worker.js
@@ -7,16 +7,21 @@ import { PdfMaker } from './pdf-maker'
/** when the worker receives data from the page, do the appropriate export */
addEventListener('message', async (e) => {
- const { format, gist, svg } = e.data
+ const { format, settings, svg } = e.data
// handle export by type
try {
- if (format === 'json') return exportJson(gist)
- if (format === 'yaml') return exportYaml(gist)
- if (format === 'github gist') return exportGithubGist(gist)
-
- if (format === 'svg') return exportSvg(svg)
-
- await exportPdf(e.data)
+ switch (format) {
+ case 'json':
+ return exportJson(settings)
+ case 'yaml':
+ return exportYaml(settings)
+ case 'github gist':
+ return exportGithubGist(settings)
+ case 'svg':
+ return exportSvg(svg)
+ default:
+ return await exportPdf(e.data)
+ }
} catch (e) {
postMessage({ success: false, error: e })
close()
@@ -37,9 +42,9 @@ const exportBlob = (blobContent, type) => {
postSuccess(blob)
}
-const exportJson = (gist) => exportBlob(JSON.stringify(gist, null, 2), 'application/json')
+const exportJson = (settings) => exportBlob(JSON.stringify(settings, null, 2), 'application/json')
-const exportYaml = (gist) => exportBlob(yaml.dump(gist), 'application/x-yaml')
+const exportYaml = (settings) => exportBlob(yaml.dump(settings), 'application/x-yaml')
const exportSvg = (svg) => exportBlob(svg, 'image/svg+xml')
diff --git a/sites/shared/components/workbench/exporting/index.mjs b/sites/shared/components/workbench/exporting/index.mjs
index 2a8eec354fd..b6513cca03a 100644
--- a/sites/shared/components/workbench/exporting/index.mjs
+++ b/sites/shared/components/workbench/exporting/index.mjs
@@ -14,23 +14,23 @@ export const ExportDraft = ({ gist, design, app }) => {
setLink(false)
setError(false)
setFormat(format)
- handleExport(
- format,
- gist,
- design,
- t,
- app,
- (e) => {
- if (e.data.link) {
- setLink(e.data.link)
- }
- },
- (e) => {
- if (e.data?.error) {
- setError(true)
- }
- }
- )
+ // handleExport(
+ // format,
+ // gist,
+ // design,
+ // t,
+ // app,
+ // (e) => {
+ // if (e.data.link) {
+ // setLink(e.data.link)
+ // }
+ // },
+ // (e) => {
+ // if (e.data?.error) {
+ // setError(true)
+ // }
+ // }
+ // )
}
return (
diff --git a/sites/shared/components/workbench/exporting/pdf-maker.mjs b/sites/shared/components/workbench/exporting/pdf-maker.mjs
index d7e63fca39d..8598821d72c 100644
--- a/sites/shared/components/workbench/exporting/pdf-maker.mjs
+++ b/sites/shared/components/workbench/exporting/pdf-maker.mjs
@@ -22,7 +22,7 @@ export class PdfMaker {
/** the svg as text to embed in the pdf */
svg
/** the document configuration */
- settings
+ pageSettings
/** the pdfKit instance that is writing the document */
pdf
/** the export buffer to hold pdfKit output */
@@ -51,8 +51,8 @@ export class PdfMaker {
pageCount = 0
lineLevel = 50
- constructor({ svg, settings, pages, strings, cutLayouts }) {
- this.settings = settings
+ constructor({ svg, pageSettings, pages, strings, cutLayouts }) {
+ this.pageSettings = pageSettings
this.pagesWithContent = pages.withContent
this.svg = svg
this.strings = strings
@@ -60,7 +60,7 @@ export class PdfMaker {
this.initPdf()
- this.margin = this.settings.margin * mmToPoints // margin is in mm because it comes from us, so we convert it to points
+ this.margin = this.pageSettings.margin * mmToPoints // margin is in mm because it comes from us, so we convert it to points
this.pageHeight = this.pdf.page.height - this.margin * 2 // this is in points because it comes from pdfKit
this.pageWidth = this.pdf.page.width - this.margin * 2 // this is in points because it comes from pdfKit
@@ -77,8 +77,8 @@ export class PdfMaker {
initPdf() {
// instantiate with the correct size and orientation
this.pdf = new PDFDocument({
- size: this.settings.size.toUpperCase(),
- layout: this.settings.orientation,
+ size: this.pageSettings.size.toUpperCase(),
+ layout: this.pageSettings.orientation,
})
// PdfKit wants to flush the buffer on each new page.
@@ -117,7 +117,7 @@ export class PdfMaker {
/** generate the cover page for the pdf */
async generateCoverPage() {
// don't make one if it's not requested
- if (!this.settings.coverPage) {
+ if (!this.pageSettings.coverPage) {
return
}
@@ -170,8 +170,8 @@ export class PdfMaker {
}
/** generate the title for a cutting layout page */
- async generateCutLayoutTitle(fabricTitle, fabricDimensions) {
- this.addText(this.strings.cuttingLayout, 12, 2).addText(fabricTitle, 28)
+ async generateCutLayoutTitle(materialTitle, materialDimensions) {
+ this.addText(this.strings.cuttingLayout, 12, 2).addText(materialTitle, 28)
this.pdf.lineWidth(1)
this.pdf
@@ -180,16 +180,16 @@ export class PdfMaker {
.stroke()
this.lineLevel += 5
- this.addText(fabricDimensions, 16)
+ this.addText(materialDimensions, 16)
}
/** generate all cutting layout pages */
async generateCutLayoutPages() {
- if (!this.settings.cutlist || !this.cutLayouts) return
+ if (!this.pageSettings.cutlist || !this.cutLayouts) return
- for (const fabric in this.cutLayouts) {
+ for (const material in this.cutLayouts) {
this.nextPage()
- const { title, dimensions, svg } = this.cutLayouts[fabric]
+ const { title, dimensions, svg } = this.cutLayouts[material]
await this.generateCutLayoutTitle(title, dimensions)
await this.generateSvgPage(svg)
}
diff --git a/sites/shared/components/workbench/index.mjs b/sites/shared/components/workbench/index.mjs
index 8b96ae07ede..8d351684bb6 100644
--- a/sites/shared/components/workbench/index.mjs
+++ b/sites/shared/components/workbench/index.mjs
@@ -14,16 +14,24 @@ import { ModalSpinner } from 'shared/components/modal/spinner.mjs'
// Views
import { DraftView, ns as draftNs } from 'shared/components/workbench/views/draft/index.mjs'
import { SaveView, ns as saveNs } from 'shared/components/workbench/views/save/index.mjs'
+import { PrintView, ns as printNs } from 'shared/components/workbench/views/print/index.mjs'
+import { CutView, ns as cutNs } from 'shared/components/workbench/views/cut/index.mjs'
-export const ns = ['account', 'workbench', ...draftNs, ...saveNs]
+export const ns = ['account', 'workbench', ...draftNs, ...saveNs, ...printNs, ...cutNs]
const defaultUi = {
renderer: 'react',
}
+const views = {
+ draft: DraftView,
+ print: PrintView,
+ cut: CutView,
+}
+
const draftViews = ['draft', 'test']
-export const Workbench = ({ design, Design, baseSettings, DynamicDocs, from, set }) => {
+export const Workbench = ({ design, Design, baseSettings, DynamicDocs, from }) => {
// Hooks
const { t, i18n } = useTranslation(ns)
const { language } = i18n
@@ -69,37 +77,44 @@ export const Workbench = ({ design, Design, baseSettings, DynamicDocs, from, set
ui,
language,
DynamicDocs,
+ Design,
}
let viewContent = null
- // Draft view
- if (view === 'draft') {
- // Generate the pattern here so we can pass it down to both the view and the options menu
- const pattern =
- settings.measurements && draftViews.includes(view) ? new Design(settings) : false
+ switch (view) {
+ // Save view
+ case 'save':
+ viewContent =
+ break
+ default: {
+ const layout = ui.layouts?.[view] || settings.layout || true
+ // Generate the pattern here so we can pass it down to both the view and the options menu
+ const pattern = settings.measurements !== undefined && new Design({ layout, ...settings })
- // Return early if the pattern is not initialized yet
- if (typeof pattern.getConfig !== 'function') return null
+ // Return early if the pattern is not initialized yet
+ if (typeof pattern.getConfig !== 'function') return null
- const patternConfig = pattern.getConfig()
- if (ui.renderer === 'svg') {
- // Add theme to svg renderer
- pattern.use(pluginI18n, { t })
- pattern.use(pluginTheme, { skipGrid: ['pages'] })
+ const patternConfig = pattern.getConfig()
+ if (ui.renderer === 'svg') {
+ // Add theme to svg renderer
+ pattern.use(pluginI18n, { t })
+ pattern.use(pluginTheme, { skipGrid: ['pages'] })
+ }
+
+ if (draftViews.includes(view)) {
+ // Draft the pattern or die trying
+ try {
+ pattern.draft()
+ } catch (error) {
+ console.log(error)
+ setError({JSON.stringify(error)})
+ }
+ }
+ const View = views[view]
+ viewContent =
}
- // Draft the pattern or die trying
- try {
- pattern.draft()
- } catch (error) {
- console.log(error)
- setError({JSON.stringify(error)})
- }
- viewContent =
}
- // Save view
- else if (view === 'save') viewContent =
-
return (
<>
diff --git a/sites/shared/components/workbench/layout/cut/index.mjs b/sites/shared/components/workbench/layout/cut/index.mjs
deleted file mode 100644
index 4a3445d2656..00000000000
--- a/sites/shared/components/workbench/layout/cut/index.mjs
+++ /dev/null
@@ -1,126 +0,0 @@
-import { useTranslation } from 'next-i18next'
-import { CutLayoutSettings } from './settings.mjs'
-import { Draft } from '../draft/index.mjs'
-import { fabricPlugin } from '../plugin-layout-part.mjs'
-import { cutLayoutPlugin } from './plugin-cut-layout.mjs'
-import { pluginAnnotations } from '@freesewing/plugin-annotations'
-import { measurementAsMm } from 'shared/utils.mjs'
-import { useEffect } from 'react'
-import get from 'lodash.get'
-
-export const fabricSettingsOrDefault = (gist, fabric) => {
- const isImperial = gist.units === 'imperial'
- const sheetHeight = measurementAsMm(isImperial ? 36 : 100, gist.units)
- const gistSettings = get(gist, ['_state', 'layout', 'forCutting', 'fabric', fabric])
- const sheetWidth = gistSettings?.sheetWidth || measurementAsMm(isImperial ? 54 : 120, gist.units)
- const grainDirection =
- gistSettings?.grainDirection === undefined ? 90 : gistSettings.grainDirection
-
- return { activeFabric: fabric, sheetWidth, grainDirection, sheetHeight }
-}
-
-const activeFabricPath = ['_state', 'layout', 'forCutting', 'activeFabric']
-const useFabricSettings = (gist) => {
- const activeFabric = get(gist, activeFabricPath) || 'fabric'
- return fabricSettingsOrDefault(gist, activeFabric)
-}
-
-const useFabricDraft = (gist, design, fabricSettings) => {
- // get the appropriate layout for the view
- const layout =
- get(gist, ['layouts', gist._state.view, fabricSettings.activeFabric]) || gist.layout || true
- // hand it separately to the design
- const draft = new design({ ...gist, layout })
-
- const layoutSettings = {
- sheetWidth: fabricSettings.sheetWidth,
- sheetHeight: fabricSettings.sheetHeight,
- }
-
- let patternProps
- try {
- // add the fabric plugin to the draft
- draft.use(fabricPlugin(layoutSettings))
- // add the cutLayout plugin
- draft.use(cutLayoutPlugin(fabricSettings.activeFabric, fabricSettings.grainDirection))
- // also, pluginAnnotations and pluginFlip are needed
- draft.use(pluginAnnotations)
-
- // draft the pattern
- draft.draft()
- patternProps = draft.getRenderProps()
- } catch (err) {
- console.log(err, gist)
- }
-
- return { draft, patternProps }
-}
-
-const useFabricList = (draft) => {
- return draft.setStores[0].cutlist.getCutFabrics(draft.settings[0])
-}
-
-const bgProps = { fill: 'none' }
-export const CutLayout = (props) => {
- const { t } = useTranslation(['workbench', 'plugin'])
- const { gist, design, updateGist } = props
-
- // disable xray
- useEffect(() => {
- if (gist?._state?.xray?.enabled) updateGist(['_state', 'xray', 'enabled'], false)
- })
-
- const fabricSettings = useFabricSettings(gist)
- const { draft, patternProps } = useFabricDraft(gist, design, fabricSettings)
- const fabricList = useFabricList(draft)
-
- const setCutFabric = (newFabric) => {
- updateGist(activeFabricPath, newFabric)
- }
-
- let name = design.designConfig.data.name
- name = name.replace('@freesewing/', '')
-
- const settingsProps = {
- gist,
- updateGist,
- patternProps,
- unsetGist: props.unsetGist,
- ...fabricSettings,
- }
-
- return patternProps ? (
-
-
{t('layoutThing', { thing: name }) + ': ' + t('forCutting')}
-
-
- {fabricList.length > 1 ? (
-
- {fabricList.map((title) => (
-
- ))}
-
- ) : null}
-
-
-
- ) : null
-}
diff --git a/sites/shared/components/workbench/layout/cut/settings.mjs b/sites/shared/components/workbench/layout/cut/settings.mjs
deleted file mode 100644
index 02543bebcea..00000000000
--- a/sites/shared/components/workbench/layout/cut/settings.mjs
+++ /dev/null
@@ -1,139 +0,0 @@
-import { ClearIcon, IconWrapper } from 'shared/components/icons.mjs'
-import { useTranslation } from 'next-i18next'
-import { formatFraction128, measurementAsMm, round, formatMm } from 'shared/utils.mjs'
-import { ShowButtonsToggle } from '../draft/buttons.mjs'
-
-const SheetIcon = (props) => (
-
-
-
-)
-
-const GrainIcon = (props) => (
-
-
-
-
-
-
-
-)
-const FabricSizer = ({ gist, updateGist, activeFabric, sheetWidth }) => {
- const { t } = useTranslation(['workbench'])
-
- let val = formatMm(sheetWidth, gist.units, 'none')
- // onChange
- const update = (evt) => {
- evt.stopPropagation()
- let evtVal = evt.target.value
- // set Val immediately so that the input reflects it
- val = evtVal
-
- let useVal = measurementAsMm(evtVal, gist.units)
- // only set to the gist if it's valid
- if (!isNaN(useVal)) {
- updateGist(['_state', 'layout', 'forCutting', 'fabric', activeFabric, 'sheetWidth'], useVal)
- }
- }
-
- return (
-
- )
-}
-export const GrainDirectionPicker = ({ grainDirection, activeFabric, updateGist }) => {
- const { t } = useTranslation(['workbench'])
-
- return (
-
- )
-}
-
-export const useFabricLength = (isImperial, height, format = 'none') => {
- // regular conversion from mm to inches or cm
- const unit = isImperial ? 25.4 : 10
- // conversion from inches or cm to yards or meters
- const fabricUnit = isImperial ? 36 : 100
- // for fabric, these divisions are granular enough
- const rounder = isImperial ? 16 : 10
-
- // we convert the used fabric height to the right units so we can round it
- const inFabricUnits = height / (fabricUnit * unit)
- // we multiply it by the rounder, round it up, then divide by the rounder again to get the rounded amount
- const roundCount = Math.ceil(rounder * inFabricUnits) / rounder
- // format as a fraction for imperial, a decimal for metric
- const count = isImperial ? formatFraction128(roundCount, format) : round(roundCount, 1)
-
- return `${count}${isImperial ? 'yds' : 'm'}`
-}
-
-export const CutLayoutSettings = ({
- gist,
- patternProps,
- unsetGist,
- updateGist,
- activeFabric,
- sheetWidth,
- grainDirection,
-}) => {
- const { t } = useTranslation(['workbench'])
-
- const fabricLength = useFabricLength(gist.units === 'imperial', patternProps.height)
-
- return (
-
-
-
-
-
-
-
- {fabricLength}
-
-
-
-
-
-
- )
-}
diff --git a/sites/shared/components/workbench/layout/draft/index.mjs b/sites/shared/components/workbench/layout/draft/index.mjs
deleted file mode 100644
index bf0a16356d0..00000000000
--- a/sites/shared/components/workbench/layout/draft/index.mjs
+++ /dev/null
@@ -1,116 +0,0 @@
-import { useRef } from 'react'
-import { Stack } from './stack.mjs'
-import { SvgWrapper } from '../../pattern/svg.mjs'
-import { PartInner } from '../../pattern/part.mjs'
-import get from 'lodash.get'
-
-export const Draft = (props) => {
- const {
- patternProps,
- gist,
- updateGist,
- app,
- bgProps = {},
- fitLayoutPart = false,
- layoutType = 'printingLayout',
- layoutSetType = 'forPrinting',
- } = props
-
- const svgRef = useRef(null)
- if (!patternProps) return null
- // keep a fresh copy of the layout because we might manipulate it without saving to the gist
- const layoutPath = ['layouts'].concat(layoutType)
- let layout = get(patternProps.settings[0], layoutPath) || {
- ...patternProps.autoLayout,
- width: patternProps.width,
- height: patternProps.height,
- }
-
- // Helper method to update part layout and re-calculate width * height
- const updateLayout = (name, config, history = true) => {
- // Start creating new layout
- const newLayout = { ...layout }
- newLayout.stacks[name] = config
-
- // Pattern topLeft and bottomRight
- let topLeft = { x: 0, y: 0 }
- let bottomRight = { x: 0, y: 0 }
- for (const pname in patternProps.stacks) {
- if (pname == props.layoutPart && !fitLayoutPart) continue
- let partLayout = newLayout.stacks[pname]
-
- // Pages part does not have its topLeft and bottomRight set by core since it's added post-draft
- if (partLayout?.tl) {
- // set the pattern extremes
- topLeft.x = Math.min(topLeft.x, partLayout.tl.x)
- topLeft.y = Math.min(topLeft.y, partLayout.tl.y)
- bottomRight.x = Math.max(bottomRight.x, partLayout.br.x)
- bottomRight.y = Math.max(bottomRight.y, partLayout.br.y)
- }
- }
-
- newLayout.width = bottomRight.x - topLeft.x
- newLayout.height = bottomRight.y - topLeft.y
- newLayout.bottomRight = bottomRight
- newLayout.topLeft = topLeft
-
- if (history) {
- updateGist(layoutPath, newLayout, history)
- } else {
- // we don't put it in the gist if it shouldn't contribute to history because we need some of the data calculated here for rendering purposes on the initial layout, but we don't want to actually save a layout until the user manipulates it. This is what allows the layout to respond appropriately to settings changes. Once the user has starting playing with the layout, all bets are off
- layout = newLayout
- }
- }
-
- const viewBox = layout.topLeft
- ? `${layout.topLeft.x} ${layout.topLeft.y} ${layout.width} ${layout.height}`
- : false
-
- // 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.
- // Bottom in SVG means we need to draw it first
- const stacks = [
- ,
- ]
-
- // then make a stack component for each remaining stack
- for (var stackName in patternProps.stacks) {
- if (stackName === props.layoutPart) {
- continue
- }
- let stack = patternProps.stacks[stackName]
-
- const stackPart = (
-
- )
-
- stacks.push(stackPart)
- }
-
- return (
-
-
- {stacks}
-
- )
-}
diff --git a/sites/shared/components/workbench/layout/draft/stack.mjs b/sites/shared/components/workbench/layout/draft/stack.mjs
deleted file mode 100644
index f489c3ed5b0..00000000000
--- a/sites/shared/components/workbench/layout/draft/stack.mjs
+++ /dev/null
@@ -1,260 +0,0 @@
-/*
- * This React component is a long way from perfect, but it's a start for
- * handling custom layouts.
- *
- * There are a few reasons that (at least in my opinion) implementing this is non-trivial:
- *
- * 1) React re-render vs DOM updates
- *
- * For performance reasons, we can't re-render with React when the user drags a
- * pattern part (or rotates it). It would kill performance.
- * So, we don't re-render with React upon dragging/rotating, but instead manipulate
- * the DOM directly.
- *
- * So far so good, but of course we don't want a pattern that's only correctly laid
- * out in the DOM. We want to update the pattern gist so that the new layout is stored.
- * For this, we re-render with React on the end of the drag (or rotate).
- *
- * Handling this balance between DOM updates and React re-renders is a first contributing
- * factor to why this component is non-trivial
- *
- * 2) SVG vs DOM coordinates
- *
- * When we drag or rotate with the mouse, all the events are giving us coordinates of
- * where the mouse is in the DOM.
- *
- * The layout uses coordinates from the embedded SVG which are completely different.
- *
- * We run `getScreenCTM().inverse()` on the svg element to pass to `matrixTransform` on a `DOMPointReadOnly` for dom to svg space conversions.
- *
- * 3) Part-level transforms
- *
- * All parts use their center as the transform-origin to simplify transforms, especially flipping and rotating.
- *
- * 4) Bounding box
- *
- * We use `getBoundingClientRect` rather than `getBBox` because it provides more data and factors in the transforms.
- * We then use our `domToSvg` function to move the points back into the SVG space.
- *
- *
- * Known issues
- * - currently none
- *
- * 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.
- */
-import { useRef, useState, useEffect } from 'react'
-import { generateStackTransform, getTransformedBounds } from '@freesewing/core'
-import { Part } from '../../draft/part.mjs'
-import { getProps, angle } from '../../draft/utils.mjs'
-import { drag } from 'd3-drag'
-import { select } from 'd3-selection'
-import { Buttons } from './buttons.mjs'
-import get from 'lodash.get'
-
-export const Stack = (props) => {
- const { layout, stack, stackName, gist } = props
-
- const stackLayout = layout.stacks?.[stackName]
- const stackExists = typeof stackLayout?.move?.x !== 'undefined'
-
- // Use a ref for direct DOM manipulation
- const stackRef = useRef(null)
- const centerRef = useRef(null)
- const innerRef = useRef(null)
-
- // State variable to switch between moving or rotating the part
- const [rotate, setRotate] = useState(false)
-
- // update the layout on mount
- useEffect(() => {
- // only update if there's a rendered part and it's not the pages or fabric part
- if (stackRef.current && !props.isLayoutPart) {
- updateLayout(false)
- }
- }, [stackRef, stackLayout])
-
- // Initialize drag handler
- useEffect(() => {
- // don't drag the pages
- if (props.isLayoutPart || !stackExists) return
- handleDrag(select(stackRef.current))
- }, [rotate, stackRef, stackLayout])
-
- // // Don't just assume this makes sense
- if (!stackExists) return null
-
- // 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
- // whole thing a bit tricky to wrap your head around
- let translateX = stackLayout.move.x
- let translateY = stackLayout.move.y
- let stackRotation = stackLayout.rotate || 0
- let rotation = stackRotation
- let flipX = !!stackLayout.flipX
- let flipY = !!stackLayout.flipY
-
- const center = {
- x: stack.topLeft.x + (stack.bottomRight.x - stack.topLeft.x) / 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 */
- const getRotation = (event) =>
- angle(center, event.subject) - angle(center, { x: event.x, y: event.y })
-
- const setTransforms = () => {
- // get the transform attributes
- const transforms = generateStackTransform(translateX, translateY, rotation, flipX, flipY, stack)
-
- const me = select(stackRef.current)
- me.attr('transform', transforms.join(' '))
-
- return transforms
- }
-
- let didDrag = false
- const handleDrag = drag()
- // subject allows us to save data from the start of the event to use throughout event handing
- .subject(function (event) {
- return rotate
- ? // if we're rotating, the subject is the mouse position
- { x: event.x, y: event.y }
- : // if we're moving, the subject is the part's x,y coordinates
- { x: translateX, y: translateY }
- })
- .on('drag', function (event) {
- if (!event.dx && !event.dy) return
-
- if (rotate) {
- let newRotation = getRotation(event)
- // shift key to snap the rotation
- if (event.sourceEvent.shiftKey) {
- 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
- if (flipX) newRotation *= -1
- if (flipY) newRotation *= -1
-
- rotation = stackRotation + newRotation
- } else {
- translateX = event.x
- translateY = event.y
- }
-
- // a drag happened, so we should update the layout when we're done
- didDrag = true
- setTransforms()
- })
- .on('end', function () {
- // save to gist if anything actually changed
- if (didDrag) updateLayout()
-
- didDrag = false
- })
-
- /** reset the part's transforms */
- const resetPart = () => {
- rotation = 0
- flipX = 0
- flipY = 0
- updateLayout()
- }
-
- /** toggle between dragging and rotating */
- const toggleDragRotate = () => {
- // only respond if the part should be able to drag/rotate
- if (!stackRef.current || props.isLayoutPart) {
- return
- }
-
- setRotate(!rotate)
- }
-
- /** update the layout either locally or in the gist */
- const updateLayout = (history = true) => {
- /** don't mess with what we don't lay out */
- if (!stackRef.current || props.isLayoutPart) return
-
- // set the transforms on the stack in order to calculate from the latest position
- const transforms = setTransforms()
-
- // apply the transforms to the bounding box to get the new extents of the stack
- const { tl, br } = getTransformedBounds(stack, transforms)
-
- // update it on the draft component
- props.updateLayout(
- stackName,
- {
- move: {
- x: translateX,
- y: translateY,
- },
- rotate: rotation % 360,
- flipX,
- flipY,
- tl,
- br,
- },
- history
- )
- }
-
- /** Method to flip (mirror) the part along the X or Y axis */
- const flip = (axis) => {
- if (axis === 'x') flipX = !flipX
- else flipY = !flipY
- updateLayout()
- }
-
- /** method to rotate 90 degrees */
- const rotate90 = (direction = 1) => {
- if (flipX) direction *= -1
- if (flipY) direction *= -1
-
- rotation += 90 * direction
-
- updateLayout()
- }
-
- // don't render if the part is empty
- // if (Object.keys(part.snippets).length === 0 && Object.keys(part.paths).length === 0) return null;
-
- const showButtons = get(gist, ['_state', 'layout', props.layoutSetType, 'showButtons'], true)
- return (
-
-
- {stack.parts.map((part) => (
-
- ))}
-
- {!props.isLayoutPart && (
- <>
-
-
- {showButtons ? (
-
- ) : null}
- >
- )}
-
- )
-}
diff --git a/sites/shared/components/workbench/layout/print/index.mjs b/sites/shared/components/workbench/layout/print/index.mjs
deleted file mode 100644
index ca99b1831cd..00000000000
--- a/sites/shared/components/workbench/layout/print/index.mjs
+++ /dev/null
@@ -1,78 +0,0 @@
-import { useEffect, useState } from 'react'
-import { useTranslation } from 'next-i18next'
-import { PrintLayoutSettings } from './settings.mjs'
-import { Draft } from '../draft/index.mjs'
-import { pagesPlugin } from '../plugin-layout-part.mjs'
-import {
- handleExport,
- defaultPdfSettings,
-} from 'shared/components/workbench/exporting/export-handler.mjs'
-import { Popout } from 'shared/components/popout.mjs'
-
-export const PrintLayout = (props) => {
- // disable xray
- useEffect(() => {
- if (props.gist?._state?.xray?.enabled) props.updateGist(['_state', 'xray', 'enabled'], false)
- })
-
- const { t } = useTranslation(['workbench', 'plugin'])
- const [error, setError] = useState(false)
-
- const draft = props.draft
-
- // add the pages plugin to the draft
- const layoutSettings = {
- ...defaultPdfSettings,
- ...props.gist?._state?.layout?.forPrinting?.page,
- }
- draft.use(pagesPlugin(layoutSettings))
-
- let patternProps
- try {
- // draft the pattern
- draft.draft()
- patternProps = draft.getRenderProps()
- } catch (err) {
- console.log(err, props.gist)
- }
- const bgProps = { fill: 'none' }
-
- const exportIt = () => {
- setError(false)
- handleExport(
- 'pdf',
- props.gist,
- props.design,
- t,
- props.app,
- () => setError(false),
- () => setError(true)
- )
- }
-
- let name = props.design.designConfig.data.name
- name = name.replace('@freesewing/', '')
- return (
-
-
{t('layoutThing', { thing: name }) + ': ' + t('forPrinting')}
diff --git a/sites/shared/components/workbench/pattern/movable/index.mjs b/sites/shared/components/workbench/pattern/movable/index.mjs
new file mode 100644
index 00000000000..1a7024ad362
--- /dev/null
+++ b/sites/shared/components/workbench/pattern/movable/index.mjs
@@ -0,0 +1,100 @@
+import { useRef } from 'react'
+import { PanZoomPattern } from 'shared/components/workbench/pan-zoom-pattern.mjs'
+import { MovableStack } from './stack.mjs'
+
+export const MovablePattern = ({
+ renderProps,
+ showButtons = true,
+ update,
+ fitImmovable = false,
+ immovable = [],
+ layoutPath,
+}) => {
+ const svgRef = useRef(null)
+ if (!renderProps) return null
+
+ // keep a fresh copy of the layout because we might manipulate it without saving to the gist
+ let layout =
+ renderProps.settings[0].layout === true
+ ? {
+ ...renderProps.autoLayout,
+ width: renderProps.width,
+ height: renderProps.height,
+ }
+ : renderProps.settings[0].layout
+
+ // Helper method to update part layout and re-calculate width * height
+ const updateLayout = (name, config, history = true) => {
+ // Start creating new layout
+ const newLayout = { ...layout }
+ newLayout.stacks[name] = config
+
+ // Pattern topLeft and bottomRight
+ let topLeft = { x: 0, y: 0 }
+ let bottomRight = { x: 0, y: 0 }
+ for (const pname in renderProps.stacks) {
+ if (immovable.includes(pname) && !fitImmovable) continue
+ let partLayout = newLayout.stacks[pname]
+
+ // Pages part does not have its topLeft and bottomRight set by core since it's added post-draft
+ if (partLayout?.tl) {
+ // set the pattern extremes
+ topLeft.x = Math.min(topLeft.x, partLayout.tl.x)
+ topLeft.y = Math.min(topLeft.y, partLayout.tl.y)
+ bottomRight.x = Math.max(bottomRight.x, partLayout.br.x)
+ bottomRight.y = Math.max(bottomRight.y, partLayout.br.y)
+ }
+ }
+
+ newLayout.width = bottomRight.x - topLeft.x
+ newLayout.height = bottomRight.y - topLeft.y
+ newLayout.bottomRight = bottomRight
+ newLayout.topLeft = topLeft
+
+ if (history) {
+ update.ui(layoutPath, newLayout)
+ } else {
+ // we don't put it in the gist if it shouldn't contribute to history because we need some of the data calculated here for rendering purposes on the initial layout, but we don't want to actually save a layout until the user manipulates it. This is what allows the layout to respond appropriately to settings changes. Once the user has starting playing with the layout, all bets are off
+ layout = newLayout
+ }
+ }
+
+ const sortedStacks = {}
+ Object.keys(renderProps.stacks)
+ .sort((a, b) => {
+ const hasA = immovable.includes(a)
+ const hasB = immovable.includes(b)
+ if (hasA && !hasB) return -1
+ if (!hasA && hasB) return 1
+ return 0
+ })
+ .forEach((s) => (sortedStacks[s] = renderProps.stacks[s]))
+
+ const sortedRenderProps = { ...renderProps, stacks: sortedStacks }
+
+ const Stack = ({ stackName, stack, settings, components, t }) => (
+
+ )
+
+ return (
+
+ )
+}
diff --git a/sites/shared/components/workbench/pattern/movable/stack.mjs b/sites/shared/components/workbench/pattern/movable/stack.mjs
new file mode 100644
index 00000000000..599e03cd693
--- /dev/null
+++ b/sites/shared/components/workbench/pattern/movable/stack.mjs
@@ -0,0 +1,272 @@
+/*
+ * This React component is a long way from perfect, but it's a start for
+ * handling custom layouts.
+ *
+ * There are a few reasons that (at least in my opinion) implementing this is non-trivial:
+ *
+ * 1) React re-render vs DOM updates
+ *
+ * For performance reasons, we can't re-render with React when the user drags a
+ * pattern part (or rotates it). It would kill performance.
+ * So, we don't re-render with React upon dragging/rotating, but instead manipulate
+ * the DOM directly.
+ *
+ * So far so good, but of course we don't want a pattern that's only correctly laid
+ * out in the DOM. We want to update the pattern gist so that the new layout is stored.
+ * For this, we re-render with React on the end of the drag (or rotate).
+ *
+ * Handling this balance between DOM updates and React re-renders is a first contributing
+ * factor to why this component is non-trivial
+ *
+ * 2) SVG vs DOM coordinates
+ *
+ * When we drag or rotate with the mouse, all the events are giving us coordinates of
+ * where the mouse is in the DOM.
+ *
+ * The layout uses coordinates from the embedded SVG which are completely different.
+ *
+ * We run `getScreenCTM().inverse()` on the svg element to pass to `matrixTransform` on a `DOMPointReadOnly` for dom to svg space conversions.
+ *
+ * 3) Part-level transforms
+ *
+ * All parts use their center as the transform-origin to simplify transforms, especially flipping and rotating.
+ *
+ * 4) Bounding box
+ *
+ * We use `getBoundingClientRect` rather than `getBBox` because it provides more data and factors in the transforms.
+ * We then use our `domToSvg` function to move the points back into the SVG space.
+ *
+ *
+ * Known issues
+ * - currently none
+ *
+ * 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.
+ */
+import { useRef, useState, useEffect, useCallback } from 'react'
+import { generateStackTransform, getTransformedBounds } from '@freesewing/core'
+import { getProps } from 'pkgs/react-components/src/pattern/utils.mjs'
+import { angle } from '../utils.mjs'
+import { drag } from 'd3-drag'
+import { select } from 'd3-selection'
+import { Buttons } from './transform-buttons.mjs'
+
+export const MovableStack = ({
+ stackName,
+ stack,
+ components,
+ t,
+ movable = true,
+ layout,
+ updateLayout,
+ showButtons,
+ settings,
+}) => {
+ const stackExists = !movable || typeof layout?.move?.x !== 'undefined'
+
+ // Use a ref for direct DOM manipulation
+ const stackRef = useRef(null)
+ const innerRef = useRef(null)
+
+ // State variable to switch between moving or rotating the part
+ const [rotate, setRotate] = useState(false)
+
+ // This is kept as state to avoid re-rendering on drag, which would kill performance
+ // It's a bit of an anti-pattern, but we'll directly manipulate the properties instead of updating the state
+ // Managing the difference between re-render and direct DOM updates makes this
+ // whole thing a bit tricky to wrap your head around
+ const stackRotation = layout?.rotate || 0
+ const [liveTransforms] = useState({
+ translateX: layout?.move.x,
+ translateY: layout?.move.y,
+ rotation: stackRotation,
+ flipX: !!layout?.flipX,
+ flipY: !!layout?.flipY,
+ })
+
+ const center = stack.topLeft && {
+ x: stack.topLeft.x + (stack.bottomRight.x - stack.topLeft.x) / 2,
+ y: stack.topLeft.y + (stack.bottomRight.y - stack.topLeft.y) / 2,
+ }
+
+ const setTransforms = useCallback(() => {
+ // get the transform attributes
+ const { translateX, translateY, rotation, flipX, flipY } = liveTransforms
+ const transforms = generateStackTransform(translateX, translateY, rotation, flipX, flipY, stack)
+
+ const me = select(stackRef.current)
+ me.attr('transform', transforms.join(' '))
+
+ return transforms
+ }, [liveTransforms, stackRef, stack])
+
+ /** update the layout either locally or in the gist */
+ const updateStacklayout = useCallback(
+ (history = true) => {
+ /** don't mess with what we don't lay out */
+ if (!stackRef.current || !movable) return
+
+ // set the transforms on the stack in order to calculate from the latest position
+ const transforms = setTransforms()
+
+ // apply the transforms to the bounding box to get the new extents of the stack
+ const { tl, br } = getTransformedBounds(stack, transforms)
+
+ // update it on the draft component
+ updateLayout(
+ stackName,
+ {
+ move: {
+ x: liveTransforms.translateX,
+ y: liveTransforms.translateY,
+ },
+ rotate: liveTransforms.rotation % 360,
+ flipX: liveTransforms.flipX,
+ flipY: liveTransforms.flipY,
+ tl,
+ br,
+ },
+ history
+ )
+ },
+ [stackRef, setTransforms, updateLayout, liveTransforms, movable, stack, stackName]
+ )
+
+ // update the layout on mount
+ useEffect(() => {
+ // only update if there's a rendered part and it's not an imovable part
+ if (stackRef.current && movable) {
+ updateStacklayout(false)
+ }
+ }, [stackRef, movable, updateStacklayout])
+
+ /** reset the part's transforms */
+ const resetPart = () => {
+ liveTransforms.rotation = 0
+ liveTransforms.flipX = 0
+ liveTransforms.flipY = 0
+ updateStacklayout()
+ }
+
+ /** toggle between dragging and rotating */
+ const toggleDragRotate = () => {
+ // only respond if the part should be able to drag/rotate
+ if (!stackRef.current || !movable) {
+ return
+ }
+
+ setRotate(!rotate)
+ }
+
+ /** Method to flip (mirror) the part along the X or Y axis */
+ const flip = (axis) => {
+ if (axis === 'x') liveTransforms.flipX = !liveTransforms.flipX
+ else liveTransforms.flipY = !liveTransforms.flipY
+ updateStacklayout()
+ }
+
+ /** method to rotate 90 degrees */
+ const rotate90 = (direction = 1) => {
+ if (liveTransforms.flipX) direction *= -1
+ if (liveTransforms.flipY) direction *= -1
+
+ liveTransforms.rotation += 90 * direction
+
+ updateStacklayout()
+ }
+
+ /** 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 })
+
+ let didDrag = false
+ const handleDrag =
+ movable &&
+ drag()
+ // subject allows us to save data from the start of the event to use throughout event handing
+ .subject(function (event) {
+ return rotate
+ ? // if we're rotating, the subject is the mouse position
+ { x: event.x, y: event.y }
+ : // if we're moving, the subject is the part's x,y coordinates
+ { x: liveTransforms.translateX, y: liveTransforms.translateY }
+ })
+ .on('drag', function (event) {
+ if (!event.dx && !event.dy) return
+
+ if (rotate) {
+ let newRotation = getRotation(event)
+ // shift key to snap the rotation
+ if (event.sourceEvent.shiftKey) {
+ 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
+ if (liveTransforms.flipX) newRotation *= -1
+ if (liveTransforms.flipY) newRotation *= -1
+
+ liveTransforms.rotation = stackRotation + newRotation
+ } else {
+ liveTransforms.translateX = event.x
+ liveTransforms.translateY = event.y
+ }
+
+ // a drag happened, so we should update the layout when we're done
+ didDrag = true
+ setTransforms()
+ })
+ .on('end', function () {
+ // save to gist if anything actually changed
+ if (didDrag) updateStacklayout()
+
+ didDrag = false
+ })
+
+ // Initialize drag handler
+ useEffect(() => {
+ // don't drag the pages
+ if (!movable || !stackExists) return
+ handleDrag(select(stackRef.current))
+ }, [stackRef, movable, stackExists, handleDrag])
+
+ // // Don't just assume this makes sense
+ if (!stackExists) return null
+
+ const { Group, Part } = components
+ return (
+
+
+ {[...stack.parts].map((part, key) => (
+
+ ))}
+
+ {movable && (
+ <>
+
+ {showButtons ? (
+
+ ) : null}
+ >
+ )}
+
+ )
+}
diff --git a/sites/shared/components/workbench/layout/draft/buttons.mjs b/sites/shared/components/workbench/pattern/movable/transform-buttons.mjs
similarity index 88%
rename from sites/shared/components/workbench/layout/draft/buttons.mjs
rename to sites/shared/components/workbench/pattern/movable/transform-buttons.mjs
index 84562e672a3..cb5634f5928 100644
--- a/sites/shared/components/workbench/layout/draft/buttons.mjs
+++ b/sites/shared/components/workbench/pattern/movable/transform-buttons.mjs
@@ -1,6 +1,5 @@
import { useTranslation } from 'next-i18next'
import { ClearIcon } from 'shared/components/icons.mjs'
-import get from 'lodash.get'
const Triangle = ({ transform = 'translate(0,0)', fill = 'currentColor' }) => (
{
)
}
-export const ShowButtonsToggle = ({ gist, layoutSetType, updateGist }) => {
+export const ShowButtonsToggle = ({ ui, update }) => {
const { t } = useTranslation('workbench')
- const path = ['_state', 'layout', layoutSetType, 'showButtons']
- const showButtons = get(gist, path, true)
- const setShowButtons = () => updateGist(path, !showButtons)
-
+ const hideButtons = (evt) => {
+ update.ui('hideMovableButtons', !evt.target.checked)
+ }
return (
-