1
0
Fork 0

wip: npm, not yarn

This commit is contained in:
joostdecock 2024-12-10 18:02:38 +01:00
parent 1861d30b30
commit a6b11b5a24
167 changed files with 109 additions and 186 deletions

View file

@ -0,0 +1,149 @@
export function defaultSa(Swizzled, units, inMm = true) {
const dflt = units === 'imperial' ? 0.5 : 1
return inMm ? Swizzled.methods.measurementAsMm(dflt, units) : dflt
}
export function defaultSamm(Swizzled, units, inMm = true) {
const dflt = units === 'imperial' ? 0.5 : 1
return inMm ? Swizzled.methods.measurementAsMm(dflt, units) : dflt
}
/** custom event handlers for inputs that need them */
export function menuCoreSettingsOnlyHandler(Swizzled, { 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(Swizzled, { 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(Swizzled, { toggleSa }) {
return toggleSa
}
export function menuCoreSettingsStructure(
Swizzled,
{ units = 'metric', sabool = false, parts = [] }
) {
return {
sabool: {
ux: Swizzled.config.uxLevels.core.sa,
list: [0, 1],
choiceTitles: {
0: 'saNo',
1: 'saYes',
},
valueTitles: {
0: 'no',
1: 'yes',
},
dflt: 0,
icon: Swizzled.components.SaIcon,
},
samm: sabool
? {
ux: Swizzled.config.uxLevels.core.sa,
min: 0,
max: units === 'imperial' ? 2 : 2.5,
dflt: Swizzled.methods.defaultSamm(units),
icon: Swizzled.components.SaIcon,
}
: false,
paperless: {
ux: Swizzled.config.uxLevels.core.paperless,
list: [0, 1],
choiceTitles: {
0: 'paperlessNo',
1: 'paperlessYes',
},
valueTitles: {
0: 'no',
1: 'yes',
},
dflt: 0,
icon: Swizzled.components.PaperlessIcon,
},
units: {
ux: Swizzled.config.uxLevels.core.units,
list: ['metric', 'imperial'],
dflt: 'metric',
choiceTitles: {
metric: 'metric',
imperial: 'imperial',
},
valueTitles: {
metric: 'metric',
imperial: 'imperial',
},
icon: Swizzled.components.UnitsIcon,
},
complete: {
ux: Swizzled.config.uxLevels.core.complete,
list: [1, 0],
dflt: 1,
choiceTitles: {
0: 'completeNo',
1: 'completeYes',
},
valueTitles: {
0: 'no',
1: 'yes',
},
icon: Swizzled.components.DetailIcon,
},
expand: {
ux: Swizzled.config.uxLevels.core.expand,
list: [1, 0],
dflt: 1,
choiceTitles: {
0: 'expandNo',
1: 'expandYes',
},
valueTitles: {
0: 'no',
1: 'yes',
},
icon: Swizzled.components.ExpandIcon,
},
only: {
ux: Swizzled.config.uxLevels.core.only,
dflt: false,
list: parts,
parts,
icon: Swizzled.components.IncludeIcon,
},
scale: {
ux: Swizzled.config.uxLevels.core.scale,
min: 0.1,
max: 5,
dflt: 1,
step: 0.1,
icon: Swizzled.components.ScaleIcon,
},
margin: {
ux: Swizzled.config.uxLevels.core.margin,
min: 0,
max: 2.5,
dflt: Swizzled.methods.measurementAsMm(units === 'imperial' ? 0.125 : 0.2, units),
icon: Swizzled.components.MarginIcon,
},
}
}

View file

@ -0,0 +1,87 @@
export function designOptionType(Swizzled, option) {
if (typeof option?.pct !== 'undefined') return 'pct'
if (typeof option?.bool !== 'undefined') return 'bool'
if (typeof option?.count !== 'undefined') return 'count'
if (typeof option?.deg !== 'undefined') return 'deg'
if (typeof option?.list !== 'undefined') return 'list'
if (typeof option?.mm !== 'undefined') return 'mm'
return 'constant'
}
import { mergeOptions } from '@freesewing/core'
import set from 'lodash.set'
import orderBy from 'lodash.orderby'
export function menuDesignOptionsStructure(Swizzled, 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 }
}
const menu = {}
// Fixme: One day we should sort this based on the translation
for (const option of orderBy(sorted, ['order', 'menu', 'name'], ['asc', 'asc', 'asc'])) {
if (typeof option === 'object') {
const oType = Swizzled.methods.designOptionType(option)
option.dflt = option.dflt || option[oType]
if (oType === 'pct') option.dflt /= 100
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(Swizzled, option, Design, state) {
const structure = Swizzled.methods.menuDesignOptionsStructure(
Design.patternConfig.options,
state.settings
)
console.log({ structure })
return Swizzled.methods.findOption(structure, option)
}
export function findOption(Swizzled, 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,720 @@
/*
* This method drafts the pattern
*
* @param {object} Swizzled - Swizzled code, not used here
* @param {function} Design - The Design constructor
* @param {object} settings - The settings for the pattern
* @return {object} data - The drafted pattern, along with errors and failure data
*/
export function draft(Swizzled, Design, settings) {
const data = {
// The pattern
pattern: new Design(settings),
// 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
}
export function flattenFlags(Swizzled, flags) {
const all = {}
for (const type of Swizzled.config.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(Swizzled, { step }) {
/*
* We'll need these
*/
const field = step.name === 'ui' ? step.path[1] : step.path[2]
const structure = Swizzled.methods.menuUiPreferencesStructure()[field]
/*
* This we'll end up returning
*/
const data = {
icon: <Swizzled.components.UiIcon />,
field,
optCode: `${field}.t`,
titleCode: 'uiPreferences.t',
structure: Swizzled.methods.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'] = Swizzled.methods.t(
structure.choiceTitles[
structure.choiceTitles[String(step[key])] ? String(step[key]) : String(structure.dflt)
] + '.t'
)
return data
}
export function getCoreSettingUndoStepData(Swizzled, { step, state, Design }) {
const field = step.path[1]
const structure = Swizzled.methods.menuCoreSettingsStructure({
language: state.language,
units: state.settings.units,
sabool: state.settings.sabool,
parts: Design.patternConfig.draftOrder,
})
const data = {
field,
titleCode: 'coreSettings.t',
optCode: `${field}.t`,
icon: <Swizzled.components.SettingsIcon />,
structure: structure[field],
}
if (!data.structure && field === 'sa') data.structure = structure.samm
const FieldIcon = data.structure?.icon || Swizzled.components.FixmeIcon
data.fieldIcon = <FieldIcon />
/*
* Save us some typing
*/
const cord = Swizzled.methods.settingsValueCustomOrDefault
const formatMm = Swizzled.methods.formatMm
const Html = Swizzled.components.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.optCode = `samm.t`
}
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 = Swizzled.methods.t(
step.new === 'imperial' ? 'pe:metricUnits' : 'pe:imperialUnits'
)
data.newVal = Swizzled.methods.t(
step.new === 'imperial' ? 'pe:imperialUnits' : 'pe:metricUnits'
)
return data
case 'only':
data.oldVal = cord(step.old, data.structure.dflt) || Swizzled.methods.t('pe:includeAllParts')
data.newVal = cord(step.new, data.structure.dflt) || Swizzled.methods.t('pe:includeAllParts')
return data
default:
data.oldVal = Swizzled.methods.t(
(data.structure.choiceTitles[String(step.old)]
? data.structure.choiceTitles[String(step.old)]
: data.structure.choiceTitles[String(data.structure.dflt)]) + '.t'
)
data.newVal = Swizzled.methods.t(
(data.structure.choiceTitles[String(step.new)]
? data.structure.choiceTitles[String(step.new)]
: data.structure.choiceTitles[String(data.structure.dflt)]) + '.t'
)
return data
}
}
export function getDesignOptionUndoStepData(Swizzled, { step, state, Design }) {
const option = Design.patternConfig.options[step.path[2]]
const data = {
icon: <Swizzled.components.OptionsIcon />,
field: step.path[2],
optCode: `${state.design}:${step.path[2]}.t`,
titleCode: `designOptions.t`,
oldVal: Swizzled.methods.formatDesignOptionValue(option, step.old, state.units === 'imperial'),
newVal: Swizzled.methods.formatDesignOptionValue(option, step.new, state.units === 'imperial'),
}
return data
}
export function getUndoStepData(Swizzled, props) {
/*
* UI Preferences
*/
if ((props.step.name === 'settings' && props.step.path[1] === 'ui') || props.step.name === 'ui')
return Swizzled.methods.getUiPreferenceUndoStepData(props)
/*
* Design options
*/
if (props.step.name === 'settings' && props.step.path[1] === 'options')
return Swizzled.methods.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 Swizzled.methods.getCoreSettingUndoStepData(props)
/*
* Measurements
*/
if (props.step.name === 'settings' && props.step.path[1] === 'measurements') {
const data = {
icon: <Swizzled.components.MeasurementsIcon />,
field: 'measurements',
optCode: `measurements`,
titleCode: 'measurements',
}
/*
* Single measurements change?
*/
if (props.step.path[2])
return {
...data,
field: props.step.path[2],
oldVal: Swizzled.methods.formatMm(props.step.old, props.imperial),
newVal: Swizzled.methods.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: Swizzled.methods.t('pe:xMeasurementsChanged', { count }) }
}
/*
* 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
* @param {object} Swizzled - The swizzled data
*/
export function initialEditorState(Swizzled) {
/*
* Create initial state object
*/
const initial = { ...Swizzled.config.initialState }
/*
* 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 {object} Swizzled - Swizzled code, not used here
* @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(Swizzled, num, factor) {
const { round } = Swizzled.methods
// 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 {object} Swizzled - Swizzled code, not used here
* @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(
Swizzled,
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 ? Swizzled.methods.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 {object} Swizzled - Swizzled code, not used here
* @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(Swizzled, 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} methods - An object holding possibly swizzled methods (unused here)
* @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(Swizzled, 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} methods - An object holding possibly swizzled methods (unused here)
* @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(
Swizzled,
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: Swizzled.methods.cloneObject(obj),
},
...cur.undos,
],
}
})
return Swizzled.methods.objUpdate(obj, path, val)
}
/*
* 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} Swizzled - An object holding possibly swizzled code (unused here)
* @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(Swizzled, undo, restore, setEphemeralState) {
setEphemeralState((cur) => {
if (!Array.isArray(cur.undos)) cur.undos = []
return {
...cur,
undos: [
{ time: Date.now(), ...undo, restore: Swizzled.methods.cloneObject(restore) },
...cur.undos,
],
}
})
}
/*
* Helper method to clone an object
*/
export function cloneObject(Swizzled, 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(Swizzled, 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(Swizzled, setState, setEphemeralState) {
return {
/*
* This allows raw access to the entire state object
*/
state: (path, val) => setState((cur) => Swizzled.methods.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) =>
Swizzled.methods.undoableObjUpdate(
'settings',
{ ...cur },
Swizzled.methods.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 = Swizzled.methods.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) Swizzled.methods.objUpdate(cur, `settings.${key}`, val)
// Which we'll group as 1 undo action
Swizzled.methods.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) =>
Swizzled.methods.undoableObjUpdate(
'ui',
{ ...cur },
Swizzled.methods.statePrefixPath('ui', path),
val,
setEphemeralState
)
),
/*
* These only hold a string, so we only take a value
*/
design: (val) => setState((cur) => Swizzled.methods.objUpdate({ ...cur }, 'design', val)),
view: (val) => {
// Only take valid view names
if (!Swizzled.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) && Swizzled.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
})
},
ux: (val) => setState((cur) => Swizzled.methods.objUpdate({ ...cur }, 'ux', val)),
clearPattern: () =>
setState((cur) => {
const newState = { ...cur }
Swizzled.methods.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
*/
Swizzled.methods.objUpdate(newState, 'ui', { ...newState.ui, renderer: 'react' })
return newState
}),
clearAll: () => setState(Swizzled.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: Swizzled.methods.t('pe:genericLoadingMsg'),
...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: Swizzled.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: Swizzled.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: Swizzled.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
* @param {object} Swizzled - Swizzled code, not used here
*/
export function cloudImageUrl(Swizzled, { id = 'default-avatar', variant = 'public' }) {
/*
* Return something default so that people will actually change it
*/
if (!id || id === 'default-avatar') return Swizzled.config.cloudImageDflt
/*
* If the variant is invalid, set it to the smallest thumbnail so
* people don't load enourmous images by accident
*/
if (!Swizzled.config.cloudImageVariants.includes(variant)) variant = 'sq100'
return `${Swizzled.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 {object} methods - An object holding possibly swizzled methods (unused here)
* @param {[string]} namespaces - A string or array of strings of namespaces
* @return {[string]} namespaces - A merged array of all namespaces
*/
export function nsMerge(Swizzled, ...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 {object} Swizzled - Swizzled code, not used here
* @param {string} key - The input
* @return {string} key - The input is returned
*/
export function t(Swizzled, key) {
/*
* Make sure this works when Swizzled is not passed in
*/
if (typeof Swizzled.components === 'undefined') key = Swizzled
return Array.isArray(key) ? key[0] : key
}
export function settingsValueIsCustom(Swizzled, val, dflt) {
return typeof val === 'undefined' || val === '__UNSET__' || val === dflt ? false : true
}
export function settingsValueCustomOrDefault(Swizzled, val, dflt) {
return typeof val === 'undefined' || val === '__UNSET__' || val === dflt ? dflt : val
}

View file

@ -0,0 +1,245 @@
/*
* Method that capitalizes a string (make the first character uppercase)
*
* @param {object} Swizzled - Swizzled code, not used here
* @param {string} string - The input string to capitalize
* @return {string} String - The capitalized input string
*/
export function capitalize(Swizzled, string) {
return typeof string === 'string' ? string.charAt(0).toUpperCase() + string.slice(1) : ''
}
export function formatDesignOptionValue(Swizzled, option, value, imperial) {
const oType = Swizzled.methods.designOptionType(option)
if (oType === 'pct') return Swizzled.methods.formatPercentage(value ? value : option.pct / 100)
if (oType === 'deg') return `${value ? value : option.deg}°`
if (oType === 'bool')
return typeof value === 'undefined' ? (
option.bool
) : value ? (
<Swizzled.components.BoolYesIcon />
) : (
<Swizzled.components.BoolNoIcon />
)
if (oType === 'mm')
return Swizzled.methods.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(Swizzled, 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 Swizzled.methods.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 Swizzled.methods.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(Swizzled, 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(Swizzled, val, units, format = 'html') {
val = Swizzled.methods.roundMm(val)
if (units === 'imperial' || units === true) {
if (val == 0) return Swizzled.methods.formatImperial('', 0, false, false, format)
let fraction = val / 25.4
return Swizzled.methods.formatFraction128(fraction, format)
} else {
if (format === 'html' || format === 'notags') return Swizzled.methods.roundMm(val / 10) + 'cm'
else return Swizzled.methods.roundMm(val / 10)
}
}
// Format a percentage (as in, between 0 and 1)
export function formatPercentage(Swizzled, val) {
return Math.round(1000 * val) / 10 + '%'
}
/**
* A generic rounding method
*
* @param {object} Swizzled - Swizzled code, not used here
* @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(Swizzled, 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 {object} Swizzled - Swizzled code, not used here
* @param {number} value - The input value
* @return {number} result - The resulting decimal value
*/
export function fractionToDecimal(Swizzled, 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 {object} Swizzled - Swizzled code, including methods
* @param {number} value - The input value
* @param {string} units - One of 'metric' or 'imperial'
* @return {number} result - Value in millimeter
*/
export function measurementAsMm(Swizzled, 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 = Swizzled.methods.fractionToDecimal(value)
if (isNaN(decimal)) return false
return decimal * 24.5
}
}
/**
* Converts a millimeter value to a Number value in the given units
*
* @param {object} Swizzled - Swizzled code, not used here
* @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(Swizzled, mmValue, units = 'metric') {
return Swizzled.methods.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 {object} Swizzled - Swizzled code, including methods
* @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(Swizzled, 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 = Swizzled.methods.fractionToDecimal(val)
return isNaN(val) ? false : Number(val)
}

View file

@ -0,0 +1,240 @@
/*************************************************************************
* *
* FreeSewing's pattern editor allows swizzling methods *
* *
* To 'swizzle' means to replace the default implementation of a *
* method with a custom one. It allows one to customize *
* the pattern editor. *
* *
* This file holds the 'swizzleMethods' method that will return *
* the various methods that can be swizzled, or their default *
* implementation. *
* *
* To use a custom version, simply pas it as a prop into the editor *
* under the 'methods' key. So to pass a custom 't' method (used for *
* translation(, you do: *
* *
* <PatternEditor methods={{ t: myCustomTranslationMethod }} /> *
* *
*************************************************************************/
/*
* Import of methods that can be swizzled
*/
import {
defaultSa,
defaultSamm,
menuCoreSettingsOnlyHandler,
menuCoreSettingsSaboolHandler,
menuCoreSettingsSammHandler,
menuCoreSettingsStructure,
} from './core-settings.mjs'
import {
designOptionType,
findOption,
getOptionStructure,
menuDesignOptionsStructure,
} from './design-options.mjs'
import {
addUndoStep,
cloneObject,
cloudImageUrl,
draft,
flattenFlags,
getCoreSettingUndoStepData,
getDesignOptionUndoStepData,
getUiPreferenceUndoStepData,
getUndoStepData,
initialEditorState,
menuRoundPct,
menuValidateNumericValue,
menuValueWasChanged,
noop,
notEmpty,
nsMerge,
objUpdate,
settingsValueIsCustom,
settingsValueCustomOrDefault,
statePrefixPath,
stateUpdateFactory,
t,
undoableObjUpdate,
} from './editor.mjs'
import {
capitalize,
formatDesignOptionValue,
formatFraction128,
formatImperial,
formatMm,
formatPercentage,
round,
roundMm,
fractionToDecimal,
measurementAsMm,
measurementAsUnits,
shortDate,
parseDistanceInput,
} from './formatting.mjs'
import {
designMeasurements,
hasRequiredMeasurements,
isDegreeMeasurement,
missingMeasurements,
structureMeasurementsAsDesign,
} from './measurements.mjs'
import { menuUiPreferencesStructure } from './ui-preferences.mjs'
/**
* This object holds all methods that can be swizzled
*/
const defaultMethods = {
// core-settings.mjs
defaultSa,
defaultSamm,
menuCoreSettingsOnlyHandler,
menuCoreSettingsSaboolHandler,
menuCoreSettingsSammHandler,
menuCoreSettingsStructure,
// design-options.mjs
designOptionType,
findOption,
getOptionStructure,
menuDesignOptionsStructure,
// editor.mjs
addUndoStep,
cloneObject,
cloudImageUrl,
draft,
flattenFlags,
getCoreSettingUndoStepData,
getDesignOptionUndoStepData,
getUiPreferenceUndoStepData,
getUndoStepData,
initialEditorState,
menuRoundPct,
menuValidateNumericValue,
menuValueWasChanged,
noop,
notEmpty,
nsMerge,
objUpdate,
settingsValueIsCustom,
settingsValueCustomOrDefault,
statePrefixPath,
stateUpdateFactory,
t,
undoableObjUpdate,
// formatting.mjs
capitalize,
formatDesignOptionValue,
formatFraction128,
formatImperial,
formatMm,
formatPercentage,
round,
roundMm,
fractionToDecimal,
measurementAsMm,
measurementAsUnits,
shortDate,
parseDistanceInput,
// measurements.mjs
designMeasurements,
hasRequiredMeasurements,
isDegreeMeasurement,
missingMeasurements,
structureMeasurementsAsDesign,
// ui-preferences.mjs
menuUiPreferencesStructure,
}
/*
* This method returns methods that can be swizzled
* So either the passed-in methods, or the default ones
*/
const swizzleMethods = (methods, Swizzled) => {
/*
* We need to pass down the resulting methods, swizzled or not
* because some methods rely on other (possibly swizzled) methods.
* So we put this in this object so we can pass that down
*/
const all = {}
for (const [name, method] of Object.entries(defaultMethods)) {
if (typeof method !== 'function')
console.warn(`${name} is not defined as default method in swizzleMethods`)
all[name] = methods[name]
? (...params) => methods[name](all, ...params)
: (...params) => method(Swizzled, ...params)
}
/*
* Return all methods
*/
return all
}
/*
* Named exports
*/
export {
swizzleMethods,
// Re-export all methods for specific imports
// core-settings.mjs
defaultSa,
defaultSamm,
menuCoreSettingsOnlyHandler,
menuCoreSettingsSaboolHandler,
menuCoreSettingsSammHandler,
menuCoreSettingsStructure,
// design-options.mjs
designOptionType,
findOption,
getOptionStructure,
menuDesignOptionsStructure,
// editor.mjs
addUndoStep,
cloneObject,
cloudImageUrl,
draft,
flattenFlags,
getCoreSettingUndoStepData,
getDesignOptionUndoStepData,
getUiPreferenceUndoStepData,
getUndoStepData,
initialEditorState,
menuRoundPct,
menuValidateNumericValue,
menuValueWasChanged,
noop,
notEmpty,
nsMerge,
objUpdate,
settingsValueIsCustom,
settingsValueCustomOrDefault,
statePrefixPath,
stateUpdateFactory,
t,
undoableObjUpdate,
// formatting.mjs
capitalize,
formatDesignOptionValue,
formatFraction128,
formatImperial,
formatMm,
formatPercentage,
round,
roundMm,
fractionToDecimal,
measurementAsMm,
measurementAsUnits,
shortDate,
parseDistanceInput,
// measurements.mjs
designMeasurements,
hasRequiredMeasurements,
isDegreeMeasurement,
missingMeasurements,
structureMeasurementsAsDesign,
// ui-preferences.mjs
menuUiPreferencesStructure,
}

View file

@ -0,0 +1,84 @@
/*
* Returns a list of measurements for a design
*
* @param {object} Swizzled - Swizzled code, not used here
* @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(Swizzled, 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 determine whether all required measurements for a design are present
*
* @param {object} Swizzled - Swizzled code, including methods
* @param {object} Design - The FreeSewing design (or a plain object holding measurements)
* @param {object} measurements - An object holding the user's measurements
* @return {array} result - An array where the first element is true when we
* have all measurements, and false if not. The second element is a list of
* missing measurements.
*/
export function hasRequiredMeasurements(Swizzled, Design, measurements = {}) {
/*
* If design is just a plain object holding measurements, we restructure it as a Design
* AS it happens, this method is smart enough to test for this, so we call it always
*/
Design = Swizzled.methods.structureMeasurementsAsDesign(Design)
/*
* Walk required measuremnets, and keep track of what's missing
*/
const missing = []
for (const m of Design.patternConfig?.measurements || []) {
if (typeof measurements[m] === 'undefined') missing.push(m)
}
/*
* Return true or false, plus a list of missing measurements
*/
return [missing.length === 0, missing]
}
/**
* Helper method to determine whether a measurement uses degrees
*
* @param {object} Swizzled - Swizzled code, not used here
* @param {string} name - The name of the measurement
* @return {bool} isDegree - True if the measurment is a degree measurement
*/
export function isDegreeMeasurement(Swizzled, name) {
return Swizzled.config.degreeMeasurements.indexOf(name) !== -1
}
/*
* Helper method to check whether measururements are missing
*
* Note that this does not actually check the settings against
* the chose 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 in the non-Swizzled ViewWrapper components
*
* @param {object} Swizzled - Object holding Swizzled code
* @param {object } state - The Editor state
* @return {bool} missing - True if there are missing measurments, false if not
*/
export function missingMeasurements(Swizzled, state) {
return (
!Swizzled.config.measurementsFreeViews.includes(state.view) &&
state._.missingMeasurements &&
state._.missingMeasurements.length > 0
)
}
/*
* This takes a POJO of measurements, and turns it into a structure that matches a design object
*
* @param {object} Swizzled - Swizzled code, not used here
* @param {object} measurements - The POJO of measurments
* @return {object} design - The measurements structured as a design object
*/
export function structureMeasurementsAsDesign(Swizzled, measurements) {
return measurements.patternConfig ? measurements : { patternConfig: { measurements } }
}

View file

@ -0,0 +1,60 @@
export function menuUiPreferencesStructure(Swizzled) {
const uiUx = Swizzled.config.uxLevels.ui
const uiPreferences = {
ux: {
ux: uiUx.ux,
emoji: '🖥️',
list: [1, 2, 3, 4, 5],
choiceTitles: {},
icon: Swizzled.components.UxIcon,
dflt: Swizzled.config.defaultUx,
},
aside: {
ux: uiUx.aside,
list: [0, 1],
choiceTitles: {
0: 'pe:noAside',
1: 'pe:withAside',
},
dflt: 1,
icon: Swizzled.components.MenuIcon,
},
kiosk: {
ux: uiUx.kiosk,
list: [0, 1],
choiceTitles: {
0: 'pe:websiteMode',
1: 'pe:kioskMode',
},
dflt: 0,
icon: Swizzled.components.KioskIcon,
},
rotate: {
ux: uiUx.rotate,
list: [0, 1],
choiceTitles: {
0: 'pe:rotateNo',
1: 'pe:rotateYes',
},
dflt: 0,
icon: Swizzled.components.RotateIcon,
},
renderer: {
ux: uiUx.renderer,
list: ['react', 'svg'],
choiceTitles: {
react: 'pe:renderWithReact',
svg: 'pe:renderWithCore',
},
valueTitles: {
react: 'React',
svg: 'SVG',
},
dflt: 'react',
icon: Swizzled.components.RocketIcon,
},
}
uiPreferences.ux.list.forEach((i) => (uiPreferences.ux.choiceTitles[i] = 'pe:ux' + i))
return uiPreferences
}