Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PROMO-251(OG): WIP: Add text-overflow for title #410

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added website/config/og/basic/RobotoMono-Variable.ttf
Binary file not shown.
17 changes: 14 additions & 3 deletions website/config/og/basic/template.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
{
"image": "preview.png",
"font": "RobotoMono-Bold.ttf",
"font": "RobotoMono-Variable.ttf",
"layout": [
{
"name": "title",
"top": 400,
"left": 210
carina-akaia marked this conversation as resolved.
Show resolved Hide resolved
"transform": "translate(100, 350)",
"fontSize": 54,
"fontWeight": 600,
"fill": "white",
"stroke": "white"
},
{
"name": "id",
"transform": "translate(100, 400)",
"fontSize": 42,
"fontWeight": 400,
"fill": "#b0b6a4",
"stroke": "#b0b6a4"
carina-akaia marked this conversation as resolved.
Show resolved Hide resolved
}
]
}
33 changes: 11 additions & 22 deletions website/plugins/docusaurus-plugin-og/font.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,22 @@
const { resolve } = require("path");
const textToSVG = require("text-to-svg");
const { getFontFace } = require("./svg");

function createFontsMapFromTemplates(templates) {
const fonts = new Map();
templates.forEach((template) => {
if (!fonts.has(template.params.font)) {
fonts.set(
template.params.font,
textToSVG.loadSync(resolve(template.path, template.name, template.params.font)),
);
// trunc file extension
const fontName = template.params.font.slice(0, -4);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: Кажется, можно попроще 🤔

Мб @Postamentovich еще что подскажет

image

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Прикольно, посмотрю!

fonts.set(template.params.font, {
name: fontName,
declaration: getFontFace(
fontName,
resolve(template.path, template.name, template.params.font),
),
});
carina-akaia marked this conversation as resolved.
Show resolved Hide resolved
}
});
return fonts;
}

function createSVGText(
font,
text,
{ fontSize = 72, fill = "white", stroke = "white" },
widthLimit = 1000,
) {
const attributes = { fill, stroke };
const options = { fontSize, anchor: "top", attributes };
// Remove all emoji from text
const filteredText = text.replace(
/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g,
"",
);

return font.getSVG(filteredText, options);
}
module.exports = { createSVGText, createFontsMapFromTemplates };
module.exports = { createFontsMapFromTemplates };
10 changes: 6 additions & 4 deletions website/plugins/docusaurus-plugin-og/layout.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { createSVGText } = require("./font");
const { Logger } = require("./utils");
const { textToSVG } = require("./svg");

function createLayoutLayers(doc, layout, previewFont, textWidthLimit) {
carina-akaia marked this conversation as resolved.
Show resolved Hide resolved
/* Check for all layers names exist in doc fields */
Expand All @@ -13,14 +13,16 @@ function createLayoutLayers(doc, layout, previewFont, textWidthLimit) {
fontSize: layer.fontSize,
fill: layer.fill,
stroke: layer.stroke,
transform: layer.transform,
fontWeight: layer.fontWeight,
};

return {
input: Buffer.from(
createSVGText(previewFont, doc[layer.name], layoutOptions, textWidthLimit),
textToSVG(previewFont, doc[layer.name], layoutOptions, textWidthLimit),
),
top: layer.top,
left: layer.left,
top: layer.top || 0,
left: layer.left || 0,
};
});
}
Expand Down
93 changes: 93 additions & 0 deletions website/plugins/docusaurus-plugin-og/svg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
const XMLSpecifiedSymbols = [
{ from: "&", to: "&" },
{ from: ">", to: ">" },
{ from: "<", to: "&lt;" },
];

Comment on lines +1 to +6
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick(non-blocking): Некрит, но тут кажется можно было бы объектом-мапой обойтись

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

угу

// prevent errors while parsing XML svg object
function isolateXMLSpecifiedSymbols(text) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion(non-blocking): Мб что-то типа function escapeText?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

непонятно звучит конечно, но давай escapeText! =)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну тип "экранирование" ~ "чистка"

@GhostMayor Как бы такое назвал?)

return XMLSpecifiedSymbols.reduce(
(result, char) => result.replace(new RegExp(char.from), char.to),
text,
);
}

function SVGText(text, font) {
return `
<text
xmlns="http://www.w3.org/2000/svg"
style="
font-family:${font.name};
font-size: ${font.fontSize};
font-weight: ${font.fontWeight};
"
transform="${font.transform}"
fill="${font.fill}"
stroke="${font.stroke}"
>
${isolateXMLSpecifiedSymbols(text)}
</text>`;
}

function getFontFace(fontName, path) {
return `<font>
<font-face font-family="${fontName}">
<font-face-src>
<font-face-uri xlink:href="file://${path}" />
</font-face-src>
</font-face>
</font>`;
}

function getTextWidth(text, options) {
return ((options.fontSize * 400) / options.fontWeight) * 0.9 * text.length;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут надо наоборот делить =)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А поч щас не пофиксить тогда? 🤔

}

function textToSVG(font, text, options, widthLimit = 1300, textPaddingTop = -70) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: Раз уж речь не про символьную длину, то мб переименовать в maxWidth? На манер с css

thoughts: Тож самое и с паддингом можно сделать кмк

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хорошая идея.

const filteredText = text.replace(
/([\u2700-\u27BF]|[[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|\uD83E[\uDD10-\uDDFF])/g,
"",
);

let svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${widthLimit}" height="${600}">`;
svg += font.declaration;

if (getTextWidth(text, options) > widthLimit) {
Comment on lines +52 to +55
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue(critical): ОЧ сложно читаемый и поддерживаемый код кмк

(хоть и используется только для постбилда)

suggestion(critical): Кмк, лучше бы переписать это на манер, как функция SVGText - т.е. чтобы сложные значения предпросчитать заранее, а на выход отдавать template-string понятный

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Щас постараюсь локально еще подсказать как можно кмк упростить

const reformat = filteredText.split(" ").reduce(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: Некрит, но лучше при разбиении отдельно константу words завести. Почище будет, и можно к ней обращаться отдельно в цикле

(acc, cur) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: Отдельно бы указал, что речь про слова, по которым итерируешься
Т.к. вне цикла не понятно, что за cur

Suggested change
(acc, cur) => {
(acc, word) => {

if (getTextWidth(`${acc.temp} ${cur}`, options) < widthLimit) {
return { ...acc, temp: `${acc.temp} ${cur}` };
}

return {
temp: cur,
result: [...acc.result, acc.temp],
};
},
{
temp: "",
result: [],
},
);
svg += SVGText(reformat.temp, {
...options,
name: font.name,
});
for (let i = reformat.result.length - 1; i >= 0; i--) {
svg += SVGText(reformat.result[i], {
...options,
transform: `${options.transform} translate(0, ${
(reformat.result.length - i) * textPaddingTop
})`,
name: font.name,
});
}
Comment on lines +58 to +84
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: А вот это дело прям упростить надо... Т.к. оч сложно считывается, и прям велика вероятность потом где-то тут ошибку сделать

suggestion: Как варианты, что в голову приходят:

  1. Свести все к генерации массива строк lines (опять же по критерию < widthLimit)
    2.A. (в идеале) Переписать логику стилей так, чтобы каждый объект можно было обернуть спокойно в SVGText(...) и не шаманить в циклах
    2.B. Если же так нельзя (а учитывая наши замашки по шаблону - так рили может быть) - то хотя бы привести к простому циклу, мб тому же редьюсу - где в константу contentSvg редьюсится итоговое значение с учетом переноса строк
  2. И как итог - просто вставляем в return template-string нужные значения contentSvg, font.declaration - и гораздо чище получится

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

На самом деле, оч смущает столько хелперов и этапов шаманств с текстом, но учитывая изначальные требования - мб по другому и никак... @feature-sliced/contributors @feature-sliced/core мб будут мнения как еще проще в svgшке текст перенести?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

На самом деле я не представляю как ты тут это всё разбирал, магию редьюсов и тд, т.к. это всё в качестве черного варианта было накидано, чтоб вообще расмотреть идею с самописным svg. Кстати owerflow через foreignObject не предлагать, он его не понимает =((


console.error(filteredText, reformat.result, reformat.temp);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: Если консолим, то хотя бы уточни что именно)
Особенно если ошибка (хотя непонятно почему ошибка именно должна быть, если тут все валидно)

} else svg += SVGText(filteredText, { ...options, name: font.name });
svg += `</svg>`;
Comment on lines +87 to +88
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: Лучше сразу обработать негативный сценарий и выбросить значение из функции

А оставшееся тело функции куда будет проще и ацикломатически, и в плане читаемости

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

угу


return svg;
}

module.exports = { textToSVG, getFontFace };
8 changes: 5 additions & 3 deletions website/plugins/docusaurus-plugin-og/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,13 @@ async function getTemplates(templatesDir, encode = "utf8") {
const Layout = object({
type: optional(string()),
name: string(),
fontSize: optional(number()),
fill: optional(string()),
stroke: optional(string()),
top: number(),
left: number(),
top: optional(number()),
left: optional(number()),
transform: optional(string()),
fontSize: optional(number()),
fontWeight: optional(number()),
carina-akaia marked this conversation as resolved.
Show resolved Hide resolved
});

const Template = object({
Expand Down