Debian Codegraph @

packages/datagrid/src/imagerenderer.ts

raw
1 // Copyright (c) Jupyter Development Team.
2 // Distributed under the terms of the Modified BSD License.
3 /*-----------------------------------------------------------------------------
4 | Copyright (c) 2014-2023, Lumino Contributors
5 |
6 | Distributed under the terms of the BSD 3-Clause License.
7 |
8 | The full license is in the file LICENSE, distributed with this software.
9 |----------------------------------------------------------------------------*/
10 import { PromiseDelegate } from '@lumino/coreutils';
11 import { AsyncCellRenderer } from './asynccellrenderer';
12 import { CellRenderer } from './cellrenderer';
13
14 import { GraphicsContext } from './graphicscontext';
15
16 const PERCENTAGE_REGEX = /^(\d+(\.\d+)?)%$/;
17 const PIXEL_REGEX = /^(\d+(\.\d+)?)px$/;
18
19 /**
20 * A cell renderer which renders data values as images.
21 */
22 export class ImageRenderer extends AsyncCellRenderer {
23 /**
24 * Construct a new text renderer.
25 *
26 * @param options - The options for initializing the renderer.
27 */
28 constructor(options: ImageRenderer.IOptions = {}) {
29 super();
30
31 this.backgroundColor = options.backgroundColor || '';
32 this.textColor = options.textColor || '#000000';
33 this.placeholder = options.placeholder || '...';
34
35 this.width = options.width || '';
36 // Not using the || operator, because the empty string '' is a valid value
37 this.height = options.height === undefined ? '100%' : options.height;
38 }
39
40 /**
41 * The CSS color for drawing the placeholder text.
42 */
43 readonly textColor: CellRenderer.ConfigOption<string>;
44
45 /**
46 * The CSS color for the cell background.
47 */
48 readonly backgroundColor: CellRenderer.ConfigOption<string>;
49
50 /**
51 * The placeholder text.
52 */
53 readonly placeholder: CellRenderer.ConfigOption<string>;
54
55 /**
56 * The width of the image.
57 */
58 readonly width: CellRenderer.ConfigOption<string>;
59
60 /**
61 * The height of the image.
62 */
63 readonly height: CellRenderer.ConfigOption<string>;
64
65 /**
66 * Whether the renderer is ready or not for that specific config.
67 * If it's not ready, the datagrid will paint the placeholder.
68 * If it's ready, the datagrid will paint the image synchronously.
69 *
70 * @param config - The configuration data for the cell.
71 *
72 * @returns Whether the renderer is ready for this config or not.
73 */
74 isReady(config: CellRenderer.CellConfig): boolean {
75 return (
76 !config.value || ImageRenderer.dataCache.get(config.value) !== undefined
77 );
78 }
79
80 /**
81 * Load the image asynchronously for a specific config.
82 *
83 * @param config - The configuration data for the cell.
84 */
85 async load(config: CellRenderer.CellConfig): Promise<void> {
86 // Bail early if there is nothing to do
87 if (!config.value) {
88 return;
89 }
90
91 const value = config.value;
92 const loadedPromise = new PromiseDelegate<void>();
93
94 ImageRenderer.dataCache.set(value, undefined);
95
96 const img = new Image();
97 img.onload = () => {
98 ImageRenderer.dataCache.set(value, img);
99
100 loadedPromise.resolve();
101 };
102 img.src = value;
103
104 return loadedPromise.promise;
105 }
106
107 /**
108 * Paint the placeholder for a cell, waiting for the renderer to be ready.
109 *
110 * @param gc - The graphics context to use for drawing.
111 *
112 * @param config - The configuration data for the cell.
113 */
114 paintPlaceholder(gc: GraphicsContext, config: CellRenderer.CellConfig): void {
115 this.drawBackground(gc, config);
116 this.drawPlaceholder(gc, config);
117 }
118
119 /**
120 * Paint the content for a cell.
121 *
122 * @param gc - The graphics context to use for drawing.
123 *
124 * @param config - The configuration data for the cell.
125 */
126 paint(gc: GraphicsContext, config: CellRenderer.CellConfig): void {
127 this.drawBackground(gc, config);
128 this.drawImage(gc, config);
129 }
130
131 /**
132 * Draw the background for the cell.
133 *
134 * @param gc - The graphics context to use for drawing.
135 *
136 * @param config - The configuration data for the cell.
137 */
138 drawBackground(gc: GraphicsContext, config: CellRenderer.CellConfig): void {
139 // Resolve the background color for the cell.
140 const color = CellRenderer.resolveOption(this.backgroundColor, config);
141
142 // Bail if there is no background color to draw.
143 if (!color) {
144 return;
145 }
146
147 // Fill the cell with the background color.
148 gc.fillStyle = color;
149 gc.fillRect(config.x, config.y, config.width, config.height);
150 }
151
152 /**
153 * Draw the placeholder for the cell.
154 *
155 * @param gc - The graphics context to use for drawing.
156 *
157 * @param config - The configuration data for the cell.
158 */
159 drawPlaceholder(gc: GraphicsContext, config: CellRenderer.CellConfig): void {
160 const placeholder = CellRenderer.resolveOption(this.placeholder, config);
161 const color = CellRenderer.resolveOption(this.textColor, config);
162
163 const textX = config.x + config.width / 2;
164 const textY = config.y + config.height / 2;
165
166 // Draw the placeholder.
167 gc.fillStyle = color;
168 gc.fillText(placeholder, textX, textY);
169 }
170
171 /**
172 * Draw the image for the cell.
173 *
174 * @param gc - The graphics context to use for drawing.
175 *
176 * @param config - The configuration data for the cell.
177 */
178 drawImage(gc: GraphicsContext, config: CellRenderer.CellConfig): void {
179 // Bail early if there is nothing to draw
180 if (!config.value) {
181 return;
182 }
183
184 const img = ImageRenderer.dataCache.get(config.value);
185
186 // If it's not loaded yet, show the placeholder
187 if (!img) {
188 return this.drawPlaceholder(gc, config);
189 }
190
191 const width = CellRenderer.resolveOption(this.width, config);
192 const height = CellRenderer.resolveOption(this.height, config);
193
194 // width and height are unset, we display the image with its original size
195 if (!width && !height) {
196 gc.drawImage(img, config.x, config.y);
197 return;
198 }
199
200 let requestedWidth = img.width;
201 let requestedHeight = img.height;
202
203 let widthPercentageMatch: RegExpMatchArray | null;
204 let widthPixelMatch: RegExpMatchArray | null;
205 let heightPercentageMatch: RegExpMatchArray | null;
206 let heightPixelMatch: RegExpMatchArray | null;
207
208 if ((widthPercentageMatch = width.match(PERCENTAGE_REGEX))) {
209 requestedWidth =
210 (parseFloat(widthPercentageMatch[1]) / 100) * config.width;
211 } else if ((widthPixelMatch = width.match(PIXEL_REGEX))) {
212 requestedWidth = parseFloat(widthPixelMatch[1]);
213 }
214
215 if ((heightPercentageMatch = height.match(PERCENTAGE_REGEX))) {
216 requestedHeight =
217 (parseFloat(heightPercentageMatch[1]) / 100) * config.height;
218 } else if ((heightPixelMatch = height.match(PIXEL_REGEX))) {
219 requestedHeight = parseFloat(heightPixelMatch[1]);
220 }
221
222 // If width is not set, we compute it respecting the image size ratio
223 if (!width) {
224 requestedWidth = (img.width / img.height) * requestedHeight;
225 }
226
227 // If height is not set, we compute it respecting the image size ratio
228 if (!height) {
229 requestedHeight = (img.height / img.width) * requestedWidth;
230 }
231
232 gc.drawImage(img, config.x, config.y, requestedWidth, requestedHeight);
233 }
234
235 private static dataCache = new Map<string, HTMLImageElement | undefined>();
236 }
237
238 /**
239 * The namespace for the `ImageRenderer` class statics.
240 */
241 export namespace ImageRenderer {
242 /**
243 * An options object for initializing an image renderer.
244 */
245 export interface IOptions {
246 /**
247 * The background color for the cells.
248 *
249 * The default is `''`.
250 */
251 backgroundColor?: CellRenderer.ConfigOption<string>;
252
253 /**
254 * The placeholder text while the cell is loading.
255 *
256 * The default is `'...'`.
257 */
258 placeholder?: CellRenderer.ConfigOption<string>;
259
260 /**
261 * The color for the drawing the placeholder text.
262 *
263 * The default is `'#000000'`.
264 */
265 textColor?: CellRenderer.ConfigOption<string>;
266
267 /**
268 * The width of the image. Can be a percentage of the available space (e.g. '50%'), a
269 * number of pixels (e.g. '123px') or an empty string.
270 * If it's an empty string, it will respect the image size ratio depending on the height value
271 * Examples:
272 * - if height='100%' and width='', it will take the available height in the cell and compute the width so
273 * that the image is not malformed.
274 * - if height='' and width='50%', it will take half of the available width in the cell and compute the height so
275 * that the image is not malformed.
276 * - if height='' and width='', the image will keep its original size.
277 *
278 * The default is `''`.
279 */
280 width?: CellRenderer.ConfigOption<string>;
281
282 /**
283 * The height of the image. Can be a percentage of the available space (e.g. '50%'), a
284 * number of pixels (e.g. '123px') or an empty string.
285 * If it's an empty string, it will respect the image size ratio depending on the width value
286 * Examples:
287 * - if height='100%' and width='', it will take the available height in the cell and compute the width so
288 * that the image is not malformed.
289 * - if height='' and width='50%', it will take half of the available width in the cell and compute the height so
290 * that the image is not malformed.
291 * - if height='' and width='', the image will keep its original size.
292 *
293 * The default is `'100%'`.
294 */
295 height?: CellRenderer.ConfigOption<string>;
296 }
297 }