@instruments/quadrat 0.0.0-stage → 0.1.1

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.
Files changed (77) hide show
  1. package/README.md +40 -2
  2. package/dist/analysis/analyze-surface-regions.d.ts +34 -0
  3. package/dist/analysis/analyze-surface-regions.d.ts.map +1 -0
  4. package/dist/analysis/analyze-surface-regions.js +47 -0
  5. package/dist/analysis/decode.d.ts +23 -0
  6. package/dist/analysis/decode.d.ts.map +1 -0
  7. package/dist/analysis/decode.js +48 -0
  8. package/dist/analysis/descriptors.d.ts +112 -0
  9. package/dist/analysis/descriptors.d.ts.map +1 -0
  10. package/dist/analysis/descriptors.js +248 -0
  11. package/dist/analysis/diagnostics.d.ts +45 -0
  12. package/dist/analysis/diagnostics.d.ts.map +1 -0
  13. package/dist/analysis/diagnostics.js +34 -0
  14. package/dist/analysis/index.d.ts +6 -0
  15. package/dist/analysis/index.d.ts.map +1 -0
  16. package/dist/analysis/index.js +2 -0
  17. package/dist/analysis/outline.d.ts +44 -0
  18. package/dist/analysis/outline.d.ts.map +1 -0
  19. package/dist/analysis/outline.js +301 -0
  20. package/dist/analysis/rank-suggestions.d.ts +21 -0
  21. package/dist/analysis/rank-suggestions.d.ts.map +1 -0
  22. package/dist/analysis/rank-suggestions.js +150 -0
  23. package/dist/analysis/repetition.d.ts +31 -0
  24. package/dist/analysis/repetition.d.ts.map +1 -0
  25. package/dist/analysis/repetition.js +105 -0
  26. package/dist/analysis/segmentation.d.ts +26 -0
  27. package/dist/analysis/segmentation.d.ts.map +1 -0
  28. package/dist/analysis/segmentation.js +81 -0
  29. package/dist/analysis/square-geometry.d.ts +34 -0
  30. package/dist/analysis/square-geometry.d.ts.map +1 -0
  31. package/dist/analysis/square-geometry.js +91 -0
  32. package/dist/analysis/surface-candidates.d.ts +45 -0
  33. package/dist/analysis/surface-candidates.d.ts.map +1 -0
  34. package/dist/analysis/surface-candidates.js +471 -0
  35. package/dist/analysis/thresholds.d.ts +189 -0
  36. package/dist/analysis/thresholds.d.ts.map +1 -0
  37. package/dist/analysis/thresholds.js +189 -0
  38. package/dist/analysis/types.d.ts +42 -0
  39. package/dist/analysis/types.d.ts.map +1 -0
  40. package/dist/analysis/types.js +2 -0
  41. package/dist/crops/crop-editor-state.d.ts +88 -0
  42. package/dist/crops/crop-editor-state.d.ts.map +1 -0
  43. package/dist/crops/crop-editor-state.js +121 -0
  44. package/dist/crops/crop-entries.d.ts +47 -0
  45. package/dist/crops/crop-entries.d.ts.map +1 -0
  46. package/dist/crops/crop-entries.js +46 -0
  47. package/dist/crops/crop-export.d.ts +21 -0
  48. package/dist/crops/crop-export.d.ts.map +1 -0
  49. package/dist/crops/crop-export.js +38 -0
  50. package/dist/crops/crop-geometry.d.ts +130 -0
  51. package/dist/crops/crop-geometry.d.ts.map +1 -0
  52. package/dist/crops/crop-geometry.js +271 -0
  53. package/dist/crops/crop-gesture.d.ts +175 -0
  54. package/dist/crops/crop-gesture.d.ts.map +1 -0
  55. package/dist/crops/crop-gesture.js +188 -0
  56. package/dist/crops/index.d.ts +10 -0
  57. package/dist/crops/index.d.ts.map +1 -0
  58. package/dist/crops/index.js +5 -0
  59. package/dist/index.d.ts +19 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +8 -0
  62. package/dist/surface-types.d.ts +41 -0
  63. package/dist/surface-types.d.ts.map +1 -0
  64. package/dist/surface-types.js +1 -0
  65. package/dist/worker/index.d.ts +4 -0
  66. package/dist/worker/index.d.ts.map +1 -0
  67. package/dist/worker/index.js +1 -0
  68. package/dist/worker/protocol.d.ts +28 -0
  69. package/dist/worker/protocol.d.ts.map +1 -0
  70. package/dist/worker/protocol.js +1 -0
  71. package/dist/worker/run-analysis.d.ts +21 -0
  72. package/dist/worker/run-analysis.d.ts.map +1 -0
  73. package/dist/worker/run-analysis.js +36 -0
  74. package/dist/worker/surface-worker.d.ts +2 -0
  75. package/dist/worker/surface-worker.d.ts.map +1 -0
  76. package/dist/worker/surface-worker.js +36 -0
  77. package/package.json +123 -3
@@ -0,0 +1,189 @@
1
+ // Every tunable number in the detector, grouped by the stage that uses it, each with its unit.
2
+ /**
3
+ * Trial values tuned by inspecting this prototype's example crops, not prescribed by the papers.
4
+ * "Analysis pixels" are pixels of the small analysis image (decode.ts), not of the source photo.
5
+ * "Descriptor distance" (descriptors.ts `descriptorDistance`) is how different two windows look: 1 means
6
+ * color, edge direction and edge strength together differ by one scale unit. "Material distance"
7
+ * (`materialDistance`) is a separate, lighting-tolerant measure used only to decide whether two finished
8
+ * crops show the same material. These are read when the detector runs, so the eval harness can patch them per run.
9
+ */
10
+ export const thresholds = {
11
+ /** Stage 3, fitting and checking one square per region. Lengths in analysis pixels, shares as fractions (0-1), tile counts as plain counts, dispersion in descriptor distance. */
12
+ crop: {
13
+ /**
14
+ * Largest feature distance between any window tiling the square and the square as a whole, or between any two windows.
15
+ * Squares that straddle materials or hold a lone object fail it; patterns whose windows agree pass.
16
+ */
17
+ dispersionLimit: 2,
18
+ /** Score lost at the limit, as a fraction: 0.5 means a square at the limit keeps half its size-based score. */
19
+ dispersionPenalty: 0.5,
20
+ /** Pixels eroded from a segment before the square is fitted: a pixel counts only if everything this close to it is in the segment. Window ownership is already conservative. */
21
+ erosionPixels: 1,
22
+ /**
23
+ * Repeat correlation (-1..1, `repeatsAtLeast`) a square must reach when its windows agree best once they are
24
+ * larger than every fixed scale (`descriptor.scales`), that is in halves of the square. Each half of a wide
25
+ * blend (blind, glass and sofa across a bay window) holds the same mix, so the halves agree; a large check or
26
+ * print agrees there too but also repeats. The cost: a frame-filling print whose repeat is longer than
27
+ * `repetition.maximumLag` gets a smaller crop. 0 is off.
28
+ */
29
+ halvesRepeatPeak: 0.45,
30
+ /** Share of the fitted square's side trimmed from each edge (0.04 is 4%), to stay clear of uncertain boundaries; the outline already keeps the fit conservative. */
31
+ insetFraction: 0.04,
32
+ /** Largest brightness-normalized chromaticity difference (unitless, as `material.chromaScale`) between any two windows, or a window and the whole, for the lighting relief. */
33
+ lightingChromaLimit: 0.15,
34
+ /** Largest edge-direction term (descriptor distance) of any comparison for the lighting relief. */
35
+ lightingOrientationLimit: 0.3,
36
+ /**
37
+ * Light changes a surface's brightness and edge strength but not its hue or edge directions, so a shaded
38
+ * wallpaper drifts across a square while its print stays put. When every window is textured, edge directions
39
+ * agree within `lightingOrientationLimit` and hue within `lightingChromaLimit`, the color term is divided by
40
+ * this. Only a second chance: it applies to a square that failed agreement and repeats at least
41
+ * `lightingRepeatPeak`, so squares that already pass are scored as before. 1 is off.
42
+ */
43
+ lightingRelief: 2,
44
+ /** Repeat correlation (-1..1, `repeatsAtLeast`) a failed square needs before the lighting relief is tried: a clear print, not a blend. */
45
+ lightingRepeatPeak: 0.6,
46
+ /** Mean gradient (8-bit intensity per pixel) every window needs for the relief; flat paint relies on color alone. */
47
+ lightingTextureEnergy: 3,
48
+ /** Most windows sampled per side when testing agreement; pairwise comparison is quadratic in their number. */
49
+ maximumTilesPerSide: 4,
50
+ /** Smallest crop side as a fraction of the image's shorter side. */
51
+ minimumSideFraction: 0.06,
52
+ /**
53
+ * Windows per side a square must hold at the scale used to test agreement. Two is the least that gives
54
+ * a comparison at all (four windows); it is weak evidence, so `thinEvidencePenalty` tightens the limit there.
55
+ * A mixture whose parts straddle the windows evenly can still agree; in halves of a large square, `halvesRepeatPeak` catches it.
56
+ */
57
+ minimumTiles: 2,
58
+ /** Fraction of the dispersion limit withheld, scaled by 1 / (tiles - 1): 20% at two tiles, 10% at three, so thin evidence must agree more tightly. */
59
+ thinEvidencePenalty: 0.2,
60
+ },
61
+ /** Stage 1, describing windows. Window sides in analysis pixels; the scales turn each term of `descriptorDistance` into "one unit". */
62
+ descriptor: {
63
+ /** Color histogram bins per channel (count): 32 bins is 8 of the 256 levels each. */
64
+ colorBins: 32,
65
+ /** 8-bit levels (0-255): the mean per-channel color shift that counts as one unit of descriptor distance. */
66
+ colorScale: 20,
67
+ /** Natural-log units of edge-strength ratio that count as one unit: 0.6 is about a 1.8x difference. */
68
+ energyScale: 0.6,
69
+ /** Mean gradient (8-bit intensity per pixel) below which a window counts as flat; also added to both energies in the ratio, and edge direction counts fully only above twice this. */
70
+ noiseEnergy: 1.5,
71
+ /** Edge-direction bins over half a turn (count): 8 bins is 22.5 degrees each. */
72
+ orientationBins: 8,
73
+ /** Edge-direction chi-square distance (0-1) that counts as one unit of descriptor distance. */
74
+ orientationScale: 0.15,
75
+ /** Window sides in analysis pixels, overlapping by half. A window must span a pattern period to describe it; 96 reaches large inlays and slat repeats. */
76
+ scales: [8, 16, 32, 48, 64, 96],
77
+ },
78
+ /** Image limits, in analysis pixels except `opaqueAlpha`. */
79
+ input: {
80
+ /** Longest side of the analysis image, in pixels; the shared decoder (decode.ts) shrinks photos to this and never upscales. */
81
+ analysisSide: 320,
82
+ /** Shortest side the detector accepts, in pixels; a smaller image gets no suggestions. */
83
+ minimumSide: 16,
84
+ /** 8-bit alpha (0-255) at or above which a pixel counts as opaque; a window or square with any other pixel is rejected. */
85
+ opaqueAlpha: 250,
86
+ },
87
+ /** Stage 4, `materialDistance`: unitless terms divided by these scales, fitted on labeled same/different-surface pairs. */
88
+ material: {
89
+ /** Brightness-normalized chromaticity distance (red-green and yellow-blue axes together, unitless) that counts as one unit. */
90
+ chromaScale: 0.16,
91
+ /** Added to each square's contrast (edge strength relative to brightness, unitless) before the log ratio, so flat squares compare finitely. */
92
+ contrastFloor: 0.02,
93
+ /** 8-bit luminance levels added to mean luminance when dividing edge strength by it (contrast), for the same reason. */
94
+ contrastOffset: 16,
95
+ /** Natural-log units of contrast ratio that count as one unit: 0.6 is about a 1.8x difference. */
96
+ contrastScale: 0.6,
97
+ /** 8-bit luminance levels added to a square's mean luminance before taking its log, so near-black squares do not blow up. */
98
+ lightnessOffset: 8,
99
+ /** Natural-log luminance units: 0.44 means a 1.55x brightness ratio counts as one unit. Lighting changes this term most, so it is the loosest of the four. */
100
+ lightnessScale: 0.44,
101
+ /** Edge-direction chi-square distance (0-1) that counts as one unit; looser than the window-level `descriptor.orientationScale`. */
102
+ orientationScale: 0.5,
103
+ },
104
+ /** Stage 5, drawing the outline. Analysis pixels, except `sigmaCells` (window cells) and `minimumLoopFraction` (share of the image area). */
105
+ outline: {
106
+ /** Cap on the blur sigma, in analysis pixels. */
107
+ maximumSigma: 10,
108
+ /** Loops (outer or hole) smaller than this share of the image are dropped as specks. */
109
+ minimumLoopFraction: 0.002,
110
+ /** Blur sigma in window cells (half a window side), capped in analysis pixels so large cells do not erase shape. */
111
+ sigmaCells: 1,
112
+ /** Ramer-Douglas-Peucker tolerance in analysis pixels, before curves are fitted. */
113
+ simplifyTolerance: 0.5,
114
+ },
115
+ /** Stage 3, `sampleQuality`: luminance in 8-bit levels (0-255), shares as fractions of a square's pixels, and unitless information terms. Three 0-1 factors multiply. */
116
+ quality: {
117
+ /** Luminance counted as clipped (cream paper and pale stone sit below it). */
118
+ blownLuma: 250,
119
+ /** Extra share of clipped pixels, beyond `blownTolerance`, over which the unclipped factor falls from 1 to 0. */
120
+ blownSpan: 0.4,
121
+ /** Share of clipped pixels tolerated with no penalty. */
122
+ blownTolerance: 0.05,
123
+ /** Mean channel spread (max minus min, 8-bit levels) that alone makes a square fully informative. */
124
+ chromaScale: 25,
125
+ /** Mean luminance (0-255) at or below which a square is useless, and the span over which it recovers fully. */
126
+ darkFloor: 25,
127
+ darkSpan: 35,
128
+ /** Information: edge energy (as a share of the noise floor) plus mean channel spread over this scale. */
129
+ energyShare: 1,
130
+ /** Squares scoring below this are dropped; above it quality scales the score. */
131
+ minimum: 0.2,
132
+ },
133
+ /** Stage 4, ranking: fractions of crop area or side, a count for `suggestionLimit`, and material-distance units for the duplicate terms. */
134
+ ranking: {
135
+ /** Two crops are one material when material distance - sizeWeight x ln(size ratio) is below this (material-distance units). */
136
+ duplicateThreshold: 0.7,
137
+ /** Share of an inner crop's area (0-1) that must lie inside a larger crop for it to count as mixture evidence there. */
138
+ mixtureContainment: 0.9,
139
+ /**
140
+ * A crop holding two smaller passing crops of clearly different materials is a mixture, however well its own
141
+ * coarse windows agree (each quarter can hold the same blend of blind, glass and sofa). Dropped when two such
142
+ * inner crops are further apart than this in material distance, eased by `sizeWeight` like duplicates. Infinity is off.
143
+ */
144
+ mixtureDistance: 2,
145
+ /**
146
+ * Smallest inner crop counted as mixture evidence, as a share of the outer crop's side; tinier ones sample edges
147
+ * and specks. A trade-off: at 0.1 single pieces of a large inlay count, so the inlaid stone floor's crop shrinks
148
+ * from 218 to 160 analysis pixels; at 0.15 it stays 218, but the bay-window blend of blind, glass and sofa
149
+ * (whose pure parts are 0.1-0.2 of it) comes back as the top crop. A pure smaller crop is preferred.
150
+ */
151
+ mixtureInnerSide: 0.1,
152
+ /** Overlap area as a fraction of the smaller crop's area; above it the lower-scoring crop is dropped. */
153
+ overlapFraction: 0.5,
154
+ /** A crop under this share of the best crop's side is dropped: beside a frame-filling crop, small ones only sample its margins or the backdrop. */
155
+ relativeSide: 0.25,
156
+ /** Homogeneity weight when choosing which of two look-alike crops to keep; heavier than in the ranking score, since a clean crop beats a bigger straddling one. */
157
+ representativePenalty: 1,
158
+ /** Material-distance units forgiven per unit of ln(size ratio), because a close-up of a texture drifts from the wide view: a crop half the size gets about 0.2 off. */
159
+ sizeWeight: 0.3,
160
+ /** Most suggestions returned (count). */
161
+ suggestionLimit: 7,
162
+ },
163
+ /** Labeling a square as repeating (repetition.ts). Analysis pixels for shifts and subsampling; correlations are unitless (-1..1). */
164
+ repetition: {
165
+ /** The largest shift is also capped at the square's side divided by this, so 3 means a third of the side. */
166
+ cropLagDivisor: 3,
167
+ /** Largest shift tried, in analysis pixels. */
168
+ maximumLag: 36,
169
+ /** Smallest shift tried when looking for a recovered peak. Neighboring pixels (shifts of 1-2) always correlate, so they say nothing about a repeat. */
170
+ minimumLag: 3,
171
+ /** Correlation a peak must exceed. Rejects smooth gradients. */
172
+ minimumPeak: 0.45,
173
+ /** How far the peak must rise above the lowest correlation seen at smaller shifts (from 2 up). Rejects smooth gradients. */
174
+ minimumRecovery: 0.25,
175
+ /** Every nth pixel is read in each direction when correlating, to save time (analysis pixels). */
176
+ sampleStep: 2,
177
+ },
178
+ /** Stage 2, segmentation. Descriptor-distance units unless stated; `minimumWindows` is a count of windows. */
179
+ segmentation: {
180
+ /** Adaptive size term k: a region of n windows tolerates k / n extra internal distance, so small regions join freely. */
181
+ componentScale: 4,
182
+ /** Hard cap on the descriptor distance that may join two windows. */
183
+ mergeLimit: 1.5,
184
+ /** A segment needs this many windows before its square is considered. */
185
+ minimumWindows: 4,
186
+ /** Touching segments whose mean descriptors are closer than this are joined before squares are fitted. */
187
+ regionMergeDistance: 1,
188
+ },
189
+ };
@@ -0,0 +1,42 @@
1
+ /** Geometry in percent coordinates: 0-100 of the source photo's width and height, so the detector never needs the source size. */
2
+ export interface PercentRectangle {
3
+ x: number;
4
+ y: number;
5
+ width: number;
6
+ height: number;
7
+ }
8
+ /** A visual-region proposal, not an identified material or a promise of crop purity. */
9
+ export interface SurfaceSuggestion {
10
+ /** Unique within one result: `surface-1`, `surface-2`, ... in rank order. */
11
+ id: string;
12
+ /** Percent coordinates (0-100). Width and height differ in percent unless the photo is square, but form a pixel square. */
13
+ crop: PercentRectangle;
14
+ /** Region outline for an SVG with viewBox="0 0 100 100"; preserves holes. */
15
+ path: string;
16
+ /** Fraction of analyzed pixels covered by the detected region, not by the crop. */
17
+ coverage: number;
18
+ /** Ranking heuristic: the crop's side as a share of the image, lowered when its parts disagree and when it is a poor sample. Higher is better; not calibrated confidence or material accuracy. */
19
+ score: number;
20
+ /** The visual evidence used to propose the region; no semantic material category is inferred. */
21
+ basis: "colour" | "texture" | "repetition";
22
+ /** Always "square" for now. */
23
+ shape: "square";
24
+ /** Largest square in source percentages that passes the same opacity, agreement and quality checks as `crop`; equals `crop` when the larger square fails them. */
25
+ maxCrop: PercentRectangle;
26
+ }
27
+ /** Internal geometry: integer pixels in the downsampled analysis image, from the top-left corner. */
28
+ export interface PixelRectangle {
29
+ x: number;
30
+ y: number;
31
+ width: number;
32
+ height: number;
33
+ }
34
+ /** Short alias for `PixelRectangle`, used inside the analysis files. */
35
+ export type Rectangle = PixelRectangle;
36
+ /** The analysis image: row-major 8-bit RGBA (four values per pixel) at the resolution the caller chose, normally from `decodePhoto`. */
37
+ export interface AnalysisImage {
38
+ width: number;
39
+ height: number;
40
+ data: Uint8ClampedArray;
41
+ }
42
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/analysis/types.ts"],"names":[],"mappings":"AAEA,kIAAkI;AAClI,MAAM,WAAW,gBAAgB;IAC/B,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,wFAAwF;AACxF,MAAM,WAAW,iBAAiB;IAChC,6EAA6E;IAC7E,EAAE,EAAE,MAAM,CAAC;IACX,2HAA2H;IAC3H,IAAI,EAAE,gBAAgB,CAAC;IACvB,6EAA6E;IAC7E,IAAI,EAAE,MAAM,CAAC;IACb,mFAAmF;IACnF,QAAQ,EAAE,MAAM,CAAC;IACjB,kMAAkM;IAClM,KAAK,EAAE,MAAM,CAAC;IACd,iGAAiG;IACjG,KAAK,EAAE,QAAQ,GAAG,SAAS,GAAG,YAAY,CAAC;IAC3C,+BAA+B;IAC/B,KAAK,EAAE,QAAQ,CAAC;IAChB,kKAAkK;IAClK,OAAO,EAAE,gBAAgB,CAAC;CAC3B;AAED,qGAAqG;AACrG,MAAM,WAAW,cAAc;IAC7B,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB;AACD,wEAAwE;AACxE,MAAM,MAAM,SAAS,GAAG,cAAc,CAAC;AAEvC,wIAAwI;AACxI,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,iBAAiB,CAAC;CACzB"}
@@ -0,0 +1,2 @@
1
+ // Shared types for the analysis boundary (pixels in, percentage crops out).
2
+ export {};
@@ -0,0 +1,88 @@
1
+ import type { LiveEdit, UserCrop } from "./crop-entries.js";
2
+ import type { PixelCrop } from "./crop-geometry.js";
3
+ /**
4
+ * What the screen-reader live region last said, kept as data rather than text
5
+ * so the words can follow the numbering (crops are renumbered when one is removed).
6
+ */
7
+ export type Announcement = {
8
+ kind: "box";
9
+ id: string;
10
+ width: number;
11
+ height: number;
12
+ } | {
13
+ kind: "reset";
14
+ id: string;
15
+ } | {
16
+ kind: "removed";
17
+ };
18
+ /**
19
+ * Everything the user has changed about one opened photo. Crops are keyed by
20
+ * ID, never by position. It holds no detector output: `buildEntries` combines
21
+ * this with the suggestions.
22
+ */
23
+ export interface EditorState {
24
+ sessionId: number;
25
+ /** The crop the user is looking at, or null for none: every crop then reads alike. */
26
+ selectedId: string | null;
27
+ hoveredId: string | null;
28
+ /** IDs of suggestions showing their largest square. */
29
+ expanded: ReadonlySet<string>;
30
+ /** Squares the user adjusted, by suggestion ID. Drawn crops are edited in `drawn` instead. */
31
+ overrides: Readonly<Record<string, PixelCrop>>;
32
+ drawn: UserCrop[];
33
+ /** Crops drawn so far, including removed ones, so IDs are never reused. */
34
+ drawnCount: number;
35
+ /** The square being dragged right now, not yet committed. */
36
+ live: LiveEdit | null;
37
+ announcement: Announcement | null;
38
+ }
39
+ /** A clean state for a photo: nothing selected, adjusted, drawn or expanded. */
40
+ export declare const initialEditorState: (sessionId: number) => EditorState;
41
+ /**
42
+ * Every change the editor accepts. Each carries the `sessionId` it was made in,
43
+ * so a late action from a photo the user has since left can be recognized and dropped.
44
+ * `preview` shows a drag in progress (null clears it); `commit` keeps an adjustment.
45
+ */
46
+ export type EditorAction = {
47
+ sessionId: number;
48
+ } &
49
+ /** `id` null clears the selection. */
50
+ ({
51
+ type: "select";
52
+ id: string | null;
53
+ } | {
54
+ type: "hover";
55
+ id: string | null;
56
+ } | {
57
+ type: "preview";
58
+ id: string;
59
+ box: PixelCrop | null;
60
+ } | {
61
+ type: "commit";
62
+ id: string;
63
+ box: PixelCrop;
64
+ } | {
65
+ type: "draw";
66
+ box: PixelCrop;
67
+ } | {
68
+ type: "toggleExpand";
69
+ id: string;
70
+ } | {
71
+ type: "reset";
72
+ id: string;
73
+ } | {
74
+ type: "clearAnnouncement";
75
+ }
76
+ /** `next` is the crop to select afterwards, chosen by whoever can see the order. */
77
+ | {
78
+ type: "remove";
79
+ id: string;
80
+ next: string | null;
81
+ });
82
+ /**
83
+ * Edits belong to one session (one opened photo). An action from an older
84
+ * session is dropped; the first action of a newer one starts from a clean slate.
85
+ * Session IDs only go up, which is what makes "older" and "newer" meaningful.
86
+ */
87
+ export declare const editorReducer: (state: EditorState, action: EditorAction) => EditorState;
88
+ //# sourceMappingURL=crop-editor-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crop-editor-state.d.ts","sourceRoot":"","sources":["../../src/crops/crop-editor-state.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAEpD;;;GAGG;AACH,MAAM,MAAM,YAAY,GACpB;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAC1D;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GAC7B;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC;AAExB;;;;GAIG;AACH,MAAM,WAAW,WAAW;IAC1B,SAAS,EAAE,MAAM,CAAC;IAClB,sFAAsF;IACtF,UAAU,EAAE,MAAM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AAE;AAC/B,oFAAoF;GAClF;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CACtD,CAAC;AA6GJ;;;;GAIG;AACH,eAAO,MAAM,aAAa,UACjB,WAAW,UACV,YAAY,KACnB,WASF,CAAC"}
@@ -0,0 +1,121 @@
1
+ /** A clean state for a photo: nothing selected, adjusted, drawn or expanded. */
2
+ export const initialEditorState = (sessionId) => ({
3
+ announcement: null,
4
+ drawn: [],
5
+ drawnCount: 0,
6
+ expanded: new Set(),
7
+ hoveredId: null,
8
+ live: null,
9
+ overrides: {},
10
+ selectedId: null,
11
+ sessionId,
12
+ });
13
+ const boxAnnouncement = (id, box) => ({
14
+ height: box.height,
15
+ id,
16
+ kind: "box",
17
+ width: box.width,
18
+ });
19
+ /** A drawn crop is edited in place; a suggestion keeps its adjustment as an override. */
20
+ const commitEdit = (state, id, box) => {
21
+ const isDrawn = state.drawn.some((item) => item.id === id);
22
+ return {
23
+ ...state,
24
+ announcement: boxAnnouncement(id, box),
25
+ drawn: isDrawn
26
+ ? state.drawn.map((item) => (item.id === id ? { ...item, box } : item))
27
+ : state.drawn,
28
+ live: null,
29
+ overrides: isDrawn ? state.overrides : { ...state.overrides, [id]: box },
30
+ };
31
+ };
32
+ /** Adds a drawn crop with the next ID (`user-1`, `user-2`, ...) and selects it. */
33
+ const drawCrop = (state, box) => {
34
+ const drawnCount = state.drawnCount + 1;
35
+ const id = `user-${drawnCount}`;
36
+ return {
37
+ ...state,
38
+ announcement: boxAnnouncement(id, box),
39
+ drawn: [...state.drawn, { box, id }],
40
+ drawnCount,
41
+ live: null,
42
+ selectedId: id,
43
+ };
44
+ };
45
+ const reduceInSession = (state, action) => {
46
+ switch (action.type) {
47
+ case "select": {
48
+ return state.selectedId === action.id
49
+ ? state
50
+ : { ...state, selectedId: action.id };
51
+ }
52
+ case "hover": {
53
+ // Mouse moves report hover constantly; an unchanged value must not re-render.
54
+ return state.hoveredId === action.id
55
+ ? state
56
+ : { ...state, hoveredId: action.id };
57
+ }
58
+ case "preview": {
59
+ if (action.box === null) {
60
+ return state.live === null ? state : { ...state, live: null };
61
+ }
62
+ return { ...state, live: { box: action.box, id: action.id } };
63
+ }
64
+ case "commit": {
65
+ return commitEdit(state, action.id, action.box);
66
+ }
67
+ case "draw": {
68
+ return drawCrop(state, action.box);
69
+ }
70
+ case "toggleExpand": {
71
+ const expanded = new Set(state.expanded);
72
+ if (expanded.has(action.id)) {
73
+ expanded.delete(action.id);
74
+ }
75
+ else {
76
+ expanded.add(action.id);
77
+ }
78
+ return { ...state, expanded };
79
+ }
80
+ case "reset": {
81
+ // Back to the suggestion's own square: forget both the expansion and the adjustment.
82
+ const expanded = new Set(state.expanded);
83
+ expanded.delete(action.id);
84
+ return {
85
+ ...state,
86
+ announcement: { id: action.id, kind: "reset" },
87
+ expanded,
88
+ overrides: Object.fromEntries(Object.entries(state.overrides).filter(([id]) => id !== action.id)),
89
+ };
90
+ }
91
+ case "clearAnnouncement": {
92
+ return { ...state, announcement: null };
93
+ }
94
+ case "remove": {
95
+ return {
96
+ ...state,
97
+ announcement: { kind: "removed" },
98
+ drawn: state.drawn.filter((item) => item.id !== action.id),
99
+ live: null,
100
+ selectedId: action.next,
101
+ };
102
+ }
103
+ default: {
104
+ return action;
105
+ }
106
+ }
107
+ };
108
+ /**
109
+ * Edits belong to one session (one opened photo). An action from an older
110
+ * session is dropped; the first action of a newer one starts from a clean slate.
111
+ * Session IDs only go up, which is what makes "older" and "newer" meaningful.
112
+ */
113
+ export const editorReducer = (state, action) => {
114
+ if (action.sessionId < state.sessionId) {
115
+ return state;
116
+ }
117
+ const base = action.sessionId === state.sessionId
118
+ ? state
119
+ : initialEditorState(action.sessionId);
120
+ return reduceInSession(base, action);
121
+ };
@@ -0,0 +1,47 @@
1
+ import type { SurfaceSuggestion } from "../analysis/analyze-surface-regions.js";
2
+ import type { ImageSize, PixelCrop } from "./crop-geometry.js";
3
+ /** A crop the user drew; its square is stored in source pixels. */
4
+ export interface UserCrop {
5
+ id: string;
6
+ box: PixelCrop;
7
+ }
8
+ /**
9
+ * One selectable crop: a suggestion (possibly adjusted or expanded) or a drawn
10
+ * one. Positions are in source pixels. Crops are matched by `id`, never by position.
11
+ */
12
+ export interface CropEntry {
13
+ id: string;
14
+ /** Why the detector proposed it (color, texture or repetition). Null for a crop the user drew. */
15
+ basis: SurfaceSuggestion["basis"] | null;
16
+ /** Detected-region outline in a 0-100 viewBox; null for a drawn crop. */
17
+ path: string | null;
18
+ /** The square used for the preview, tile and export, in source pixels. */
19
+ box: PixelCrop;
20
+ /** The suggestion's own square, which snapping and Reset return to. */
21
+ home: PixelCrop | null;
22
+ /** The largest square the suggestion allows (its own when expanding is unsafe). */
23
+ reach: PixelCrop | null;
24
+ /** True for a crop the user drew. */
25
+ user: boolean;
26
+ /** The user has dragged, resized or nudged it. Takes over from `expanded`. */
27
+ adjusted: boolean;
28
+ /** `box` is currently `reach`. Never true together with `adjusted`. */
29
+ expanded: boolean;
30
+ /** Expand would change something: not adjusted, and `reach` is larger than `home`. */
31
+ expandable: boolean;
32
+ }
33
+ /** The selected crop's square while it is being dragged, before it is committed. */
34
+ export interface LiveEdit {
35
+ id: string;
36
+ box: PixelCrop;
37
+ }
38
+ /**
39
+ * Suggestions first, then the crops the user drew, each with its adjustments
40
+ * applied. A suggestion's square is the user's adjustment if there is one, else
41
+ * its largest square if expanded, else its own. This is where the detector's
42
+ * percent coordinates become source pixels (`size` is the source photo).
43
+ */
44
+ export declare const buildEntries: (suggestions: SurfaceSuggestion[], size: ImageSize, expanded: ReadonlySet<string>, overrides: Readonly<Record<string, PixelCrop>>, drawn: UserCrop[]) => CropEntry[];
45
+ /** The entries as they look right now: the one being dragged shows its live square. */
46
+ export declare const withLive: (entries: CropEntry[], live: LiveEdit | null) => CropEntry[];
47
+ //# sourceMappingURL=crop-entries.d.ts.map
@@ -0,0 +1 @@
1
+ {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G,IAAI,KACpB,SAAS,EAKL,CAAC"}
@@ -0,0 +1,46 @@
1
+ import { canExpand, cropPixels } from "./crop-geometry.js";
2
+ /**
3
+ * Suggestions first, then the crops the user drew, each with its adjustments
4
+ * applied. A suggestion's square is the user's adjustment if there is one, else
5
+ * its largest square if expanded, else its own. This is where the detector's
6
+ * percent coordinates become source pixels (`size` is the source photo).
7
+ */
8
+ export const buildEntries = (suggestions, size, expanded, overrides, drawn) => {
9
+ const entries = suggestions.map((item) => {
10
+ const home = cropPixels(item.crop, size, true);
11
+ const reach = cropPixels(item.maxCrop, size, true);
12
+ const override = overrides[item.id];
13
+ const isExpanded = expanded.has(item.id);
14
+ return {
15
+ adjusted: override !== undefined,
16
+ basis: item.basis,
17
+ box: override ?? (isExpanded ? reach : home),
18
+ expandable: override === undefined && canExpand(item, size),
19
+ expanded: isExpanded && override === undefined,
20
+ home,
21
+ id: item.id,
22
+ path: item.path,
23
+ reach,
24
+ user: false,
25
+ };
26
+ });
27
+ for (const crop of drawn) {
28
+ entries.push({
29
+ adjusted: false,
30
+ basis: null,
31
+ box: crop.box,
32
+ expandable: false,
33
+ expanded: false,
34
+ home: null,
35
+ id: crop.id,
36
+ path: null,
37
+ reach: null,
38
+ user: true,
39
+ });
40
+ }
41
+ return entries;
42
+ };
43
+ /** The entries as they look right now: the one being dragged shows its live square. */
44
+ export const withLive = (entries, live) => live === null
45
+ ? entries
46
+ : entries.map((entry) => entry.id === live.id ? { ...entry, box: live.box } : entry);
@@ -0,0 +1,21 @@
1
+ import type { PixelCrop } from "./crop-geometry.js";
2
+ /**
3
+ * The pixel size an exported crop is drawn at. Without `maxSide` it is the
4
+ * crop itself; with it, the crop is scaled down (never up) so its longer side
5
+ * is at most `maxSide`.
6
+ */
7
+ export declare const exportSize: (box: PixelCrop, maxSide?: number) => {
8
+ height: number;
9
+ width: number;
10
+ };
11
+ /**
12
+ * Export exactly the pixels the preview shows: no overlays, scaling or padding.
13
+ * `box` is in source pixels and `bitmap` must be the full-size source photo, not
14
+ * the small analysis copy. JPEG quality is 0.95. Resolves to null if the browser
15
+ * cannot encode the image, and throws if a canvas is unavailable.
16
+ *
17
+ * `maxSide` scales the result down for uses that do not need every pixel (a
18
+ * search request); downloads leave it out and get the crop at full size.
19
+ */
20
+ export declare const exportCrop: (bitmap: ImageBitmap, box: PixelCrop, maxSide?: number) => Promise<Blob | null>;
21
+ //# sourceMappingURL=crop-export.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crop-export.d.ts","sourceRoot":"","sources":["../../src/crops/crop-export.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAEpD;;;;GAIG;AACH,eAAO,MAAM,UAAU,QAAS,SAAS,YAAY,MAAM;IAMvD,MAAM;IACN,KAAK;CAER,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,UAAU,WACb,WAAW,OACd,SAAS,YACJ,MAAM,KACf,OAAO,CAAC,IAAI,GAAG,IAAI,CAwBrB,CAAC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The pixel size an exported crop is drawn at. Without `maxSide` it is the
3
+ * crop itself; with it, the crop is scaled down (never up) so its longer side
4
+ * is at most `maxSide`.
5
+ */
6
+ export const exportSize = (box, maxSide) => {
7
+ const scale = maxSide === undefined
8
+ ? 1
9
+ : Math.min(1, maxSide / Math.max(box.width, box.height));
10
+ return {
11
+ height: Math.max(1, Math.round(box.height * scale)),
12
+ width: Math.max(1, Math.round(box.width * scale)),
13
+ };
14
+ };
15
+ /**
16
+ * Export exactly the pixels the preview shows: no overlays, scaling or padding.
17
+ * `box` is in source pixels and `bitmap` must be the full-size source photo, not
18
+ * the small analysis copy. JPEG quality is 0.95. Resolves to null if the browser
19
+ * cannot encode the image, and throws if a canvas is unavailable.
20
+ *
21
+ * `maxSide` scales the result down for uses that do not need every pixel (a
22
+ * search request); downloads leave it out and get the crop at full size.
23
+ */
24
+ export const exportCrop = async (bitmap, box, maxSide) => {
25
+ const size = exportSize(box, maxSide);
26
+ const canvas = document.createElement("canvas");
27
+ canvas.width = size.width;
28
+ canvas.height = size.height;
29
+ const context = canvas.getContext("2d");
30
+ if (context === null) {
31
+ throw new Error("Canvas unavailable");
32
+ }
33
+ context.imageSmoothingQuality = "high";
34
+ context.drawImage(bitmap, box.x, box.y, box.width, box.height, 0, 0, size.width, size.height);
35
+ return await new Promise((resolve) => {
36
+ canvas.toBlob(resolve, "image/jpeg", 0.95);
37
+ });
38
+ };