1
0
Fork 0

[breaking]: FreeSewing v4 (#7297)

Refer to the CHANGELOG for all info.

---------

Co-authored-by: Wouter van Wageningen <wouter.vdub@yahoo.com>
Co-authored-by: Josh Munic <jpmunic@gmail.com>
Co-authored-by: Jonathan Haas <haasjona@gmail.com>
This commit is contained in:
Joost De Cock 2025-04-01 16:15:20 +02:00 committed by GitHub
parent d22fbe78d9
commit 51dc1d9732
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6626 changed files with 142053 additions and 150606 deletions

View file

@ -0,0 +1,248 @@
import React from 'react'
// Dependencies
import { defaultConfig as config } from '../config/index.mjs'
import { measurementAsMm } from '@freesewing/utils'
import { linkClasses } from '@freesewing/utils'
/*
* Components
* Note that these are only used as returns values
* There's no JSX in here so no React import needed
*/
import {
DetailIcon,
ExpandIcon,
IncludeIcon,
MarginIcon,
PaperlessIcon,
SaIcon,
ScaleIcon,
UnitsIcon,
} from '@freesewing/react/components/Icon'
export function defaultSa(units, inMm = true) {
const dflt = units === 'imperial' ? 0.5 : 1
return inMm ? measurementAsMm(dflt, units) : dflt
}
export function defaultSamm(units, inMm = true) {
const dflt = units === 'imperial' ? 0.5 : 1
return inMm ? measurementAsMm(dflt, units) : dflt
}
/** custom event handlers for inputs that need them */
export function menuCoreSettingsOnlyHandler({ updateHandler, current }) {
return function (path, part) {
// Is this a reset?
if (part === undefined || part === '__UNSET__') return updateHandler(path, part)
// add or remove the part from the set
let newParts = new Set(current || [])
if (newParts.has(part)) newParts.delete(part)
else newParts.add(part)
// if the set is now empty, reset
if (newParts.size < 1) newParts = undefined
// otherwise use the new set
else newParts = [...newParts]
updateHandler(path, newParts)
}
}
export function menuCoreSettingsSammHandler({ updateHandler, config }) {
return function (_path, newCurrent) {
// convert to millimeters if there's a value
newCurrent = newCurrent === undefined ? config.dflt : newCurrent
// update both values to match
updateHandler(['samm'], newCurrent)
updateHandler(['sa'], newCurrent)
}
}
export function menuCoreSettingsSaboolHandler({ toggleSa }) {
return toggleSa
}
const CoreDocsLink = ({ item }) => (
<a href={`/docs/about/site/draft/#${item.toLowerCase()}`} className={`${linkClasses} tw-px-2`}>
Learn more
</a>
)
export function menuCoreSettingsStructure({ units = 'metric', sabool = false, parts = [] }) {
return {
sabool: {
dense: true,
title: 'Include seam allowance',
about: (
<>
Controls whether or not you want to include seam allowance on your pattern.
<CoreDocsLink item="sabool" />
</>
),
ux: config.uxLevels.core.sa,
list: [0, 1],
choiceTitles: {
0: 'Do not include seam allowance',
1: 'Include seam allowance',
},
valueTitles: {
0: 'No',
1: 'Yes',
},
dflt: 0,
icon: SaIcon,
},
samm: sabool
? {
title: 'Seam Allowance Size',
about: (
<>
Controls the size of the pattern's seam allowance.
<CoreDocsLink item="sa" />
</>
),
ux: config.uxLevels.core.sa,
min: 0,
max: units === 'imperial' ? 2 : 2.5,
dflt: defaultSamm(units),
icon: SaIcon,
}
: false,
units: {
dense: true,
title: 'Pattern units',
about: (
<>
Allows you to switch between metric and imperial units on the pattern.
<CoreDocsLink item="units" />
</>
),
ux: config.uxLevels.core.units,
list: ['metric', 'imperial'],
dflt: 'metric',
choiceTitles: {
metric: 'Metric Units (cm)',
imperial: 'Imperial Units (inch)',
},
valueTitles: {
metric: 'Metric',
imperial: 'Imperial',
},
icon: UnitsIcon,
},
paperless: {
dense: true,
title: 'Paperless pattern',
about: (
<>
Trees are awesome, and taping together sewing patterns is not much fun. Try our paperless
mode to avoid the need to print out your pattern altogether.
<CoreDocsLink item="paperless" />
</>
),
ux: config.uxLevels.core.paperless,
list: [0, 1],
choiceTitles: {
0: 'Generate a regular pattern',
1: 'Generate a paperless pattern',
},
valueTitles: {
0: 'No',
1: 'Yes',
},
dflt: 0,
icon: PaperlessIcon,
},
complete: {
dense: true,
title: 'Generate a detailed pattern',
about: (
<>
Controls how detailed the pattern is; Either a complete pattern with all details, or a
basic outline of the pattern parts.
<CoreDocsLink item="complete" />
</>
),
ux: config.uxLevels.core.complete,
list: [1, 0],
dflt: 1,
choiceTitles: {
0: 'Generate a pattern outline',
1: 'Generate a detailed pattern',
},
valueTitles: {
0: 'No',
1: 'Yes',
},
icon: DetailIcon,
},
expand: {
dense: true,
title: 'Expand pattern parts',
about: (
<>
Controls efforts to save paper. Disable this to expand all pattern parts at the cost of
using more space & paper.
<CoreDocsLink item="expand" />
</>
),
ux: config.uxLevels.core.expand,
list: [1, 0],
dflt: 1,
choiceTitles: {
0: 'Keep pattern parts compact where possible',
1: 'Expand all pattern parts',
},
valueTitles: {
0: 'No',
1: 'Yes',
},
icon: ExpandIcon,
},
only: {
dense: true,
title: 'Only included selected pattern parts',
about: (
<>
Allows you to control what parts to include in your pattern.
<CoreDocsLink item="only" />
</>
),
ux: config.uxLevels.core.only,
dflt: false,
list: parts,
parts,
icon: IncludeIcon,
},
scale: {
title: 'Pattern annotations scale',
about: (
<>
Allows you to control the scale of annotations on the pattern. This is most useful when
generating very small patterns, like for doll outfits.
<CoreDocsLink item="scale" />
</>
),
ux: config.uxLevels.core.scale,
min: 0.1,
max: 5,
dflt: 1,
step: 0.1,
icon: ScaleIcon,
},
margin: {
title: 'Pattern parts margin',
about: (
<>
Controls the gap between pattern parts, as well as the gap between the parts and the page
edge.
<CoreDocsLink item="margin" />
</>
),
ux: config.uxLevels.core.margin,
min: 0,
max: 2.5,
dflt: measurementAsMm(units === 'imperial' ? 0.125 : 0.2, units),
icon: MarginIcon,
},
}
}

View file

@ -0,0 +1,129 @@
import React from 'react'
import { mergeOptions } from '@freesewing/core'
import { designOptionType, set, orderBy } from '@freesewing/utils'
import { i18n } from '@freesewing/collection'
import { linkClasses } from '@freesewing/utils'
const DesignDocsLink = ({ design, item }) => (
<a
href={`/docs/designs/${design}/options/#${item.toLowerCase()}`}
className={`${linkClasses} tw-px-2`}
target="_BLANK"
>
Learn more
</a>
)
export function menuDesignOptionsStructure(design, options, settings, asFullList = false) {
if (!options) return options
const sorted = {}
for (const [name, option] of Object.entries(options)) {
if (typeof option === 'object') {
sorted[name] = {
...option,
name,
title: i18n[design]?.en?.o?.[name]?.t || name,
about: (
<span>
{i18n[design]?.en?.o?.[name]?.d || name}
<DesignDocsLink item={name} design={design} />
</span>
),
dense: true,
sideBySide: true,
}
}
}
// Save us some typing to access English options
const eno = i18n[design]?.en?.o || {}
const menu = {}
for (const option of orderBy(sorted, ['order', 'menu', 'name'], ['asc', 'asc', 'asc'])) {
if (typeof option === 'object') {
const oType = designOptionType(option)
option.dflt = option.dflt || option[oType]
// Percentage option tweaks
if (oType === 'pct') option.dflt /= 100
// List option tweaks
else if (oType === 'list') {
option.valueTitles = {}
option.choiceTitles = {}
option.choiceDescriptions = {}
for (const entry of option.list) {
option.choiceTitles[entry] = eno[`${option.name}.${entry}`]?.t || option.name
option.choiceDescriptions[entry] = eno[`${option.name}.${entry}`]?.d || ''
option.valueTitles[entry] = eno[`${option.name}.${entry}`]?.t || option.name
}
}
// Bool option tweaks
else if (oType === 'bool') {
option.list = [false, true]
option.valueTitles = {}
option.choiceTitles = {}
option.choiceDescriptions = {}
for (const entry of option.list) {
option.choiceTitles.false = eno[`${option.name}No`]?.t || option.name
option.choiceDescriptions.false = eno[`${option.name}No`]?.d || 'No'
option.valueTitles.false = 'No'
option.choiceTitles.true = eno[`${option.name}Yes`]?.t || 'Yes'
option.choiceDescriptions.true = eno[`${option.name}Yes`]?.d || 'No'
option.valueTitles.true = 'Yes'
}
}
if (typeof option.menu === 'function')
option.menu = asFullList
? 'conditional'
: option.menu(settings, mergeOptions(settings, options))
if (option.menu) {
// Handle nested groups that don't have any direct children
if (option.menu.includes('.')) {
let menuPath = []
for (const chunk of option.menu.split('.')) {
menuPath.push(chunk)
set(menu, `${menuPath.join('.')}.isGroup`, true)
}
}
set(menu, `${option.menu}.isGroup`, true)
set(menu, `${option.menu}.${option.name}`, option)
} else if (typeof option.menu === 'undefined') {
console.log(
`Warning: Option ${option.name} does not have a menu config. ` +
'Either configure it, or set it to false to hide this option.'
)
}
}
}
// Always put advanced at the end
if (menu.advanced) {
const adv = menu.advanced
delete menu.advanced
menu.advanced = adv
}
return menu
}
/*
* Helper method to grab an option from an Design options structure
*
* Since these structures can be nested with option groups, this needs some extra logic
*/
export function getOptionStructure(option, Design, state) {
const structure = menuDesignOptionsStructure(Design.patternConfig.options, state.settings)
return findOption(structure, option)
}
export function findOption(structure, option) {
for (const [key, val] of Object.entries(structure)) {
if (key === option) return val
if (val.isGroup) {
const sub = findOption(val, option)
if (sub) return sub
}
}
return false
}

View file

@ -0,0 +1,783 @@
// Dependencies
import React from 'react'
import { defaultConfig } from '../config/index.mjs'
import { round, formatMm, randomLoadingMessage } from '@freesewing/utils'
import { formatDesignOptionValue, menuCoreSettingsStructure } from './index.mjs'
import { menuUiPreferencesStructure } from './ui-preferences.mjs'
import { i18n } from '@freesewing/collection'
import { i18n as pluginI18n } from '@freesewing/core-plugins'
import { flags as flagTranslations } from '@freesewing/i18n'
// Components
import {
ErrorIcon,
MeasurementsIcon,
OptionsIcon,
SettingsIcon,
UiIcon,
} from '@freesewing/react/components/Icon'
import { HtmlSpan } from '../components/HtmlSpan.mjs'
/*
* i18n makes everything complicated
*/
const flagTranslationsWithNamespace = {}
for (const [key, val] of Object.entries(flagTranslations || {}))
flagTranslationsWithNamespace[`flag:${key}`] = val
/*
* This method bundles pattern translations in a object we can pass to the Pattern component
*
* @param {string} design - The name of the design
* @return {object} strings - An object of key/value pairs for translation
*/
export const bundlePatternTranslations = (design) => {
const strings = {}
for (const [key, val] of Object.entries(flagTranslationsWithNamespace)) strings[key] = val
if (i18n[design]?.en) {
const en = i18n[design].en
// Parts have no prefix
for (const [key, val] of Object.entries(en.p || {})) strings[key] = val
// Strings do
for (const [key, val] of Object.entries(en.s || {})) strings[`${design}:${key}`] = val
}
for (const [key, val] of Object.entries(pluginI18n.en)) strings[key] = val
return strings
}
/*
* This method drafts the pattern
*
* @param {function} Design - The Design constructor
* @param {object} settings - The settings for the pattern
* @param {array} plugins - Any (extra) plugins to load into the pattern
* @return {object} data - The drafted pattern, along with errors and failure data
*/
export function draft(Design, settings, plugins = []) {
const pattern = new Design(settings)
for (const plugin of plugins) pattern.use(plugin)
const data = {
// The pattern
pattern,
// Any errors logged by the pattern
errors: [],
// If the pattern fails to draft, this will hold the error
failure: false,
}
// Draft the pattern or die trying
try {
data.pattern.draft()
data.errors.push(...data.pattern.store.logs.error)
for (const store of data.pattern.setStores) data.errors.push(...store.logs.error)
} catch (error) {
data.failure = error
}
return data
}
/*
* This method samples a pattern option
*
* @param {function} Design - The Design constructor
* @param {object} settings - The settings for the pattern
* @param {array} plugins - Any (extra) plugins to load into the pattern
* @return {object} data - The drafted pattern, along with errors and failure data
*/
export function sample(Design, settings, plugins = []) {
const pattern = new Design(settings)
for (const plugin of plugins) pattern.use(plugin)
const data = {
// The pattern
pattern,
// Any errors logged by the pattern
errors: [],
// If the pattern fails to draft, this will hold the error
failure: false,
}
// Draft the pattern or die trying
try {
data.pattern.sample()
data.errors.push(...data.pattern.store.logs.error)
for (const store of data.pattern.setStores) data.errors.push(...store.logs.error)
} catch (error) {
data.failure = error
}
return data
}
export function flattenFlags(flags) {
const all = {}
for (const type of defaultConfig.flagTypes) {
let i = 0
if (flags[type]) {
for (const flag of Object.values(flags[type])) {
i++
all[`${type}-${i}`] = { ...flag, type }
}
}
}
return all
}
export function getUiPreferenceUndoStepData({ step }) {
/*
* We'll need these
*/
const field = step.name === 'ui' ? step.path[1] : step.path[2]
const structure = menuUiPreferencesStructure()[field]
if (!structure) return false
/*
* This we'll end up returning
*/
const data = {
icon: <UiIcon />,
field,
title: structure.title,
menu: 'UI Preferences',
structure: menuUiPreferencesStructure()[field],
}
const FieldIcon = data.structure.icon
data.fieldIcon = <FieldIcon />
/*
* Add oldval and newVal if they exist, or fall back to default
*/
for (const key of ['old', 'new'])
data[key + 'Val'] = t(
structure.choiceTitles[
structure.choiceTitles[String(step[key])] ? String(step[key]) : String(structure.dflt)
]
)
return data
}
export function getCoreSettingUndoStepData({ step, state, Design }) {
const field = step.path[1]
const structure = menuCoreSettingsStructure({
language: state.language,
units: state.settings.units,
sabool: state.settings.sabool,
parts: Design.patternConfig.draftOrder,
})
const data = {
field,
menu: 'Core Settings',
title: structure?.[field] ? structure[field].title : '',
icon: <SettingsIcon />,
structure: structure[field],
}
if (!data.structure && field === 'sa') data.structure = structure.samm
const FieldIcon = data.structure?.icon || ErrorIcon
data.fieldIcon = <FieldIcon />
/*
* Save us some typing
*/
const cord = settingsValueCustomOrDefault
const Html = HtmlSpan
/*
* Need to allow HTML in some of these in case this is
* formated as imperial which uses <sub> and <sup>
*/
switch (data.field) {
case 'margin':
case 'sa':
case 'samm':
if (data.field !== 'margin') data.title = 'Seam Allowance'
data.oldVal = <Html html={formatMm(cord(step.old, data.structure.dflt))} />
data.newVal = <Html html={formatMm(cord(step.new, data.structure.dflt))} />
return data
case 'scale':
data.oldVal = cord(step.old, data.structure.dflt)
data.newVal = cord(step.new, data.structure.dflt)
return data
case 'units':
data.oldVal = t(step.new === 'imperial' ? 'Metric Units' : 'Imperial Units')
data.newVal = t(step.new === 'imperial' ? 'Imperial Units' : 'Metric Units')
return data
case 'only':
data.oldVal = cord(step.old, data.structure.dflt) || 'Include all parts'
data.newVal = cord(step.new, data.structure.dflt) || 'Include all parts'
return data
default:
data.oldVal = t(
data.structure.choiceTitles[String(step.old)]
? data.structure.choiceTitles[String(step.old)]
: data.structure.choiceTitles[String(data.structure.dflt)]
)
data.newVal = t(
data.structure.choiceTitles[String(step.new)]
? data.structure.choiceTitles[String(step.new)]
: data.structure.choiceTitles[String(data.structure.dflt)]
)
return data
}
}
export function getDesignOptionUndoStepData({ step, state, Design }) {
const option = Design.patternConfig.options[step.path[2]]
const data = {
icon: <OptionsIcon />,
field: step.path[2],
title: `${state.design}:${step.path[2]}`,
menu: `Design Options`,
oldVal: formatDesignOptionValue(option, step.old, state.units === 'imperial'),
newVal: formatDesignOptionValue(option, step.new, state.units === 'imperial'),
}
return data
}
export function getUndoStepData(props) {
/*
* UI Preferences
*/
if ((props.step.name === 'settings' && props.step.path[1] === 'ui') || props.step.name === 'ui')
return getUiPreferenceUndoStepData(props)
/*
* Design options
*/
if (props.step.name === 'settings' && props.step.path[1] === 'options')
return getDesignOptionUndoStepData(props)
/*
* Core Settings
*/
if (
props.step.name === 'settings' &&
[
'sa',
'samm',
'margin',
'scale',
'only',
'complete',
'paperless',
'sabool',
'units',
'expand',
].includes(props.step.path[1])
)
return getCoreSettingUndoStepData(props)
/*
* Measurements
*/
if (props.step.name === 'settings' && props.step.path[1] === 'measurements') {
const data = {
icon: <MeasurementsIcon />,
field: 'measurements',
title: `measurements`,
menu: 'measurements',
}
/*
* Single measurements change?
*/
if (props.step.path[2])
return {
...data,
field: props.step.path[2],
oldVal: formatMm(props.step.old, props.imperial),
newVal: formatMm(props.step.new, props.imperial),
}
let count = 0
for (const m of Object.keys(props.step.new)) {
if (props.step.new[m] !== props.step.old?.[m]) count++
}
return { ...data, msg: `${count} measurements updated` }
}
/*
* Bail out of the step fell throug
*/
return false
}
/*
* This helper method constructs the initial state object.
*
* If they are not present, it will fall back to the relevant defaults
*/
export function initialEditorState(preload = {}, config) {
/*
* Create initial state object
*/
const initial = { ...config.initialState, ...preload }
/*
* FIXME: Add preload support, from URL or other sources, rather than just passing in an object
*/
return initial
}
/**
* round a value to the correct number of decimal places to display all supplied digits after multiplication
* this is a workaround for floating point errors
* examples:
* roundPct(0.72, 100) === 72
* roundPct(7.5, 0.01) === 0.075
* roundPct(7.50, 0.01) === 0.0750
* @param {Number} num the number to be operated on
* @param {Number} factor the number to multiply by
* @return {Number} the given num multiplied by the factor, rounded appropriately
*/
export function menuRoundPct(num, factor) {
// stringify
const str = '' + num
// get the index of the decimal point in the number
const decimalIndex = str.indexOf('.')
// get the number of places the factor moves the decimal point
const factorPlaces = factor > 0 ? Math.ceil(Math.log10(factor)) : Math.floor(Math.log10(factor))
// the number of places needed is the number of digits that exist after the decimal minus the number of places the decimal point is being moved
const numPlaces = Math.max(0, str.length - (decimalIndex + factorPlaces))
return round(num * factor, numPlaces)
}
const menuNumericInputMatcher = /^-?[0-9]*[.,eE]?[0-9]+$/ // match a single decimal separator
const menuFractionInputMatcher = /^-?[0-9]*(\s?[0-9]+\/|[.,eE])?[0-9]+$/ // match a single decimal separator or fraction
/**
* Validate and parse a value that should be a number
* @param {any} val the value to validate
* @param {Boolean} allowFractions should fractions be considered valid input?
* @param {Number} min the minimum allowable value
* @param {Number} max the maximum allowable value
* @return {null|false|Number} null if the value is empty,
* false if the value is invalid,
* or the value parsed to a number if it is valid
*/
export function menuValidateNumericValue(
val,
allowFractions = true,
min = -Infinity,
max = Infinity
) {
// if it's empty, we're neutral
if (typeof val === 'undefined' || val === '') return null
// make sure it's a string
val = ('' + val).trim()
// get the appropriate match pattern and check for a match
const matchPattern = allowFractions ? menuFractionInputMatcher : menuNumericInputMatcher
if (!val.match(matchPattern)) return false
// replace comma with period
const parsedVal = val.replace(',', '.')
// if fractions are allowed, parse for fractions, otherwise use the number as a value
const useVal = allowFractions ? fractionToDecimal(parsedVal) : parsedVal
// check that it's a number and it's in the range
if (isNaN(useVal) || useVal > max || useVal < min) return false
// all checks passed. return the parsed value
return useVal
}
/**
* Check to see if a value is different from its default
* @param {Number|String|Boolean} current the current value
* @param {Object} config configuration containing a dflt key
* @return {Boolean} was the value changed?
*/
export function menuValueWasChanged(current, config) {
if (typeof current === 'undefined') return false
if (current == config.dflt) return false
return true
}
import get from 'lodash.get'
import set from 'lodash.set'
import unset from 'lodash.unset'
const UNSET = '__UNSET__'
/*
* Helper method to handle object updates
*
* @param {object} obj - The object to update
* @param {string|array} path - The path to the key to update, either as array or dot notation
* @param {mixed} val - The new value to set or 'unset' to unset the value
* @return {object} result - The updated object
*/
export function objUpdate(obj = {}, path, val = '__UNSET__') {
if (val === UNSET) unset(obj, path)
else set(obj, path, val)
return obj
}
/*
* Helper method to handle object updates that also updates the undo history in ephemeral state
*
* @param {object} obj - The object to update
* @param {string|array} path - The path to the key to update, either as array or dot notation
* @param {mixed} val - The new value to set or 'unset' to unset the value
* @param {function} setEphemeralState - The ephemeral state setter
* @return {object} result - The updated object
*/
export function undoableObjUpdate(name, obj = {}, path, val = '__UNSET__', setEphemeralState) {
const current = get(obj, path)
setEphemeralState((cur) => {
if (!Array.isArray(cur.undos)) cur.undos = []
return {
...cur,
undos: [
{
name,
time: Date.now(),
path,
old: current,
new: val,
restore: cloneObject(obj),
},
...cur.undos,
],
}
})
return objUpdate(obj, path, val)
}
/*
* Helper method to strip a namespace: prefix from a string
*
* @param {string} key
* @return {string} keyWithoutNamespace
*/
export function stripNamespace(key) {
const pos = `${key}`.indexOf(':')
return pos === -1 ? key : key.slice(pos + 1)
}
/*
* Helper method to add an undo step for which state updates are handles in another way
*
* This is typically used for SA changes as it requires changing 3 fields:
* - sabool: Is sa on or off?
* - sa: sa value for core
* - samm: Holds the sa value in mm even when sa is off
*
* @param {object} undo - The undo step to add
* @param {object} restore - The state to restore for this step
* @param {function} setEphemeralState - The ephemeral state setter
*/
export function addUndoStep(undo, restore, setEphemeralState) {
setEphemeralState((cur) => {
if (!Array.isArray(cur.undos)) cur.undos = []
return {
...cur,
undos: [{ time: Date.now(), ...undo, restore: cloneObject(restore) }, ...cur.undos],
}
})
}
/*
* Helper method to clone an object
*/
export function cloneObject(obj) {
return JSON.parse(JSON.stringify(obj))
}
/**
* Helper method to push a prefix to a set path
*
* By 'set path' we mean a path to be passed to the
* objUpdate method, which uses lodash's set under the hood.
*
* @param {string} prefix - The prefix path to add
* @param {string|array} path - The path to prefix either as array or a string in dot notation
* @return {array} newPath - The prefixed path
*/
export function statePrefixPath(prefix, path) {
if (Array.isArray(path)) return [prefix, ...path]
else return [prefix, ...path.split('.')]
}
/*
* This creates the helper object for state updates
*/
export function stateUpdateFactory(setState, setEphemeralState, config) {
return {
/*
* This allows raw access to the entire state object
*/
state: (path, val) => setState((cur) => objUpdate({ ...cur }, path, val)),
/*
* These hold an object, so we take a path
*/
settings: (path = null, val = null) => {
/*
* This check can be removed once all code is migrated to the new editor
*/
if (Array.isArray(path) && Array.isArray(path[0]) && val === null) {
throw new Error(
'Update.settings was called with an array of operations. This is no longer supported.'
)
}
return setState((cur) =>
undoableObjUpdate(
'settings',
{ ...cur },
statePrefixPath('settings', path),
val,
setEphemeralState
)
)
},
/*
* Helper to restore from undo state
* Takes the index of the undo step in the array in ephemeral state
*/
restore: async (i, ephemeralState) => {
setState(ephemeralState.undos[i].restore)
setEphemeralState((cur) => {
cur.undos = cur.undos.slice(i + 1)
return cur
})
},
/*
* Helper to toggle SA on or off as that requires managing sa, samm, and sabool
*/
toggleSa: () =>
setState((cur) => {
const sa = cur.settings?.samm || (cur.settings?.units === 'imperial' ? 15.3125 : 10)
const restore = cloneObject(cur)
// This requires 3 changes
const update = cur.settings.sabool
? [
['sabool', 0],
['sa', 0],
['samm', sa],
]
: [
['sabool', 1],
['sa', sa],
['samm', sa],
]
for (const [key, val] of update) objUpdate(cur, `settings.${key}`, val)
// Which we'll group as 1 undo action
addUndoStep(
{
name: 'settings',
path: ['settings', 'sa'],
new: cur.settings.sabool ? 0 : sa,
old: cur.settings.sabool ? sa : 0,
},
restore,
setEphemeralState
)
return cur
}),
ui: (path, val) =>
setState((cur) =>
undoableObjUpdate('ui', { ...cur }, statePrefixPath('ui', path), val, setEphemeralState)
),
/*
* These only hold a string, so we only take a value
*/
design: (val) => setState((cur) => objUpdate({ ...cur }, 'design', val)),
view: (val) => {
// Only take valid view names
if (!config.views.includes(val)) return console.log('not a valid view:', val)
setState((cur) => ({ ...cur, view: val }))
// Also add it onto the views (history)
setEphemeralState((cur) => {
if (!Array.isArray(cur.views)) cur.views = []
return { ...cur, views: [val, ...cur.views] }
})
},
viewBack: () => {
setEphemeralState((eph) => {
if (Array.isArray(eph.views) && config.views.includes(eph.views[1])) {
// Load view at the 1 position of the history
setState((cur) => ({ ...cur, view: eph.views[1] }))
return { ...eph, views: eph.views.slice(1) }
}
return eph
})
},
// Pattern ID (pid)
pid: (val) => setState((cur) => ({ ...cur, pid: val })),
ux: (val) => setState((cur) => objUpdate({ ...cur }, 'ux', val)),
clearPattern: () =>
setState((cur) => {
const newState = { ...cur }
objUpdate(newState, 'settings', {
measurements: cur.settings.measurements,
})
/*
* Let's also reset the renderer to React as that feels a bit like a pattern setting even though it's UI
*/
objUpdate(newState, 'ui', { ...newState.ui, renderer: 'react' })
return newState
}),
clearAll: () => setState(config.initialState),
/*
* These are setters for the ephemeral state which is passed down as part of the
* state object, but is not managed in the state backend because it's ephemeral
*/
startLoading: (id, conf = {}) =>
setEphemeralState((cur) => {
const newState = { ...cur }
if (typeof newState.loading !== 'object') newState.loading = {}
if (typeof conf.color === 'undefined') conf.color = 'info'
newState.loading[id] = {
msg: randomLoadingMessage(),
icon: 'spinner',
...conf,
}
return newState
}),
stopLoading: (id) =>
setEphemeralState((cur) => {
const newState = { ...cur }
if (typeof newState.loading[id] !== 'undefined') delete newState.loading[id]
return newState
}),
clearLoading: () => setEphemeralState((cur) => ({ ...cur, loading: {} })),
notify: (conf, id = false) =>
setEphemeralState((cur) => {
const newState = { ...cur }
/*
* Passing in an id allows making sure the same notification is not repeated
* So if the id is set, and we have a loading state with that id, we just return
*/
if (id && cur.loading?.[id]) return newState
if (typeof newState.loading !== 'object') newState.loading = {}
if (id === false) id = Date.now()
newState.loading[id] = { ...conf, id, fadeTimer: config.notifyTimeout }
return newState
}),
notifySuccess: (msg, id = false) =>
setEphemeralState((cur) => {
const newState = { ...cur }
/*
* Passing in an id allows making sure the same notification is not repeated
* So if the id is set, and we have a loading state with that id, we just return
*/
if (id && cur.loading?.[id]) return newState
if (typeof newState.loading !== 'object') newState.loading = {}
if (id === false) id = Date.now()
newState.loading[id] = {
msg,
icon: 'success',
color: 'success',
id,
fadeTimer: config.notifyTimeout,
}
return newState
}),
notifyFailure: (msg, id = false) =>
setEphemeralState((cur) => {
const newState = { ...cur }
/*
* Passing in an id allows making sure the same notification is not repeated
* So if the id is set, and we have a loading state with that id, we just return
*/
if (id && cur.loading?.[id]) return newState
if (typeof newState.loading !== 'object') newState.loading = {}
if (id === false) id = Date.now()
newState.loading[id] = {
msg,
icon: 'failure',
color: 'error',
id,
fadeTimer: config.notifyTimeout,
}
return newState
}),
fadeNotify: (id) =>
setEphemeralState((cur) => {
const newState = { ...cur }
newState.loading[id] = { ...newState.loading[id], clearTimer: 600, id, fading: true }
delete newState.loading[id].fadeTimer
return newState
}),
clearNotify: (id) =>
setEphemeralState((cur) => {
const newState = { ...cur }
if (typeof newState.loading[id] !== 'undefined') delete newState.loading[id]
return newState
}),
}
}
/*
* Returns the URL of a cloud-hosted image (cloudflare in this case) based on the ID and Variant
*/
export function cloudImageUrl({ id = 'default-avatar', variant = 'public' }) {
/*
* Return something default so that people will actually change it
*/
if (!id || id === 'default-avatar') return config.cloudImageDflt
/*
* If the variant is invalid, set it to the smallest thumbnail so
* people don't load enourmous images by accident
*/
if (!config.cloudImageVariants.includes(variant)) variant = 'sq100'
return `${config.cloudImageUrl}${id}/${variant}`
}
/**
* This method does nothing. It is used to disable certain methods
* that need to be passed it to work
*
* @return {null} null - null
*/
export function noop() {
return null
}
/*
* A method that check that a value is not empty
*/
export function notEmpty(value) {
return String(value).length > 0
}
/**
* Helper method to merge arrays of translation namespaces
*
* Note that this method is variadic
*
* @param {[string]} namespaces - A string or array of strings of namespaces
* @return {[string]} namespaces - A merged array of all namespaces
*/
export function nsMerge(...args) {
const ns = new Set()
for (const arg of args) {
if (typeof arg === 'string') ns.add(arg)
else if (Array.isArray(arg)) {
for (const el of nsMerge(...arg)) ns.add(el)
}
}
return [...ns]
}
/*
* A translation fallback method in case none is passed in
*
* @param {string} key - The input
* @return {string} key - The input is returned
*/
export function t(key) {
return Array.isArray(key) ? key[0] : key
}
export function settingsValueIsCustom(val, dflt) {
return typeof val === 'undefined' || val === '__UNSET__' || val === dflt ? false : true
}
export function settingsValueCustomOrDefault(val, dflt) {
return typeof val === 'undefined' || val === '__UNSET__' || val === dflt ? dflt : val
}

View file

@ -0,0 +1,55 @@
/**
* A web worker to handle the business of exporting pattern files
* */
import yaml from 'js-yaml'
import { PdfMaker } from './pdf-maker.mjs'
import { SinglePdfMaker } from './single-pdf-maker.mjs'
/** when the worker receives data from the page, do the appropriate export */
addEventListener('message', async (e) => {
const { format, settings, svg } = e.data
// handle export by type
try {
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()
}
})
/** post a blob from a successful export */
const postSuccess = (blob) => {
postMessage({ success: true, blob })
close()
}
/** export a blob */
const exportBlob = (blobContent, type) => {
const blob = new Blob([blobContent], {
type: `${type};charset=utf-8`,
})
postSuccess(blob)
}
const exportJson = (settings) => exportBlob(JSON.stringify(settings, null, 2), 'application/json')
const exportYaml = (settings) => exportBlob(yaml.dump(settings), 'application/x-yaml')
const exportSvg = (svg) => exportBlob(svg, 'image/svg+xml')
const exportPdf = async (data) => {
const maker = data.format === 'pdf' ? new SinglePdfMaker(data) : new PdfMaker(data)
await maker.makePdf()
postSuccess(await maker.toBlob())
}

View file

@ -0,0 +1,203 @@
import Worker from 'web-worker'
import fileSaver from 'file-saver'
import { themePlugin } from '@freesewing/plugin-theme'
import { pluginI18n } from '@freesewing/plugin-i18n'
import { tilerPlugin } from './plugin-tiler.mjs'
import { capitalize, formatMm, get } from '@freesewing/utils'
import mustache from 'mustache'
import he from 'he'
import yaml from 'js-yaml'
export const exportTypes = {
exportForPrinting: ['a4', 'a3', 'a2', 'a1', 'a0', 'letter', 'legal', 'tabloid'],
exportForEditing: ['svg', 'pdf'],
exportAsData: ['json', 'yaml'],
}
export const defaultPrintSettings = (units) => ({
size: units === 'imperial' ? 'letter' : 'a4',
orientation: 'portrait',
margin: units === 'imperial' ? 12.7 : 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} 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, 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'] })
pattern.use(pluginI18n, (key) => key)
return pattern
}
/**
* Handle exporting the draft or settings
* format: format to export to
* settings: the settings
* Design: the pattern constructor for the design to be exported
* t: a translation function to attach to the draft
* onComplete: business to perform after a successful export
* onError: business to perform on error
* */
export const handleExport = async ({
format,
settings,
Design,
design,
ui,
t,
startLoading,
stopLoading,
stopLoadingFail,
onComplete,
onError,
}) => {
// start the loading indicator
if (typeof startLoading === 'function') startLoading()
// get a worker going
const worker = new Worker(new URL('./export-worker.js', import.meta.url), { type: 'module' })
/*
* Guard against settings being false, which happens for
* fully default designs that do not require measurements
*/
if (settings === false) settings = {}
// listen for the worker's message back
worker.addEventListener('message', (e) => {
// on success
if (e.data.success) {
// save it out
if (e.data.blob) {
const fileType = exportTypes.exportForPrinting.indexOf(format) === -1 ? format : 'pdf'
fileSaver.saveAs(e.data.blob, `freesewing-${design || 'pattern'}.${fileType}`)
}
// do additional business
onComplete && onComplete(e)
// stop the loader
if (typeof stopLoading === 'function') stopLoading()
}
// on error
else {
console.log(e.data.error)
onError && onError(e)
// stop the loader
if (typeof stopLoadingFail === 'function') stopLoadingFail()
}
})
// pdf settings
const pageSettings = {
...defaultPrintSettings(settings.units),
...get(ui, 'layout', {}),
}
// arguments to pass to the worker
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) {
settings.embed = false
// make a pattern instance for export rendering
const layout = settings.layout || ui.layouts?.print || true
let pattern = themedPattern(Design, settings, { layout }, format, t)
// a specified size should override the settings one
pageSettings.size = format
try {
// add pages to pdf exports
if (!exportTypes.exportForEditing.includes(format)) {
pattern.use(
tilerPlugin({
...pageSettings,
printStyle: true,
renderBlanks: false,
setPatternSize: true,
})
)
}
// add the strings that are used on the cover page
workerArgs.strings = {
design: capitalize(design),
tagline: 'Come for the sewing pattern. Stay for the community.',
url: window.location.href,
cuttingLayout: 'Cutting layout',
}
// Initialize the pattern stores
pattern.getConfig()
// Save the measurement set name to pattern stores
if (settings?.metadata?.setName) {
pattern.store.set('data.setName', settings.metadata.setName)
for (const store of pattern.setStores) store.set('data.setName', settings.metadata.setName)
}
// draft and render the pattern
pattern.draft()
workerArgs.svg = pattern.render()
// Get coversheet info: setName, settings YAML, version, notes, warnings
const store = pattern.setStores[pattern.activeSet]
workerArgs.strings.setName = settings?.metadata?.setName
? settings.metadata.setName
: 'ephemeral'
workerArgs.strings.yaml = yaml.dump(settings)
workerArgs.strings.version = store?.data?.version ? store.data.version : ''
const notes = store?.plugins?.['plugin-annotations']?.flags?.note
? store?.plugins?.['plugin-annotations']?.flags?.note
: []
const warns = store?.plugins?.['plugin-annotations']?.flags?.warn
? store?.plugins?.['plugin-annotations']?.flags?.warn
: []
workerArgs.strings.notes = flagsToString(notes, mustache, t)
workerArgs.strings.warns = flagsToString(warns, mustache, t)
if (format === 'pdf') pageSettings.size = [pattern.width, pattern.height]
// add the svg and pages data to the worker args
workerArgs.pages = pattern.setStores[pattern.activeSet].get('pages')
} catch (err) {
console.log(err)
onError && onError(err)
}
}
// post a message to the worker with all needed data
worker.postMessage(workerArgs)
}
/**
* Convert pattern flags to a formatted string for printing
*/
const flagsToString = (flags, mustache, t) => {
let first = true
let string = ''
for (const flag of Object.values(flags)) {
let title = flag.replace ? mustache.render(flag.title, flag.replace) : flag.title
title = he.decode(title)
let desc = flag.replace ? mustache.render(flag.desc, flag.replace) : flag.desc
desc = desc.replaceAll('\n\n', '\n')
desc = desc.replaceAll('\n', ' ')
desc = he.decode(desc)
if (!first) string += '\n'
first = false
string += '- ' + title + ': ' + desc
}
return string
}

View file

@ -0,0 +1,262 @@
// __SDEFILE__ - This file is a dependency for the stand-alone environment
import { Pdf, mmToPoints } from './pdf.mjs'
import SVGtoPDF from 'svg-to-pdfkit'
import { logoPath } from '@freesewing/config'
/** an svg of the logo to put on the cover page */
const logoSvg = `<svg viewBox="0 0 25 25">
<style> path {fill: none; stroke: #555555; stroke-width: 0.25} </style>
<path d="${logoPath}" />
</svg>`
const lineStart = 50
/**
* Freesewing's first explicit class?
* handles pdf exporting
*/
export class PdfMaker {
/** the svg as text to embed in the pdf */
svg
/** the document configuration */
pageSettings
/** the pdfKit instance that is writing the document */
pdf
/** the export buffer to hold pdfKit output */
buffers
/** translated strings to add to the cover page */
strings
/** cutting layout svgs and strings */
cutLayouts
/** the usable width (excluding margin) of the pdf page, in points */
pageWidth
/** the usable height (excluding margin) of the pdf page, in points */
pageHeight
/** the page margin, in points */
margin
/** the number of columns of pages in the svg */
columns
/** the number of rows of pages in the svg */
rows
/** the width of the entire svg, in points */
svgWidth
/** the height of the entire svg, in points */
svgHeight
pageCount = 0
lineLevel = 50
constructor({ svg, pageSettings, pages, strings, cutLayouts }) {
this.pageSettings = pageSettings
this.pagesWithContent = pages.withContent
this.svg = svg
this.strings = strings
this.cutLayouts = cutLayouts
this.pdf = Pdf({
size: this.pageSettings.size.toUpperCase(),
layout: this.pageSettings.orientation,
})
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
// get the pages data
this.columns = pages.cols
this.rows = pages.rows
// calculate the width of the svg in points
this.svgWidth = this.columns * this.pageWidth
this.svgHeight = this.rows * this.pageHeight
}
/** make the pdf */
async makePdf() {
await this.generateCoverPage()
await this.generateCutLayoutPages()
await this.generatePages()
}
/** convert the pdf to a blob */
async toBlob() {
return this.pdf.toBlob()
}
/** generate the cover page for the pdf */
async generateCoverPage() {
// don't make one if it's not requested
if (!this.pageSettings.coverPage) {
return
}
this.nextPage()
await this.generateCoverPageTitle()
await this.generateSvgPage(this.svg)
}
/** generate a page that has an svg centered in it below any text */
async generateSvgPage(svg) {
//abitrary margin for visual space
let coverMargin = 85
let coverHeight = this.pdf.page.height - coverMargin * 2 - this.lineLevel
let coverWidth = this.pdf.page.width - coverMargin * 2
// add the entire pdf to the page, so that it fills the available space as best it can
await SVGtoPDF(this.pdf, svg, coverMargin, this.lineLevel + coverMargin, {
width: coverWidth,
height: coverHeight,
assumePt: false,
// use aspect ratio to center it
preserveAspectRatio: 'xMidYMid meet',
})
// increment page count
this.pageCount++
}
/** generate the title for the cover page */
async generateCoverPageTitle() {
// FreeSewing tag
this.addText('FreeSewing', 20).addText(this.strings.tagline, 10, 4)
// Design name, version, and Measurement Set
this.addText(this.strings.design, 32)
let savedLineLevel = this.lineLevel - 27
let savedWidth = this.pdf.widthOfString(this.strings.design) + 50
const versionSetString = ' v' + this.strings.version + ' ( ' + this.strings.setName + ' )'
this.pdf.fontSize(18)
this.pdf.text(versionSetString, savedWidth, savedLineLevel)
// Date and timestamp
const currentDateTime = new Date().toLocaleString('en', {
weekday: 'long',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
timeZoneName: 'short',
})
this.addText(currentDateTime, 10)
// Settings YAML
this.addText('Settings: ', 10)
savedLineLevel = this.lineLevel - 9
savedWidth = this.pdf.widthOfString('Settings: ') + 50
this.pdf.fontSize(6)
this.pdf.text('(Measurement values are in mm.)', savedWidth, savedLineLevel)
this.addText(this.strings.yaml, 8)
// Notes and Warnings
if (this.strings.notes) {
this.addText('Notes:', 10).addText(this.strings.notes, 8)
}
if (this.strings.warns) {
this.addText('Warnings:', 10).addText(this.strings.warns, 8)
}
await SVGtoPDF(this.pdf, logoSvg, this.pdf.page.width - lineStart - 50, lineStart, {
width: 50,
height: this.lineLevel - lineStart,
preserveAspectRatio: 'xMaxYMin meet',
})
this.pdf.lineWidth(1)
this.pdf
.moveTo(lineStart, this.lineLevel)
.lineTo(this.pdf.page.width - lineStart, this.lineLevel)
.stroke()
this.lineLevel += 8
this.pdf.fillColor('#888888')
/*
* Don't print URL on pattern. See #5526
*/
//this.addText(this.strings.url, 10)
}
/** generate the title for a cutting layout page */
async generateCutLayoutTitle(materialTitle, materialDimensions) {
this.addText(this.strings.cuttingLayout, 12, 2).addText(materialTitle, 28)
this.pdf.lineWidth(1)
this.pdf
.moveTo(lineStart, this.lineLevel)
.lineTo(this.pdf.page.width - lineStart, this.lineLevel)
.stroke()
this.lineLevel += 5
this.addText(materialDimensions, 16)
}
/** generate all cutting layout pages */
async generateCutLayoutPages() {
if (!this.pageSettings.cutlist || !this.cutLayouts) return
for (const material in this.cutLayouts) {
this.nextPage()
const { title, dimensions, svg } = this.cutLayouts[material]
await this.generateCutLayoutTitle(title, dimensions)
await this.generateSvgPage(svg)
}
}
/** generate the pages of the pdf */
async generatePages() {
// pass the same options to the svg converter for each page
const options = {
assumePt: true,
width: this.svgWidth,
height: this.svgHeight,
preserveAspectRatio: 'xMinYMin slice',
}
// everything is offset by a margin so that it's centered on the page
const startMargin = this.margin
for (var h = 0; h < this.rows; h++) {
for (var w = 0; w < this.columns; w++) {
// skip empty pages
if (!this.pagesWithContent[h][w]) continue
// position it
let x = -w * this.pageWidth + startMargin
let y = -h * this.pageHeight + startMargin
this.nextPage()
// add the pdf to the page, offset by the page distances
await SVGtoPDF(this.pdf, this.svg, x, y, options)
this.pageCount++
}
}
}
/** Reset to a clean page */
nextPage() {
// set the line level back to the top
this.lineLevel = lineStart
// if no pages have been made, we can use the current
if (this.pageCount === 0) return
// otherwise make a new page
this.pdf.addPage()
}
/**
* Add Text to the page at the current line level
* @param {String} text the text to add
* @param {Number} fontSize the size for the text
* @param {Number} marginBottom additional margin to add below the text
*/
addText(text, fontSize, marginBottom = 0) {
this.pdf.fontSize(fontSize)
this.pdf.text(text, 50, this.lineLevel)
this.lineLevel += this.pdf.heightOfString(text) + marginBottom
return this
}
}

View file

@ -0,0 +1,59 @@
import PDFDocument from 'pdfkit/js/pdfkit.standalone.js'
/**
* PdfKit, the library we're using for pdf generation, uses points as a unit,
* so when we tell it things like where to put the svg and how big the svg is,
* we need those numbers to be in points. The svg uses mm internally, so when
* we do spatial reasoning inside the svg, we need to know values in mm
* */
export const mmToPoints = 2.834645669291339
/**
* A PDFKit PDF instance
*/
export const Pdf = ({ size, layout }) => {
const pdf = new PDFDocument({
size,
layout,
})
/*
* PdfKit wants to flush the buffer on each new page.
* We can't save directly from inside a worker, so we have to manage the
* buffers ourselves so we can return a blob
*/
const buffers = []
/*
* Use a listener to add new data to our buffer storage
*/
pdf.on('data', buffers.push.bind(buffers))
/*
* Convert the pdf to a blob
*/
pdf.toBlob = function () {
return new Promise((resolve) => {
/*
* We have to do it this way so that the document flushes everything to buffers
*/
pdf.on('end', () => {
/*
* Convert buffers to a blob
*/
resolve(
new Blob(buffers, {
type: 'application/pdf',
})
)
})
/*
* End the stream
*/
pdf.end()
})
}
return pdf
}

View file

@ -0,0 +1,432 @@
const name = 'Tiler Plugin'
const version = '1.0.0'
export const sizes = {
a4: [210, 297],
a3: [297, 420],
a2: [420, 594],
a1: [594, 841],
a0: [841, 1188],
letter: [215.9, 279.4],
legal: [215.9, 355.6],
tabloid: [279.4, 431.8],
}
/** get a letter to represent an index less than 26*/
const indexLetter = (i) => String.fromCharCode('A'.charCodeAt(0) + i - 1)
/** get a string of letters to represent an index */
const indexStr = (i) => {
let index = i % 26
let quotient = i / 26
let result
if (i <= 26) {
return indexLetter(i)
} //Number is within single digit bounds of our encoding letter alphabet
if (quotient >= 1) {
//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
result = indexStr(quotient)
}
if (index === 0) {
index = 26
} //Accounts for the edge case of the final letter; avoids getting an empty string
return result + indexLetter(index)
}
/**
* A plugin to tile a pattern into printer pages
* */
export const tilerPlugin = ({ size = 'a4', ...settings }) => {
const ls = settings.orientation === 'landscape'
let sheetHeight = sizes[size][ls ? 0 : 1]
let sheetWidth = sizes[size][ls ? 1 : 0]
sheetWidth -= settings.margin * 2
sheetHeight -= settings.margin * 2
return basePlugin({ ...settings, sheetWidth, sheetHeight })
}
export const materialPlugin = (settings) => {
return basePlugin({
...settings,
partName: 'material',
responsiveColumns: false,
})
}
/** check if there is anything to render on the given section of the svg so that we can skip empty pages */
const doScanForBlanks = (stacks, layout, x, y, w, h) => {
let hasContent = false
for (var s in stacks) {
let stack = stacks[s]
// get the position of the part
let stackLayout = layout.stacks[s]
if (!stackLayout) continue
let stackMinX = stackLayout.tl?.x || stackLayout.move.x + stack.topLeft.x
let stackMinY = stackLayout.tl?.y || stackLayout.move.y + stack.topLeft.y
let stackMaxX = stackLayout.br?.x || stackMinX + stack.width
let stackMaxY = stackLayout.br?.y || stackMinY + stack.height
// check if the stack overlaps the page extents
if (
// if the left of the stack is further left than the right end of the page
stackMinX < x + w &&
// and the top of the stack is above the bottom of the page
stackMinY < y + h &&
// and the right of the stack is further right than the left of the page
stackMaxX > x &&
// and the bottom of the stack is below the top to the page
stackMaxY > y
) {
// the stack has content inside the page
hasContent = true
// so we stop looking
break
}
}
return hasContent
}
export function addToOnly(pattern, partName) {
const only = pattern.settings[0].only
if (only && !only.includes(partName)) {
pattern.settings[0].only = [].concat(only, partName)
}
}
function removeFromOnly(pattern, partName) {
const only = pattern.settings[0].only
if (only && only.includes(partName)) {
pattern.settings[0].only.splice(only.indexOf(partName), 1)
}
}
/**
* The base plugin for adding a layout helper part like pages or fabric
* sheetWidth: the width of the helper part
* sheetHeight: the height of the helper part
* boundary: should the helper part calculate its boundary?
* responsiveColumns: should the part make more columns if the pattern exceed its width? (for pages you want this, for fabric you don't)
* printStyle: should the pages be rendered for printing or for screen viewing?
* */
const basePlugin = ({
sheetWidth,
sheetHeight,
// boundary = false,
partName = 'pages',
responsiveColumns = true,
printStyle = false,
scanForBlanks = true,
renderBlanks = true,
setPatternSize = false,
}) => ({
name,
version,
hooks: {
preDraft: function (pattern) {
if (!responsiveColumns) {
pattern.settings[0].maxWidth = sheetWidth
}
addToOnly(pattern, partName)
// Add part
pattern.addPart({
name: partName,
draft: (shorthand) => {
const layoutData = shorthand.store.get('layoutData')
// only actually draft the part if layout data has been set
if (layoutData) {
shorthand.macro('addPages', layoutData, shorthand)
shorthand.part.unhide()
} else {
shorthand.part.hide()
}
return shorthand.part
},
})
},
postLayout: function (pattern) {
let { height, width, stacks } = pattern
if (!responsiveColumns) width = sheetWidth
// get the layout
const layout =
typeof pattern.settings[pattern.activeSet].layout === 'object'
? pattern.settings[pattern.activeSet].layout
: pattern.autoLayout
// if the layout doesn't start at 0,0 we want to account for that in our height and width
if (layout?.topLeft) {
height += layout.topLeft.y
responsiveColumns && (width += layout.topLeft.x)
}
// store the layout data so the part can use it during drafting
pattern.setStores[pattern.activeSet].set('layoutData', {
size: [sheetHeight, sheetWidth],
height,
width,
layout,
stacks,
})
// draft the part
pattern.draftPartForSet(partName, pattern.activeSet)
// if the pattern size is supposed to be re-set to the full width and height of all pages, do that
const generatedPageData = pattern.setStores[pattern.activeSet].get(partName)
if (setPatternSize === true || setPatternSize === 'width')
pattern.width = Math.max(pattern.width, sheetWidth * generatedPageData.cols)
if (setPatternSize === true || setPatternSize === 'height')
pattern.height = Math.max(pattern.height, sheetHeight * generatedPageData.rows)
removeFromOnly(pattern, partName)
},
preRender: function (svg) {
addToOnly(svg.pattern, partName)
},
postRender: function (svg) {
removeFromOnly(svg.pattern, partName)
},
},
macros: {
/** draft the pages */
addPages: function (so, shorthand) {
const [h, w] = so.size
const cols = Math.ceil(so.width / w)
const rows = Math.ceil(so.height / h)
const { points, Point, paths, Path, part, macro, store } = shorthand
let count = 0
let withContent = {}
part.topLeft = so.layout.topLeft
? new Point(so.layout.topLeft.x, so.layout.topLeft.y)
: new Point(0, 0)
// 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(so.stacks, 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)
.setCircle(56, 'stroke-4xl muted fabric')
.attr('data-circle-id', `${pageName}-circle`)
points[`${pageName}-text`] = new Point(x + w / 2, y + h / 2)
.setText(
`${responsiveColumns ? indexStr(col + 1) : ''}${row + 1}`,
'text-4xl center baseline-center bold muted fill-fabric'
)
.attr('data-text-id', `${pageName}-text`)
paths[pageName] = new Path()
.attr('id', pageName)
.move(points[`${pageName}-tl`])
.line(points[`${pageName}-bl`])
.line(points[`${pageName}-br`])
.line(points[`${pageName}-tr`])
.close()
// add an edge warning if it can't expand horizontally
if (!responsiveColumns) {
paths[pageName + '_edge'] = new Path()
.move(points[`${pageName}-tr`])
.line(points[`${pageName}-br`])
// .move(points[`${pageName}-br`].translate(20, 0))
.addClass('help contrast stroke-xl')
shorthand.macro('banner', {
path: paths[pageName + '_edge'],
text: 'plugin:edgeOf' + shorthand.utils.capitalize(partName),
className: 'text-xl center',
spaces: 20,
})
}
if (col === cols - 1 && row === rows - 1) {
const br = points[`${pageName}-br`]
part.width = br.x
part.height = br.y
part.bottomRight = new Point(br.x, br.y)
}
if (!printStyle) {
paths[pageName]
.attr('class', 'fill-fabric')
.attr(
'style',
`stroke-opacity: 0; fillOpacity: ${(col + row) % 2 === 0 ? 0.03 : 0.15};`
)
} else {
paths[pageName].attr('class', 'interfacing stroke-xs')
// add markers and rulers
macro('addPageMarkers', { row, col, pageName, withContent }, shorthand)
macro('addRuler', { xAxis: true, pageName }, shorthand)
macro('addRuler', { xAxis: false, pageName }, shorthand)
}
}
}
// Store page count in part
store.set(partName, { 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
const isMetric = this.context.settings.units === 'metric'
// not so arbitrary number of units for the ruler
const rulerLength = isMetric ? 10 : 2
// distance to the end of the ruler
const endPointDist = [(isMetric ? 10 : 25.4) * rulerLength, 0]
const axisName = xAxis ? 'x' : 'y'
const rulerName = `${pageName}-${axisName}`
// start by making an endpoint for the ruler based on the axis
const endPoint = [endPointDist[xAxis ? 0 : 1], endPointDist[xAxis ? 1 : 0]]
points[`${rulerName}-ruler-end`] = points[`${pageName}-tl`].translate(
endPoint[0],
endPoint[1]
)
// also make a tick for the end of the ruler
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' : '&quot;'))
// 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
paths[`${rulerName}-ruler`] = new Path()
.move(points[`${pageName}-tl`])
// give it an explicit id in case we need to hide it later
.attr('id', `${rulerName}-ruler`)
.attr('class', 'interfacing stroke-xs')
// get the distance between the smaller ticks on the rule
const division = (isMetric ? 0.1 : 0.125) / rulerLength
// Set up intervals for whole and half units.
const wholeInterval = isMetric ? 10 : 8
const halfInterval = isMetric ? 5 : 4
let tickCounter = 1
// we're going to go by fraction, so we want to do this up to 1
for (var d = division; d < 1; d += division) {
// make a start point
points[`${rulerName}-ruler-${d}-end`] = points[`${pageName}-tl`].shiftFractionTowards(
points[`${rulerName}-ruler-end`],
d
)
// base tick size on whether this is a major interval or a minor one
let tick = 1
// if this tick indicates a whole unit, extra long
if (tickCounter % wholeInterval === 0) tick = 3
// if this tick indicates half a unit, long
else if (tickCounter % halfInterval === 0) tick = 2
tickCounter++
// make a point for the end of the tick
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`]
.line(points[`${rulerName}-ruler-end`])
.line(points[`${rulerName}-ruler-tick`])
},
/** add page markers to the given page */
addPageMarkers({ row, col, pageName, withContent }, shorthand) {
const { macro, points } = shorthand
// these markers are placed on the top and left of the page,
// so skip markers for the top row or leftmost column
if (row !== 0 && withContent[row - 1][col])
macro('addPageMarker', {
along: [points[`${pageName}-tr`], points[`${pageName}-tl`]],
label: [`${row}`, `${row + 1}`],
isRow: true,
pageName,
})
if (col !== 0 && withContent[row][col - 1])
macro('addPageMarker', {
along: [points[`${pageName}-tl`], points[`${pageName}-bl`]],
label: [indexStr(col), indexStr(col + 1)],
isRow: false,
pageName,
})
},
/** add a page marker for either the row or the column, to aid with alignment and orientation */
addPageMarker({ along, label, isRow, pageName }) {
const { points, paths, Path, scale } = this.shorthand()
const markerName = `${pageName}-${isRow ? 'row' : 'col'}-marker`
// x and y distances between corners. one will always be 0, which is helpful
const xDist = along[0].dx(along[1])
const yDist = along[0].dy(along[1])
// size of the x mark should be impacted by the scale setting
const markSize = 4 * scale
// make one at 25% and one at 75%
for (var d = 25; d < 100; d += 50) {
// get points to make an x at d% along the edge
const dName = `${markerName}-${d}`
const centerName = `${dName}-center`
points[centerName] = along[0].translate((xDist * d) / 100, (yDist * d) / 100)
points[`${dName}-tr`] = points[centerName].translate(-markSize, markSize)
points[`${dName}-tl`] = points[centerName].translate(-markSize, -markSize)
points[`${dName}-br`] = points[centerName].translate(markSize, markSize)
points[`${dName}-bl`] = points[centerName].translate(markSize, -markSize)
// make a path for the x
paths[`${dName}`] = new Path()
.move(points[`${dName}-tr`])
.line(points[`${dName}-bl`])
.move(points[`${dName}-tl`])
.line(points[`${dName}-br`])
.attr('class', 'interfacing stroke-xs')
// give it an explicit ID in case we need to hide it later
.attr('id', dName)
// add directional labels
let angle = along[0].angle(along[1]) - 90
for (var i = 0; i < 2; i++) {
points[`${dName}-label-${i + 1}`] = points[centerName]
.shift(angle, markSize)
.setText(label[i], 'text-xs center baseline-center fill-interfacing')
// give it an explicit ID in case we need to hide it later
.attr('data-text-id', `${dName}-text-${i + 1}`)
// rotate for the next one
angle += 180
}
}
},
},
})

View file

@ -0,0 +1,24 @@
// __SDEFILE__ - This file is a dependency for the stand-alone environment
import { Pdf, mmToPoints } from './pdf.mjs'
import SVGtoPDF from 'svg-to-pdfkit'
/**
* Basic exporter for a single-page pdf containing the rendered pattern.
* This generates a PDF that is the size of the pattern and has no additional frills*/
export class SinglePdfMaker {
pdf
svg
constructor({ svg, pageSettings }) {
this.pdf = Pdf({ size: pageSettings.size.map((s) => s * mmToPoints) })
this.svg = svg
}
async makePdf() {
await SVGtoPDF(this.pdf, this.svg)
}
async toBlob() {
return this.pdf.toBlob()
}
}

View file

@ -0,0 +1,229 @@
import React from 'react'
import { designOptionType } from '@freesewing/utils'
import { BoolNoIcon, BoolYesIcon } from '@freesewing/react/components/Icon'
/*
* Method that capitalizes a string (make the first character uppercase)
*
* @param {string} string - The input string to capitalize
* @return {string} String - The capitalized input string
*/
export function capitalize(string) {
return typeof string === 'string' ? string.charAt(0).toUpperCase() + string.slice(1) : ''
}
export function formatDesignOptionValue(option, value, imperial) {
const oType = designOptionType(option)
if (oType === 'pct') return formatPercentage(value ? value : option.pct / 100)
if (oType === 'deg') return `${value ? value : option.deg}°`
if (oType === 'bool')
return typeof value === 'undefined' ? option.bool : value ? <BoolYesIcon /> : <BoolNoIcon />
if (oType === 'mm') return formatMm(typeof value === 'undefined' ? option.mm : value, imperial)
if (oType === 'list') return typeof value === 'undefined' ? option.dflt : value
return value
}
/**
* format a value to the nearest fraction with a denominator that is a power of 2
* or a decimal if the value is between fractions
* NOTE: this method does not convert mm to inches. It will turn any given value directly into its equivalent fractional representation
*
* fraction: the value to process
* format: the type of formatting to apply. html, notags, or anything else which will only return numbers
*/
export function formatFraction128(fraction, format = 'html') {
let negative = ''
let inches = ''
let rest = ''
if (fraction < 0) {
fraction = fraction * -1
negative = '-'
}
if (Math.abs(fraction) < 1) rest = fraction
else {
inches = Math.floor(fraction)
rest = fraction - inches
}
let fraction128 = Math.round(rest * 128)
if (fraction128 == 0) return formatImperial(negative, inches || fraction128, false, false, format)
for (let i = 1; i < 7; i++) {
const numoFactor = Math.pow(2, 7 - i)
if (fraction128 % numoFactor === 0)
return formatImperial(negative, inches, fraction128 / numoFactor, Math.pow(2, i), format)
}
return (
negative +
Math.round(fraction * 100) / 100 +
(format === 'html' || format === 'notags' ? '"' : '')
)
}
// Formatting for imperial values
export function formatImperial(neg, inch, numo = false, deno = false, format = 'html') {
if (format === 'html') {
if (numo) return `${neg}${inch}&nbsp;<sup>${numo}</sup>/<sub>${deno}</sub>"`
else return `${neg}${inch}"`
} else if (format === 'notags') {
if (numo) return `${neg}${inch} ${numo}/${deno}"`
else return `${neg}${inch}"`
} else {
if (numo) return `${neg}${inch} ${numo}/${deno}`
else return `${neg}${inch}`
}
}
// Format a value in mm based on the user's units
// Format can be html, notags, or anything else which will only return numbers
export function formatMm(val, units, format = 'html') {
val = roundMm(val)
if (units === 'imperial' || units === true) {
if (val == 0) return formatImperial('', 0, false, false, format)
let fraction = val / 25.4
return formatFraction128(fraction, format)
} else {
if (format === 'html' || format === 'notags') return roundMm(val / 10) + 'cm'
else return roundMm(val / 10)
}
}
// Format a percentage (as in, between 0 and 1)
export function formatPercentage(val) {
return Math.round(1000 * val) / 10 + '%'
}
/**
* A generic rounding method
*
* @param {number} val - The input number to round
* @param {number} decimals - The number of decimal points to use when rounding
* @return {number} result - The rounded number
*/
export function round(methods, val, decimals = 1) {
return Math.round(val * Math.pow(10, decimals)) / Math.pow(10, decimals)
}
// Rounds a value in mm
export function roundMm(val, units) {
if (units === 'imperial') return Math.round(val * 1000000) / 1000000
else return Math.round(val * 10) / 10
}
/**
* Converts a value that contain a fraction to a decimal
*
* @param {number} value - The input value
* @return {number} result - The resulting decimal value
*/
export function fractionToDecimal(value) {
// if it's just a number, return it
if (!isNaN(value)) return value
// keep a running total
let total = 0
// split by spaces
let chunks = String(value).split(' ')
if (chunks.length > 2) return Number.NaN // too many spaces to parse
// a whole number with a fraction
if (chunks.length === 2) {
// shift the whole number from the array
const whole = Number(chunks.shift())
// if it's not a number, return NaN
if (isNaN(whole)) return Number.NaN
// otherwise add it to the total
total += whole
}
// now we have only one chunk to parse
let fraction = chunks[0]
// split it to get numerator and denominator
let fChunks = fraction.trim().split('/')
// not really a fraction. return NaN
if (fChunks.length !== 2 || fChunks[1] === '') return Number.NaN
// do the division
let num = Number(fChunks[0])
let denom = Number(fChunks[1])
if (isNaN(num) || isNaN(denom)) return NaN
return total + num / denom
}
/**
* Helper method to turn a measurement in millimeter regardless of units
*
* @param {number} value - The input value
* @param {string} units - One of 'metric' or 'imperial'
* @return {number} result - Value in millimeter
*/
export function measurementAsMm(value, units = 'metric') {
if (typeof value === 'number') return value * (units === 'imperial' ? 25.4 : 10)
if (String(value).endsWith('.')) return false
if (units === 'metric') {
value = Number(value)
if (isNaN(value)) return false
return value * 10
} else {
const decimal = fractionToDecimal(value)
if (isNaN(decimal)) return false
return decimal * 24.5
}
}
/**
* Converts a millimeter value to a Number value in the given units
*
* @param {number} mmValue - The input value in millimeter
* @param {string} units - One of 'metric' or 'imperial'
* @result {number} result - The result in millimeter
*/
export function measurementAsUnits(mmValue, units = 'metric') {
return round(mmValue / (units === 'imperial' ? 25.4 : 10), 3)
}
export function shortDate(locale = 'en', timestamp = false, withTime = true) {
const options = {
year: 'numeric',
month: 'short',
day: 'numeric',
}
if (withTime) {
options.hour = '2-digit'
options.minute = '2-digit'
options.hour12 = false
}
const ts = timestamp ? new Date(timestamp) : new Date()
return ts.toLocaleDateString(locale, options)
}
/*
* Parses value that should be a distance (cm or inch)
*
* @param {number} val - The input value
* @param {bool} imperial - True if the units are imperial, false for metric
* @return {number} result - The distance in the relevant units
*/
export function parseDistanceInput(val = false, imperial = false) {
// No input is not valid
if (!val) return false
// Cast to string, and replace comma with period
val = val.toString().trim().replace(',', '.')
// Regex pattern for regular numbers with decimal seperator or fractions
const regex = imperial
? /^-?[0-9]*(\s?[0-9]+\/|[.])?[0-9]+$/ // imperial (fractions)
: /^-?[0-9]*[.]?[0-9]+$/ // metric (no fractions)
if (!val.match(regex)) return false
// if fractions are allowed, parse for fractions, otherwise use the number as a value
if (imperial) val = fractionToDecimal(val)
return isNaN(val) ? false : Number(val)
}

View file

@ -0,0 +1,123 @@
/*
* Import of all methods used by the editor
*/
import {
defaultSa,
defaultSamm,
menuCoreSettingsOnlyHandler,
menuCoreSettingsSaboolHandler,
menuCoreSettingsSammHandler,
menuCoreSettingsStructure,
} from './core-settings.mjs'
import { findOption, getOptionStructure, menuDesignOptionsStructure } from './design-options.mjs'
import { menuLayoutSettingsStructure } from './layout-settings.mjs'
import {
addUndoStep,
bundlePatternTranslations,
cloneObject,
cloudImageUrl,
draft,
flattenFlags,
getCoreSettingUndoStepData,
getDesignOptionUndoStepData,
getUiPreferenceUndoStepData,
getUndoStepData,
initialEditorState,
menuRoundPct,
menuValidateNumericValue,
menuValueWasChanged,
noop,
notEmpty,
nsMerge,
objUpdate,
sample,
settingsValueIsCustom,
settingsValueCustomOrDefault,
statePrefixPath,
stateUpdateFactory,
stripNamespace,
t,
undoableObjUpdate,
} from './editor.mjs'
import {
capitalize,
formatDesignOptionValue,
formatFraction128,
formatImperial,
formatMm,
formatPercentage,
round,
roundMm,
fractionToDecimal,
measurementAsMm,
measurementAsUnits,
shortDate,
parseDistanceInput,
} from './formatting.mjs'
import { designMeasurements, missingMeasurements } from './measurements.mjs'
import { menuUiPreferencesStructure } from './ui-preferences.mjs'
/*
* Re-export as named exports
*/
export {
// core-settings.mjs
defaultSa,
defaultSamm,
menuCoreSettingsOnlyHandler,
menuCoreSettingsSaboolHandler,
menuCoreSettingsSammHandler,
menuCoreSettingsStructure,
// design-options.mjs
findOption,
getOptionStructure,
menuDesignOptionsStructure,
// layout-settings.mjs
menuLayoutSettingsStructure,
// editor.mjs
addUndoStep,
bundlePatternTranslations,
cloneObject,
cloudImageUrl,
draft,
flattenFlags,
getCoreSettingUndoStepData,
getDesignOptionUndoStepData,
getUiPreferenceUndoStepData,
getUndoStepData,
initialEditorState,
menuRoundPct,
menuValidateNumericValue,
menuValueWasChanged,
noop,
notEmpty,
nsMerge,
objUpdate,
sample,
settingsValueIsCustom,
settingsValueCustomOrDefault,
statePrefixPath,
stateUpdateFactory,
stripNamespace,
t,
undoableObjUpdate,
// formatting.mjs
capitalize,
formatDesignOptionValue,
formatFraction128,
formatImperial,
formatMm,
formatPercentage,
round,
roundMm,
fractionToDecimal,
measurementAsMm,
measurementAsUnits,
shortDate,
parseDistanceInput,
// measurements.mjs
designMeasurements,
missingMeasurements,
// ui-preferences.mjs
menuUiPreferencesStructure,
}

View file

@ -0,0 +1,116 @@
import React from 'react'
import { linkClasses } from '@freesewing/utils'
import {
CoverPageIcon,
PageMarginIcon,
PageOrientationIcon,
PageSizeIcon,
PatternIcon,
ScaleIcon,
} from '@freesewing/react/components/Icon'
const UiDocsLink = ({ item }) => (
<a href={`/docs/about/site/draft/#${item.toLowerCase()}`} className={`${linkClasses} tw-px-2`}>
Learn more
</a>
)
const sizes = ['a4', 'a3', 'a2', 'a1', 'a0', 'letter', 'legal', 'tabloid']
const defaultPrintSettings = (units) => ({
size: units === 'imperial' ? 'letter' : 'a4',
orientation: 'portrait',
margin: units === 'imperial' ? 12.7 : 10,
coverPage: true,
})
export function menuLayoutSettingsStructure(units) {
const defaults = defaultPrintSettings(units)
const sizeTitles = {
a4: 'A4',
a3: 'A3',
a2: 'A2',
a1: 'A1',
a0: 'A0',
letter: 'Letter',
legal: 'Legal',
tabloid: 'Tabloid',
}
return {
size: {
dense: true,
title: 'Paper Size',
about: (
<span>
This control the pages overlay that helps you see how your pattern spans the pages. This
does not limit your export options, you can still export in a variety of paper sizes.
</span>
),
ux: 1,
list: Object.keys(sizeTitles),
choiceTitles: sizeTitles,
valueTitles: sizeTitles,
dflt: defaults.size,
icon: PageSizeIcon,
},
orientation: {
dense: true,
title: 'Page Orientation',
about: (
<span>Landscape or Portrait. Try both to see which yields the least amount of pages.</span>
),
ux: 1,
list: ['portrait', 'landscape'],
choiceTitles: {
portrait: (
<div className="tw-flex tw-flex-row tw-items-center tw-gap-4">
<PatternIcon className="tw-h-5 tw-w-5" />
<span className="tw-grow">Portrait (tall)</span>
</div>
),
landscape: (
<div className="tw-flex tw-flex-row tw-items-center tw-gap-4">
<PatternIcon className="tw-h-5 tw-w-5 tw--rotate-90" />
<span className="tw-grow">Landscape (wide)</span>
</div>
),
},
icon: PageOrientationIcon,
},
margin: {
dense: true,
title: 'Page Margin',
min: units === 'imperial' ? 2.5 : 5,
max: 25,
dflt: defaults.margin,
icon: PageMarginIcon,
ux: 1,
},
coverPage: {
dense: true,
ux: 1,
icon: CoverPageIcon,
title: 'Cover Page',
about:
'The cover page includes information about the pattern and an overview of how to assemble the pages.',
list: [0, 1],
choiceTitles: {
0: 'Do not include a cover page',
1: 'Include a cover page',
},
dflt: 0,
},
iconSize: {
dense: true,
ux: 1,
icon: ScaleIcon,
title: 'Icon Size',
about:
'Controls the size of the icons that allow you to rotate/flip individual pattern parts',
min: 10,
dflt: 0.5,
step: 1,
max: 200,
},
}
}

View file

@ -0,0 +1,36 @@
// Dependencies
import { defaultConfig } from '../config/index.mjs'
/*
* Returns a list of measurements for a design
*
* @param {object} Design - The Design object
* @param {object} measies - The current set of measurements
* @return {object} measurements - Object holding measurements that are relevant for this design
*/
export function designMeasurements(Design, measies = {}) {
const measurements = {}
for (const m of Design.patternConfig?.measurements || []) measurements[m] = measies[m]
for (const m of Design.patternConfig?.optionalMeasurements || []) measurements[m] = measies[m]
return measurements
}
/*
* Helper method to check whether measurements are missing
*
* Note that this does not actually check the settings against
* the chosen design, but rather relies on the missing measurements
* being set in state. That's because checking is more expensive,
* so we do it only once.
*
* @param {object} state - The Editor state
* @return {bool} missing - True if there are missing measurments, false if not
*/
export function missingMeasurements(state) {
return (
!defaultConfig.measurementsFreeViews.includes(state.view) &&
state._.missingMeasurements &&
state._.missingMeasurements.length > 0
)
}

View file

@ -0,0 +1,119 @@
import React from 'react'
import { defaultConfig } from '../config/index.mjs'
import { linkClasses } from '@freesewing/utils'
import { AsideIcon, RotateIcon, RocketIcon, UxIcon } from '@freesewing/react/components/Icon'
const UiDocsLink = ({ item }) => (
<a href={`/docs/about/site/draft/#${item.toLowerCase()}`} className={`${linkClasses} tw-px-2`}>
Learn more
</a>
)
export function menuUiPreferencesStructure() {
const uiUx = defaultConfig.uxLevels.ui
const uiPreferences = {
aside: {
dense: true,
title: 'Show side menu',
about: (
<span>
Uses the right side of the screen for the Design Options, Core Settings, and UI
Preferences menus.
<UiDocsLink item="aside" />
</span>
),
ux: uiUx.aside,
list: [0, 1],
choiceTitles: {
0: 'Do not show the side menu',
1: 'Show the side menu',
},
dflt: 0,
icon: AsideIcon,
},
ux: {
dense: true,
title: 'User Experience',
about: (
<span>
Controls the user experience, from keep it simple, to give me all the powers.
<UiDocsLink item="control" />
</span>
),
ux: uiUx.ux,
emoji: '🖥️',
list: [1, 2, 3, 4, 5],
choiceTitles: {
1: 'Keep it as simple as possible',
2: 'Keep it simple, but not too simple',
3: 'Balance simplicity with power',
4: 'Give me all powers, but keep me safe',
5: 'Get out of my way',
},
_choiceDescriptions: {
1: 'Hides all but the most crucial features.',
2: 'Hides most of the advanced features.',
3: 'Reveals the majority of advanced features, but not all of them.',
4: 'Reveals all advanced features, keeps handrails and safety checks.',
5: 'Reveals all advanced features, removes handrails and safety checks.',
},
icon: UxIcon,
dflt: defaultConfig.defaultUx,
},
rotate: {
dense: true,
title: 'Rotate Pattern',
about: (
<span>
Allows you to rotate your pattern 90 degrees, handy for tall patterns.
<UiDocsLink item="rotate" />
</span>
),
ux: uiUx.rotate,
list: [0, 1],
choiceTitles: {
0: 'Do not rotate the pattern',
1: 'Rotate the pattern 90 degrees',
},
dflt: 0,
icon: RotateIcon,
},
renderer: {
dense: true,
title: 'Pattern render engine',
about: 'Change the way the pattern is rendered on screen',
about: (
<span>
Change the underlying method for rendering the pattern on screen.
<UiDocsLink item="renderer" />
</span>
),
ux: uiUx.renderer,
list: ['react', 'svg'],
choiceTitles: {
react: (
<span>
Render using <em>@freesewing/react</em>
</span>
),
svg: (
<span>
Render using <em>@freesewing/core</em>
</span>
),
},
choiceDescriptions: {
0: 'pe:noAside',
1: 'pe:withAside',
},
valueTitles: {
react: 'React',
svg: 'Core',
},
dflt: 'react',
icon: RocketIcon,
},
}
return uiPreferences
}