three-text 0.2.8 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * three-text v0.2.8
2
+ * three-text v0.2.9
3
3
  * Copyright (C) 2025 Countertype LLC
4
4
  *
5
5
  * This program is free software: you can redistribute it and/or modify
@@ -188,11 +188,11 @@
188
188
  FitnessClass[FitnessClass["VERY_LOOSE"] = 3] = "VERY_LOOSE";
189
189
  })(FitnessClass || (FitnessClass = {}));
190
190
  // ActiveNodeList maintains all currently viable breakpoints as we scan through the text.
191
- // Each node represents a potential break with accumulated demerits (total "cost" from start).
191
+ // Each node represents a potential break with accumulated demerits (total "cost" from start)
192
192
  //
193
193
  // Demerits = cumulative penalty score from text start to this break, calculated as:
194
- // (line_penalty + badness)² + penalty² + flagged/fitness adjustments (tex.web §859)
195
- // Lower demerits = better line breaks. TeX minimizes total demerits across the paragraph.
194
+ // (line_penalty + badness)² + penalty² + flagged/fitness adjustments (tex.web line 16634)
195
+ // Lower demerits = better line breaks. TeX minimizes total demerits across the paragraph
196
196
  //
197
197
  // Implementation differs from TeX:
198
198
  // - Hash map for O(1) lookups by position+fitness
@@ -263,7 +263,7 @@
263
263
  const SHORT_LINE_WIDTH_THRESHOLD = 0.5; // Lines < 50% of width are problematic
264
264
  const SHORT_LINE_EMERGENCY_STRETCH_INCREMENT = 0.1; // Add 10% per iteration
265
265
  class LineBreak {
266
- // Calculate badness according to TeX's formula (tex.web §108, line 2337)
266
+ // Calculate badness according to TeX's formula (tex.web line 2337)
267
267
  // Given t (desired adjustment) and s (available stretch/shrink)
268
268
  // Returns approximation to 100(t/s)³, representing how "bad" a line is
269
269
  // Constants are derived from TeX's fixed-point arithmetic:
@@ -812,19 +812,22 @@
812
812
  // First pass: no hyphenation
813
813
  let currentItems = allItems;
814
814
  let breaks = LineBreak.findBreakpoints(currentItems, width, pretolerance, looseness, false, 0, context);
815
- // Second pass: compute hyphenation only if needed
815
+ // Second pass: with hyphenation if first pass failed
816
816
  if (breaks.length === 0 && useHyphenation) {
817
817
  const itemsWithHyphenation = LineBreak.itemizeText(text, measureText, true, language, hyphenationPatterns, lefthyphenmin, righthyphenmin, context);
818
818
  currentItems = itemsWithHyphenation;
819
819
  breaks = LineBreak.findBreakpoints(currentItems, width, tolerance, looseness, false, 0, context);
820
820
  }
821
- // Emergency pass: use currentItems as-is (preserves hyphenation from pass 2 if it ran)
821
+ // Emergency pass: add emergency stretch to background stretchability
822
822
  if (breaks.length === 0) {
823
- breaks = LineBreak.findBreakpoints(currentItems, width, INF_BAD + 1, looseness, true, currentEmergencyStretch, context);
823
+ // For first emergency attempt, use initialEmergencyStretch
824
+ // For subsequent iterations (short line detection), progressively increase
825
+ currentEmergencyStretch = initialEmergencyStretch + (iteration * width * SHORT_LINE_EMERGENCY_STRETCH_INCREMENT);
826
+ breaks = LineBreak.findBreakpoints(currentItems, width, tolerance, looseness, true, currentEmergencyStretch, context);
824
827
  }
825
- // Force with infinite tolerance if still no breaks found
828
+ // Last resort: allow higher badness (but not infinite)
826
829
  if (breaks.length === 0) {
827
- breaks = LineBreak.findBreakpoints(currentItems, width, Infinity, looseness, true, currentEmergencyStretch, context);
830
+ breaks = LineBreak.findBreakpoints(currentItems, width, INF_BAD, looseness, true, currentEmergencyStretch, context);
828
831
  }
829
832
  // Create lines from breaks
830
833
  if (breaks.length > 0) {
@@ -834,9 +837,7 @@
834
837
  if (shortLineDetectionEnabled &&
835
838
  breaks.length > 1 &&
836
839
  LineBreak.hasShortLines(currentItems, breaks, width, shortLineThreshold)) {
837
- // Increase emergency stretch and try again
838
- currentEmergencyStretch +=
839
- width * SHORT_LINE_EMERGENCY_STRETCH_INCREMENT;
840
+ // Retry with more emergency stretch to push words to next line
840
841
  iteration++;
841
842
  continue;
842
843
  }
@@ -868,11 +869,12 @@
868
869
  threshold = Infinity, // maximum badness allowed for a break
869
870
  looseness = 0, // desired line count adjustment
870
871
  isFinalPass = false, // whether this is the final pass
871
- emergencyStretch = 0, // emergency stretch added to background stretchability
872
+ backgroundStretch = 0, // additional stretchability for all glue (emergency stretch)
872
873
  context) {
873
874
  // Pre-compute cumulative widths for fast range queries
874
875
  const cumulativeWidths = LineBreak.computeCumulativeWidths(items);
875
876
  const activeNodes = new ActiveNodeList();
877
+ const minimumDemerits = { value: Infinity };
876
878
  activeNodes.insert({
877
879
  position: 0,
878
880
  line: 0,
@@ -886,16 +888,16 @@
886
888
  const item = items[i];
887
889
  if (item.type === ItemType.PENALTY &&
888
890
  item.penalty < Infinity) {
889
- LineBreak.considerBreak(items, activeNodes, i, lineWidth, threshold, emergencyStretch, cumulativeWidths, context);
891
+ LineBreak.considerBreak(items, activeNodes, i, lineWidth, threshold, backgroundStretch, cumulativeWidths, context, isFinalPass, minimumDemerits);
890
892
  }
891
893
  if (item.type === ItemType.DISCRETIONARY &&
892
894
  item.penalty < Infinity) {
893
- LineBreak.considerBreak(items, activeNodes, i, lineWidth, threshold, emergencyStretch, cumulativeWidths, context);
895
+ LineBreak.considerBreak(items, activeNodes, i, lineWidth, threshold, backgroundStretch, cumulativeWidths, context, isFinalPass, minimumDemerits);
894
896
  }
895
897
  if (item.type === ItemType.GLUE &&
896
898
  i > 0 &&
897
899
  items[i - 1].type === ItemType.BOX) {
898
- LineBreak.considerBreak(items, activeNodes, i, lineWidth, threshold, emergencyStretch, cumulativeWidths, context);
900
+ LineBreak.considerBreak(items, activeNodes, i, lineWidth, threshold, backgroundStretch, cumulativeWidths, context, isFinalPass, minimumDemerits);
899
901
  }
900
902
  LineBreak.deactivateNodes(activeNodes, i, lineWidth, cumulativeWidths.minWidths);
901
903
  }
@@ -962,7 +964,7 @@
962
964
  }
963
965
  return breakpoints;
964
966
  }
965
- static considerBreak(items, activeNodes, breakpoint, lineWidth, threshold = Infinity, emergencyStretch = 0, cumulativeWidths, context) {
967
+ static considerBreak(items, activeNodes, breakpoint, lineWidth, threshold = Infinity, backgroundStretch = 0, cumulativeWidths, context, isFinalPass = false, minimumDemerits = { value: Infinity }) {
966
968
  const penalty = items[breakpoint].type === ItemType.PENALTY
967
969
  ? items[breakpoint].penalty
968
970
  : 0;
@@ -974,11 +976,11 @@
974
976
  continue;
975
977
  const adjustmentData = LineBreak.computeAdjustmentRatio(items, node.position, breakpoint, node.line, lineWidth, cumulativeWidths, context);
976
978
  const { ratio: r, adjustment, stretch, shrink, totalWidth } = adjustmentData;
977
- // Calculate badness according to TeX formula
979
+ // Calculate badness
978
980
  let badness;
979
981
  if (adjustment > 0) {
980
- // Add emergency stretch to the background stretchability
981
- const effectiveStretch = stretch + emergencyStretch;
982
+ // backgroundStretch includes emergency stretch if in emergency pass
983
+ const effectiveStretch = stretch + backgroundStretch;
982
984
  if (effectiveStretch <= 0) {
983
985
  // Overfull box - badness is infinite + 1
984
986
  badness = INF_BAD + 1;
@@ -1003,26 +1005,32 @@
1003
1005
  else {
1004
1006
  badness = 0;
1005
1007
  }
1006
- if (!isForcedBreak && r < -1) {
1007
- // Too tight, skip unless forced
1008
- continue;
1008
+ // Artificial demerits: in final pass with no feasible solution yet
1009
+ // and only one active node left, force this break as a last resort
1010
+ const isLastResort = isFinalPass &&
1011
+ minimumDemerits.value === Infinity &&
1012
+ allActiveNodes.length === 1 &&
1013
+ node.active;
1014
+ if (!isForcedBreak && !isLastResort && r < -1) {
1015
+ continue; // too tight
1009
1016
  }
1010
1017
  const fitnessClass = LineBreak.computeFitnessClass(badness, adjustment > 0);
1011
- if (!isForcedBreak && badness > threshold) {
1018
+ if (!isForcedBreak && !isLastResort && badness > threshold) {
1012
1019
  continue;
1013
1020
  }
1014
- // Initialize demerits based on TeX formula with saturation check
1021
+ // Initialize demerits with saturation check
1015
1022
  let flaggedDemerits = 0;
1016
1023
  let fitnessDemerits = 0;
1017
1024
  const configuredLinePenalty = context?.linePenalty ?? 0;
1018
1025
  let d = configuredLinePenalty + badness;
1019
1026
  let demerits = Math.abs(d) >= 10000 ? 100000000 : d * d;
1027
+ const artificialDemerits = isLastResort;
1020
1028
  const breakpointPenalty = items[breakpoint].type === ItemType.PENALTY
1021
1029
  ? items[breakpoint].penalty
1022
1030
  : items[breakpoint].type === ItemType.DISCRETIONARY
1023
1031
  ? items[breakpoint].penalty
1024
1032
  : 0;
1025
- // TeX penalty handling: pi != 0 check, then positive/negative logic
1033
+ // Penalty contribution to demerits
1026
1034
  if (breakpointPenalty !== 0) {
1027
1035
  if (breakpointPenalty > 0) {
1028
1036
  demerits += breakpointPenalty * breakpointPenalty;
@@ -1048,10 +1056,13 @@
1048
1056
  fitnessDemerits = context?.adjDemerits ?? 0;
1049
1057
  demerits += fitnessDemerits;
1050
1058
  }
1051
- if (isForcedBreak) {
1059
+ if (isForcedBreak || artificialDemerits) {
1052
1060
  demerits = 0;
1053
1061
  }
1054
1062
  const totalDemerits = node.totalDemerits + demerits;
1063
+ if (totalDemerits < minimumDemerits.value) {
1064
+ minimumDemerits.value = totalDemerits;
1065
+ }
1055
1066
  let existingNode = activeNodes.findExisting(breakpoint, fitnessClass);
1056
1067
  if (existingNode) {
1057
1068
  if (totalDemerits < existingNode.totalDemerits) {
@@ -1189,7 +1200,6 @@
1189
1200
  return { widths, stretches, shrinks, minWidths };
1190
1201
  }
1191
1202
  // Deactivate nodes that can't lead to good line breaks
1192
- // TeX recalculates minWidth each time, we use cumulative arrays for lookup
1193
1203
  static deactivateNodes(activeNodeList, currentPosition, lineWidth, minWidths) {
1194
1204
  const activeNodes = activeNodeList.getAllActive();
1195
1205
  for (let i = activeNodes.length - 1; i >= 0; i--) {
@@ -1394,8 +1404,8 @@
1394
1404
 
1395
1405
  class TextMeasurer {
1396
1406
  // Measures text width including letter spacing
1397
- // Letter spacing is added uniformly after each glyph during measurement,
1398
- // so the widths given to the line-breaking algorithm already account for tracking
1407
+ // (letter spacing is added uniformly after each glyph during measurement,
1408
+ // so the widths given to the line-breaking algorithm already account for tracking)
1399
1409
  static measureTextWidth(loadedFont, text, letterSpacing = 0) {
1400
1410
  const buffer = loadedFont.hb.createBuffer();
1401
1411
  buffer.addText(text);
@@ -3719,10 +3729,11 @@
3719
3729
  }
3720
3730
  }
3721
3731
 
3732
+ const CONTOUR_CACHE_MAX_ENTRIES = 1000;
3733
+ const WORD_CACHE_MAX_ENTRIES = 1000;
3722
3734
  class GlyphGeometryBuilder {
3723
3735
  constructor(cache, loadedFont) {
3724
3736
  this.fontId = 'default';
3725
- this.wordCache = new Map();
3726
3737
  this.cache = cache;
3727
3738
  this.loadedFont = loadedFont;
3728
3739
  this.tessellator = new Tessellator();
@@ -3732,7 +3743,7 @@
3732
3743
  this.drawCallbacks = new DrawCallbackHandler();
3733
3744
  this.drawCallbacks.createDrawFuncs(this.loadedFont, this.collector);
3734
3745
  this.contourCache = new LRUCache({
3735
- maxEntries: 1000,
3746
+ maxEntries: CONTOUR_CACHE_MAX_ENTRIES,
3736
3747
  calculateSize: (contours) => {
3737
3748
  let size = 0;
3738
3749
  for (const path of contours.paths) {
@@ -3741,6 +3752,15 @@
3741
3752
  return size + 64; // bounds overhead
3742
3753
  }
3743
3754
  });
3755
+ this.wordCache = new LRUCache({
3756
+ maxEntries: WORD_CACHE_MAX_ENTRIES,
3757
+ calculateSize: (data) => {
3758
+ let size = data.vertices.length * 4;
3759
+ size += data.normals.length * 4;
3760
+ size += data.indices.length * data.indices.BYTES_PER_ELEMENT;
3761
+ return size;
3762
+ }
3763
+ });
3744
3764
  }
3745
3765
  getOptimizationStats() {
3746
3766
  return this.collector.getOptimizationStats();
@@ -4030,7 +4050,7 @@
4030
4050
  let currentClusterText = '';
4031
4051
  let clusterStartPosition = new Vec3();
4032
4052
  let cursor = new Vec3(lineInfo.xOffset, -lineIndex * scaledLineHeight, 0);
4033
- // Apply letter spacing between glyphs (must match what was used in width measurements)
4053
+ // Apply letter spacing after each glyph to match width measurements used during line breaking
4034
4054
  const letterSpacingFU = letterSpacing * this.loadedFont.upem;
4035
4055
  const spaceAdjustment = this.calculateSpaceAdjustment(lineInfo, align, letterSpacing);
4036
4056
  const cjkAdjustment = this.calculateCJKAdjustment(lineInfo, align);
@@ -5068,6 +5088,54 @@
5068
5088
  if (!Text.hbInitPromise) {
5069
5089
  Text.hbInitPromise = HarfBuzzLoader.getHarfBuzz();
5070
5090
  }
5091
+ const loadedFont = await Text.resolveFont(options);
5092
+ const text = new Text({ maxCacheSizeMB: options.maxCacheSizeMB });
5093
+ text.setLoadedFont(loadedFont);
5094
+ // Initial creation
5095
+ const { font, maxCacheSizeMB, ...geometryOptions } = options;
5096
+ const result = await text.createGeometry(geometryOptions);
5097
+ // Recursive update function
5098
+ const update = async (newOptions) => {
5099
+ // Merge options - preserve font from original options if not provided
5100
+ const mergedOptions = { ...options };
5101
+ for (const key in newOptions) {
5102
+ const value = newOptions[key];
5103
+ if (value !== undefined) {
5104
+ mergedOptions[key] = value;
5105
+ }
5106
+ }
5107
+ // If font definition or configuration changed, reload font and reset helpers
5108
+ if (newOptions.font !== undefined ||
5109
+ newOptions.fontVariations !== undefined ||
5110
+ newOptions.fontFeatures !== undefined) {
5111
+ const newLoadedFont = await Text.resolveFont(mergedOptions);
5112
+ text.setLoadedFont(newLoadedFont);
5113
+ // Reset geometry builder and shaper to use new font
5114
+ text.resetHelpers();
5115
+ }
5116
+ // Update closure options for next time
5117
+ options = mergedOptions;
5118
+ const { font, maxCacheSizeMB, ...currentGeometryOptions } = options;
5119
+ const newResult = await text.createGeometry(currentGeometryOptions);
5120
+ return {
5121
+ ...newResult,
5122
+ getLoadedFont: () => text.getLoadedFont(),
5123
+ getCacheStatistics: () => text.getCacheStatistics(),
5124
+ clearCache: () => text.clearCache(),
5125
+ measureTextWidth: (textString, letterSpacing) => text.measureTextWidth(textString, letterSpacing),
5126
+ update
5127
+ };
5128
+ };
5129
+ return {
5130
+ ...result,
5131
+ getLoadedFont: () => text.getLoadedFont(),
5132
+ getCacheStatistics: () => text.getCacheStatistics(),
5133
+ clearCache: () => text.clearCache(),
5134
+ measureTextWidth: (textString, letterSpacing) => text.measureTextWidth(textString, letterSpacing),
5135
+ update
5136
+ };
5137
+ }
5138
+ static async resolveFont(options) {
5071
5139
  const baseFontKey = typeof options.font === 'string'
5072
5140
  ? options.font
5073
5141
  : `buffer-${Text.generateFontContentHash(options.font)}`;
@@ -5082,17 +5150,7 @@
5082
5150
  if (!loadedFont) {
5083
5151
  loadedFont = await Text.loadAndCacheFont(fontKey, options.font, options.fontVariations, options.fontFeatures);
5084
5152
  }
5085
- const text = new Text({ maxCacheSizeMB: options.maxCacheSizeMB });
5086
- text.setLoadedFont(loadedFont);
5087
- const { font, maxCacheSizeMB, ...geometryOptions } = options;
5088
- const result = await text.createGeometry(geometryOptions);
5089
- return {
5090
- ...result,
5091
- getLoadedFont: () => text.getLoadedFont(),
5092
- getCacheStatistics: () => text.getCacheStatistics(),
5093
- clearCache: () => text.clearCache(),
5094
- measureTextWidth: (textString, letterSpacing) => text.measureTextWidth(textString, letterSpacing)
5095
- };
5153
+ return loadedFont;
5096
5154
  }
5097
5155
  static async loadAndCacheFont(fontKey, font, fontVariations, fontFeatures) {
5098
5156
  const tempText = new Text();
@@ -5550,6 +5608,11 @@
5550
5608
  glyphLineIndex: glyphLineIndices
5551
5609
  };
5552
5610
  }
5611
+ resetHelpers() {
5612
+ this.geometryBuilder = undefined;
5613
+ this.textShaper = undefined;
5614
+ this.textLayout = undefined;
5615
+ }
5553
5616
  destroy() {
5554
5617
  if (!this.loadedFont) {
5555
5618
  return;