-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathrehype-video-aspect-ratio.mjs
More file actions
170 lines (143 loc) · 4.35 KB
/
rehype-video-aspect-ratio.mjs
File metadata and controls
170 lines (143 loc) · 4.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import ffprobe from '@ffprobe-installer/ffprobe';
import { exec } from 'child_process';
import fs from 'fs';
import path from 'path';
import { visit } from 'unist-util-visit';
import { promisify } from 'util';
const execAsync = promisify(exec);
/**
* Rehype plugin to add aspect ratio preservation to video tags
*/
export default function rehypeVideoAspectRatio({ staticDir }) {
return async (tree, file) => {
const promises = [];
visit(tree, 'mdxJsxFlowElement', (node) => {
if (node.name === 'video') {
// Find video source - check src attribute or source children
let videoSrc = null;
// Look for src in attributes
if (node.attributes) {
const srcAttr = node.attributes.find(
(attr) => attr.type === 'mdxJsxAttribute' && attr.name === 'src'
);
if (srcAttr) {
videoSrc = srcAttr.value;
}
}
// If no src attribute, look for source children
if (!videoSrc && node.children) {
const sourceNode = node.children.find(
(child) =>
child.type === 'mdxJsxFlowElement' && child.name === 'source'
);
if (sourceNode?.attributes) {
const srcAttr = sourceNode.attributes.find(
(attr) => attr.type === 'mdxJsxAttribute' && attr.name === 'src'
);
if (srcAttr) {
videoSrc = srcAttr.value;
}
}
}
const isLocalFile =
videoSrc &&
!videoSrc.startsWith('http://') &&
!videoSrc.startsWith('https://') &&
!videoSrc.startsWith('//');
if (isLocalFile) {
const videoPath = path.join(
videoSrc.startsWith('/') ? file.cwd : file.dirname,
staticDir,
videoSrc
);
if (fs.existsSync(videoPath)) {
const promise = getVideoDimensions(videoPath).then((dimensions) => {
if (dimensions.width && dimensions.height) {
applyAspectRatio(node, dimensions.width, dimensions.height);
}
});
promises.push(promise);
} else {
throw new Error(`Video file does not exist (got ${videoPath})`);
}
}
}
});
await Promise.all(promises);
};
}
/**
* Apply aspect ratio styles to a video node
*/
function applyAspectRatio(node, width, height) {
const data = {
estree: {
type: 'Program',
body: [
{
type: 'ExpressionStatement',
expression: {
type: 'ObjectExpression',
properties: [
{
type: 'Property',
key: { type: 'Identifier', name: 'aspectRatio' },
value: { type: 'Literal', value: width / height },
kind: 'init',
},
],
},
},
],
},
};
node.attributes = node.attributes || [];
let styleAttr = node.attributes?.find(
(attr) => attr.type === 'mdxJsxAttribute' && attr.name === 'style'
);
if (styleAttr) {
const properties =
styleAttr.value?.data?.estree?.body?.[0]?.expression?.properties ?? [];
data.estree.body[0].expression.properties.push(...properties);
}
styleAttr = {
type: 'mdxJsxAttribute',
name: 'style',
value: {
type: 'mdxJsxAttributeValueExpression',
data,
},
};
const existingIndex = node.attributes.findIndex(
(attr) => attr.type === 'mdxJsxAttribute' && attr.name === 'style'
);
if (existingIndex !== -1) {
node.attributes[existingIndex] = styleAttr;
} else {
node.attributes.push(styleAttr);
}
}
/**
* Get video dimensions using ffprobe
*/
async function getVideoDimensions(filePath) {
const { stdout } = await execAsync(
`${ffprobe.path} -v error -of flat=s=_ -select_streams v:0 -show_entries stream=height,width "${filePath}"`
);
const lines = stdout.trim().split('\n');
const dimensions = {};
for (const line of lines) {
if (line.includes('width')) {
const width = Number(line.split('=')[1]);
if (Number.isFinite(width) && width > 0) {
dimensions.width = width;
}
} else if (line.includes('height')) {
const height = Number(line.split('=')[1]);
if (Number.isFinite(height) && height > 0) {
dimensions.height = height;
}
}
}
return dimensions;
}