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,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()
}
}