48 Commits
1.0.3 ... 2.0.0

Author SHA1 Message Date
LightAir
83f2045b23 Изменение версии пакета 2021-08-29 02:25:18 +03:00
LightAir
01aa654b03 Рефакторинг. Дорабавление новых опций. 2021-08-29 02:19:59 +03:00
Nikita Kornilov
c676a924b0 Add support for image captions. (#7)
* Add support for image caption.

* Add support for image_caption prop.
2021-08-28 23:26:26 +03:00
LightAir
7aceeeaa36 Возврат covearge 2021-06-09 22:45:40 +03:00
LightAir
9cccd65768 Обновление версии пакета 2021-06-09 22:27:19 +03:00
LightAir
812a429d9b Удаление лишних dev пакетов. Удаление dev пакетов с уязвимостями 2021-06-09 22:17:08 +03:00
LightAir
15c9715cee Merge pull request #6 from Armanio/patch-1
chore(docs): typo fix in readme
2021-06-04 21:47:12 +03:00
Arman
816b6b5690 chore(docs): typo fix in readme 2021-06-04 15:17:36 +03:00
LightAir
ef90f974bd Изменение тестов 2020-12-15 22:51:02 +03:00
LightAir
8aa086865d Изменение тестов 2020-12-15 22:47:51 +03:00
LightAir
6d3cd71f47 Правки версии пакета 2020-12-02 00:40:28 +03:00
LightAir
ec44f8e5d3 Небольшие изменения 2020-12-02 00:32:13 +03:00
LightAir
7770e925fd Добавление новых версий ноды в travis ci 2020-12-01 23:54:04 +03:00
LightAir
9864d6408a Небольшие правки. Добавил тесты на новый функционал от crackosok 2020-12-01 23:49:41 +03:00
LightAir
3d5258a6c7 Merge pull request #4 from crackosok/master
add possibility to set turbo false
2020-12-01 20:21:44 +03:00
Kirill Myagkikh
a8e4ba436c review fixes 2020-11-29 19:20:10 +05:00
Kirill Myagkikh
acd60d5922 add possibility to set turbo false 2020-11-18 15:23:38 +05:00
cfea55ea4c Merge pull request #3 from concertmoscow/goals
Added turbo:goal support
2020-09-02 10:28:48 +03:00
vvm
93815ec708 1.1.0 2020-08-31 23:16:13 +03:00
vvm
c5a7ff6e1c Added turbo:goal support 2020-08-31 23:08:53 +03:00
LightAir
2d3f75902f Косметические изменения 2018-05-30 22:47:30 +03:00
LightAir
d896040f63 Рабочая версия 2018-05-30 22:20:54 +03:00
la
8645a88b01 Публикация в npmjs версии 1.0.7 2018-05-30 14:56:56 +03:00
la
c65b6ccc12 Добавлена опция relatedfinity для формирования непрерывной ленты статей 2018-05-30 14:53:25 +03:00
la
4b0f033aa9 Добавление codeclimate 2018-05-30 14:13:01 +03:00
la
86678c6448 Добавление codeclimate 2018-05-30 13:55:05 +03:00
la
83c8380108 add new version 2018-05-30 12:18:15 +03:00
la
c76f5a522f cleaning repo 2018-05-30 12:17:22 +03:00
la
415afbc2e3 add bages 2018-05-30 11:29:09 +03:00
la
6819999a2e Code climate 2018-05-30 11:12:37 +03:00
la
4ddd19e269 Проблема с времнем 2018-05-29 15:54:25 +03:00
la
2a4e3c5083 Изменены версии nodejs для travis 2018-05-29 14:35:32 +03:00
la
b7f6667798 Изменён способ добавления аттрибутов на правильный 2018-05-29 14:24:33 +03:00
la
e1516f9e1b update readme 2018-05-29 13:19:09 +03:00
la
44d345ac6b add eslint 2018-05-29 13:13:54 +03:00
LightAir
c5a9e4b5fd Merge pull request #2 from jahglow/master
corrected readme, ++patch
2018-05-29 11:01:54 +03:00
la
97e23fe031 Стилизация. Добавление теста для related 2018-05-29 11:00:33 +03:00
Ivan Pilyugin (aka Archer)
a4b18cde97 added yandex:related 2018-05-29 10:35:37 +03:00
Ivan Pilyugin (aka Archer)
1dca86ab85 corrected readme for yandex:related 2018-05-29 10:34:55 +03:00
Ivan Pilyugin (aka Archer)
8b4ec85bcf Merge pull request #1 from LightAir/master
Merge pull request #1 from jahglow/master
2018-05-29 10:32:52 +03:00
LightAir
b02eaab7e6 Merge pull request #1 from jahglow/master
Базовая поддержка yandex:related
2018-05-29 10:07:16 +03:00
Ivan Pilyugin (aka Archer)
10e74b0a1b yandex:related image renamed to image_url
for naming consistency
2018-05-29 10:04:50 +03:00
Ivan Pilyugin (aka Archer)
c47a6d3d0f Update readme.md
added description to yandex:related
2018-05-29 10:03:41 +03:00
Ivan Pilyugin (aka Archer)
365abd5592 added yandex:related support 2018-05-29 09:58:53 +03:00
la
8bd429accc Приведение в порядок соответствия версий npm и git 2018-05-03 13:55:28 +03:00
la
43dadcd891 Merge branch 'master' of github.com:LightAir/turbo-rss 2018-05-03 13:53:40 +03:00
la
e4b5093678 npm 1.0.3 2018-05-03 13:52:59 +03:00
LightAir
28030cd0dc Update readme.md 2018-05-03 13:37:38 +03:00
23 changed files with 553 additions and 246 deletions

5
.codeclimate.yml Normal file
View File

@@ -0,0 +1,5 @@
plugins:
eslint:
enabled: true
config:
config: .eslintrc.json

View File

@@ -1,16 +0,0 @@
# Get the plugin for your editor and your
# tab settings will be set automatically.
# http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with no newline ending every file
[*]
end_of_line = lf
insert_final_newline = false
# Indentation override for all JS under lib directory
[*.js]
indent_style = space
indent_size = 4

34
.eslintrc.json Normal file
View File

@@ -0,0 +1,34 @@
{
"env": {
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"no-var": "error",
"no-multi-spaces": "error",
"space-in-parens": "error",
"no-multiple-empty-lines": "error",
"prefer-const": "error",
"no-use-before-define": "error"
}
}

1
.gitignore vendored
View File

@@ -2,3 +2,4 @@
node_modules node_modules
package-lock.json package-lock.json
*.log *.log
coverage/

View File

@@ -1,14 +0,0 @@
{
"esversion":6,
"curly": true,
"eqeqeq": true,
"immed": true,
"latedef": true,
"newcap": true,
"noarg": true,
"sub": true,
"undef": true,
"boss": true,
"eqnull": true,
"node": true
}

View File

@@ -1,11 +1,16 @@
language: node_js language: node_js
sudo: false sudo: false
addons:
code_climate:
repo_token:
secure: "Lz3KeRxbJ877gDe0kWNdAg3erDe4TVruP98Xes18N13H8XGyIdWs2GnJiRHHS831tCd3yYu5F643xNXJuQ3omWikvRVr0lu57yBdJVg0dhJwjEnP85DRIU3YmGAe4Ua5qNoMlhZMyZwL6TTHWt30SZ2NK/HmYOr+fI0/H8OTWtrxcMlwYYZkbmhllGAYWnXnZCOCHuIcio7L21pEX/PXtrQMTVNFuebT2Q8GihjoW00KeH8z4t7E+a7MFb427dX7MRYGHHGuu2dAUoDI/P5tz7FIQg83Uz4Jmnzh34Wc9uYLd5lTcRc6Mb7mOVHXO9ZLoVtxE7gB+apN+NkzhPhZjQToyvypwyzUZiHV9xtYj9abUuU5vXEdGTA4+KEy7iM25r7U1cqsVVWsXBckpEpprlvJ2FQbbajP9PZpvnSwFmbPDGFJf2uPs07xtav1F6fpAU9zSg8J+iagS9grmCccNcs4TrExWRCFLRupN2AC9SeLWCb2ux+3IMuqwNkJiiWYNzLMOHru2kxFGgc7+wd3bzREbgZJbYUHCmVchHVcUT2/dn240mSVnLoemP1z91VdxbUN3EwR0Hcp5LnTMqCSQ880QUmFjDFnd0huKXKrKrr61na/wVoUDrcQGg/DKgvGcDm6CqzeHfSM9EHqwbbYx4cZn36ZA1nDiNTMLSxHhn0="
script: npm run coverage
before_script:
- export TZ=Europe/Moscow
- date
- npm install codeclimate-test-reporter istanbul -g
after_script:
- codeclimate-test-reporter < ./coverage/lcov.info
matrix: matrix:
include: include:
- node_js: '0.10' - node_js: 'lts/*'
before_install: npm -g i npm@2
- node_js: '0.12'
before_install: npm -g i npm@2
- node_js: '4'
before_install: npm -g i npm@2

View File

@@ -1,51 +0,0 @@
'use strict';
module.exports = function(grunt) {
/**
* grunt release or grunt release:patch increment the patch number
* grunt release:minor increments the minor version number
* grunt release:major increments the major version number
*
* grunt readme to generate the readme (you might need to do grunt repos first)
*/
require('time-grunt')(grunt);
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'lib/**/*.js',
'test/**/*.js'
]
},
release: {
github: {
repo: 'dylang/node-rss',
accessTokenVar: 'GITHUB_ACCESS_TOKEN'
}
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('lint', [
'jshint'
]);
grunt.registerTask('default', [
'lint'
]);
grunt.registerTask('pre-publish', [
'lint',
'repos',
'readme'
]);
};

View File

@@ -1,53 +1,187 @@
'use strict'; 'use strict';
const xml = require('xml'); const baseXml = require('xml');
function ifTruePush(bool, array, data) { class TR {
if (bool) { constructor(options, items) {
options = options || {};
this.title = options.title || '';
this.link = options.link || '';
this.description = options.description || '';
this.language = options.language || 'ru';
this.items = [];
if (Array.isArray(items) && items.length > 0) {
const self = this;
items.forEach(function (item) {
self.item(item);
});
}
}
xml() {
return baseXml(this.generateXML(this));
}
item(data) {
data = data || {};
this.items.push(
this.itemData(data)
);
return this;
}
/**
* Check first argument. If true - push last argument to second argument
*
* @param condition
* @param array
* @param data
*/
pushIfConditionTrue(condition, array, data) {
if (condition) {
array.push(data); array.push(data);
} }
} }
function generateXML(data) { /**
* @param related
let channel = []; * @param itemValues
* @param relatedInfinity
channel.push({title: {_cdata: data.title}}); */
channel.push({link: data.link || 'http://github.com/LightAir/turbo-rss'}); addRelated(related, itemValues, relatedInfinity) {
channel.push({description: {_cdata: data.description || data.title}}); const relatedResult = related.map(function (rel) {
channel.push({language: 'ru'}); return {
link: [{
data.items.forEach(function (item) { _attr: {
'url': rel.link,
let item_values = []; 'img': rel.image_url
item_values.push({_attr: {'turbo': 'true'}});
item_values.push({link: item.url});
item_values.push({'turbo:source': item.url});
ifTruePush(item.date, item_values, {pubDate: new Date(item.date).toGMTString()});
ifTruePush(item.author, item_values, {author: item.author});
let img = '';
let menu = '';
if (item.image_url) {
img = '<figure><img src="' + item.image_url + '" /></figure>';
} }
}, rel.text]
if (item.menu) { };
menu = '<menu>' + item.menu + '</menu>';
}
let fullContent = '<header>' + img + ' <h1>' + item.title + '</h1>' + menu + '</header>' + item.content;
item_values.push({'turbo:content': {_cdata: fullContent}});
channel.push({item: item_values});
}); });
let _attr = { if (relatedInfinity) {
relatedResult.push({
_attr: {'type': 'infinity'}
});
}
this.pushIfConditionTrue(related, itemValues, {'yandex:related': relatedResult});
}
/**
* @param item
* @param itemValues
*/
pushGoals(item, itemValues) {
if (item.goals.length > 0) {
item.goals.forEach(goal => itemValues.push({
'turbo:goal': {
_attr: {
type: goal.type || 'yandex',
'turbo-goal-id': goal.id,
name: goal.name,
id: goal.counter_id,
}
}
}));
}
}
getImageContent(item) {
if (item.image_url.length > 0) {
let imageCaption = '';
if (item.image_caption.length > 0) {
imageCaption = `<figcaption>${item.image_caption}</figcaption>`;
}
return `<figure><img src="${item.image_url}" />${imageCaption}</figure>`;
}
return '';
}
getSubheading(item) {
if (item.subheading.length > 0) {
return `<h2>${item.subheading}</h2>`;
}
return '';
}
getLinksString(links) {
return links.map(function (item) {
return `<a href="${item.link}">${item.text}</a>`;
}).join('');
}
getMenu(item) {
if (Array.isArray(item.menu) && item.menu.length > 0) {
return `<menu>${this.getLinksString(item.menu)}</menu>`;
}
return '';
}
getBreadcrumbs(item) {
if (Array.isArray(item.breadcrumbs) && item.breadcrumbs.length > 0) {
return `<div data-block="breadcrumblist">${this.getLinksString(item.breadcrumbs)}</div>`;
}
return '';
}
/**
* Items processing
* @param items
* @param channel
*/
itemsProcessing(items, channel) {
const self = this;
items.forEach(function (item) {
const itemValues = [];
itemValues.push({_attr: {'turbo': item.turboEnabled ? 'true' : 'false'}});
itemValues.push({link: item.url});
self.pushIfConditionTrue(item.turboSource, itemValues, {'turbo:source': item.turboSource});
self.pushIfConditionTrue(item.turboTopic, itemValues, {'turbo:topic': item.turboTopic});
self.pushIfConditionTrue(item.date, itemValues, {pubDate: new Date(item.date).toUTCString()});
self.pushIfConditionTrue(item.author, itemValues, {author: item.author});
const fullContent = `<header>${self.getImageContent(item)}<h1>${item.title}</h1>${self.getSubheading(item)}${self.getMenu(item)}${self.getBreadcrumbs(item)}</header>${item.content}`;
self.pushGoals(item, itemValues);
itemValues.push({'turbo:content': {_cdata: fullContent}});
if (typeof item.related !== 'undefined') {
self.addRelated(item.related, itemValues, item.relatedInfinity);
}
channel.push({item: itemValues});
});
}
/**
* @param options
*
* @returns {{rss: *[]}}
*/
generateXML(options) {
const channel = [];
channel.push({title: {_cdata: options.title}});
channel.push({link: options.link});
channel.push({description: {_cdata: options.description}});
channel.push({language: options.language});
this.itemsProcessing(options.items, channel);
const _attr = {
'xmlns:yandex': 'http://news.yandex.ru', 'xmlns:yandex': 'http://news.yandex.ru',
'xmlns:media': 'http://search.yahoo.com/mrss/', 'xmlns:media': 'http://search.yahoo.com/mrss/',
'xmlns:turbo': 'http://turbo.yandex.ru', 'xmlns:turbo': 'http://turbo.yandex.ru',
@@ -62,34 +196,30 @@ function generateXML(data) {
}; };
} }
function YTurbo(options, items) { /**
options = options || {}; * @param data
* @returns {*}
this.title = options.title || 'Untitled'; */
this.description = options.description || ''; itemData(data) {
this.link = options.link; return {
this.items = items || []; title: data.title || '', // h1
subheading: data.subheading || '', // h2
this.item = function (options) { image_url: data.image_url || '',
options = options || {}; image_caption: data.image_caption || '',
let item = { url: data.url || data.link,
title: options.title || 'No title', author: data.author,
description: options.description || '', date: data.date || data.pubDate,
image_url: options.image_url, content: data.content,
url: options.url, menu: data.menu || [],
author: options.author, breadcrumbs: data.breadcrumbs || [],
date: options.date || options.pubDate, related: data.related,
content: options.content, relatedInfinity: data.relatedInfinity || false,
menu: options.menu turboSource: data.turboSource || '',
}; turboTopic: data.turboTopic || '',
goals: data.goals || [],
this.items.push(item); turboEnabled: data.turboEnabled !== undefined ? data.turboEnabled : true,
return this;
};
this.xml = function () {
return xml(generateXML(this));
}; };
} }
}
module.exports = YTurbo; module.exports = TR;

View File

@@ -1,6 +1,6 @@
{ {
"name": "turbo-rss", "name": "turbo-rss",
"version": "1.0.1", "version": "2.0.0",
"description": "RSS based, feed generator for Yandex turbo", "description": "RSS based, feed generator for Yandex turbo",
"keywords": [ "keywords": [
"yandex", "yandex",
@@ -10,17 +10,17 @@
], ],
"main": "lib/index", "main": "lib/index",
"scripts": { "scripts": {
"test": "tape test --tap | tap-difflet", "test": "tape test --tap | tap-min",
"lint": "grunt lint", "coverage": "istanbul cover tape test -- -R spec"
"test:browser": "prova -b"
}, },
"homepage": "http://github.com/lightair/yandex-turbo", "homepage": "https://github.com/LightAir/turbo-rss",
"author": { "author": {
"name": "LightAir", "name": "LightAir",
"email": "public@softroot.ru" "email": "public@softroot.ru"
}, },
"contributors": [ "contributors": [
"LightAir <public@softroot.ru>", "LightAir <public@softroot.ru>",
"Ivan Pilyugin (aka Archer)",
"Dylan Greene <dylang@gmail.com>", "Dylan Greene <dylang@gmail.com>",
"Xavier Damman <xdamman@gmail.com>", "Xavier Damman <xdamman@gmail.com>",
"Michael R. Lange", "Michael R. Lange",
@@ -34,10 +34,10 @@
], ],
"repository": { "repository": {
"type": "git", "type": "git",
"url": "http://github.com/lightair/yandex-turbo.git" "url": "https://github.com/LightAir/turbo-rss.git"
}, },
"bugs": { "bugs": {
"url": "http://github.com/lightair/yandex-turbo/issues" "url": "https://github.com/LightAir/turbo-rss/issues"
}, },
"testling": { "testling": {
"files": "test/*.js", "files": "test/*.js",
@@ -56,26 +56,12 @@
"xml": "1.0.1" "xml": "1.0.1"
}, },
"devDependencies": { "devDependencies": {
"folderify": "^1.1.0", "eslint": "^7.28.0",
"grunt": "^0.4.5",
"grunt-cli": "^0.1.13",
"grunt-contrib-jshint": "^0.11.3",
"grunt-release": "^0.13.0",
"grunt-templates-dylang": "^1.0.10",
"include-folder": "^1.0.0", "include-folder": "^1.0.0",
"load-grunt-tasks": "^3.3.0", "mockdate": "^3.0.5",
"mockdate": "^1.0.3", "q": "^1.5.1",
"prova": "^2.1.2", "tap-min": "~2.0.0",
"q": "^1.4.1", "tape": "^5.2.2"
"tap-difflet": "^0.4.0",
"tape": "^4.2.1",
"time-grunt": "^1.2.1",
"xml2js": "^0.4.12"
},
"browserify": {
"transform": [
"folderify"
]
}, },
"license": "MIT" "license": "MIT"
} }

View File

@@ -1,15 +1,12 @@
## WIP
## turbo-rss ## turbo-rss
[![Build Status](https://travis-ci.org/LightAir/turbo-rss.svg)](https://travis-ci.org/lightair/turbo-rss) [![Maintainability](https://api.codeclimate.com/v1/badges/6525d2aabf20185b68b6/maintainability)](https://codeclimate.com/github/LightAir/turbo-rss/maintainability)
![npm](https://img.shields.io/npm/v/npm.svg) [![Test Coverage](https://api.codeclimate.com/v1/badges/6525d2aabf20185b68b6/test_coverage)](https://codeclimate.com/github/LightAir/turbo-rss/test_coverage)
![Packagist](https://img.shields.io/packagist/l/doctrine/orm.svg) [![Build Status](https://travis-ci.org/LightAir/turbo-rss.svg)](https://travis-ci.org/LightAir/turbo-rss)
[![npm](https://img.shields.io/badge/npm%20package-1.0.7-blue.svg?longCache=true&style=flat)](https://www.npmjs.com/package/turbo-rss)
![license](https://img.shields.io/packagist/l/doctrine/orm.svg?longCache=true&style=flat)
>Генератор RSS разметки для сервиса Турбо-страницы https://yandex.ru/support/webmaster/turbo/connection.html
>Генератор RSS разметки для сервиса Турбо-страницы
>ПРЕДУПРЕЖДЕНИЕ! Работа в процессе
### Использование ### Использование
@@ -24,12 +21,11 @@ var feed = new TR(feedOptions);
##### `Опции канала` ##### `Опции канала`
* `title` **string** Название RSS-канала. * `title` **string** Название RSS-канала.
* `description` _optional_ **string** Описание канала одним предложением. Не используйте HTML-разметку.. * `link` **url string** Домен сайта, данные которого транслируются.
* `author` _optional_ **string** If included it is the name of the item's creator. **(Будет удалено)** * `description` _optional_ **string** Описание канала одним предложением. Не используйте HTML-разметку.
* `link` **url string** Домен сайта, данные которого транслируются.. * `language` _optional_ **string** Язык статьи по стандарту ISO 639-1. По умолчанию ru.
* `pubDate` _optional_ **Date object or date string** The publication date for content in the feed **(Будет удалено)**
*Будет добавлено в новых версиях turbo:analytics, turbo:adNetwork* *Будет добавлено в новых версиях turbo:analytics, turbo:adNetwork, на текущий момент можно добавить в интерфейсе Яндекс Вебмастер*
#### Добавление страницы в канал #### Добавление страницы в канал
```js ```js
@@ -39,13 +35,40 @@ feed.item(itemOptions);
##### itemOptions ##### itemOptions
* `title` **string** Заголовок страницы. * `title` **string** Заголовок страницы.
* `image_url` **url string** Адрес изображения, которое используется в качестве обложки. Изображение может быть в любом формате. * `subheading` _optional_ **string** Подзаголовок страницы.
* `url` **url string** URL страницы сайта, для которой нужно сформировать Турбо-страницу. * `image_url` _optional_ **url string** Адрес изображения, которое используется в качестве обложки. Изображение может быть в любом формате.
* `image_caption` _optional_ **string** Подпись к изображению обложки.
* `link` **url string** URL страницы сайта, для которой нужно сформировать Турбо-страницу.
* `author` _optional_ **string** Автор статьи, размещенной на странице. * `author` _optional_ **string** Автор статьи, размещенной на странице.
* `date` **string** Время публикации контента на сайте источника. * `date` или `pubDate` **string** Время публикации контента на сайте источника. Передается в формате RFC-822.
* `content` **string** Содержимое страницы * `content` **string** Содержимое страницы
* `menu` _optional_ **array** Внимание! Меню будет отображаться только в том случае, если в настройках на странице Яндекс Вебмастер -> Турбо-страницы -> Настройки, содержимое 'Меню Турбо-страниц' пустое!
* `breadcrumbs` _optional_ **array** Навигационная ссылка https://yandex.ru/dev/turbo/doc/rss/elements/header.html#breadcrumbs
* `related` _optional_ **array** Аффилированные ссылки `yandex:related` в конце статьи. Вы можете разместить ссылки на другие ресурсы или настроить отображение непрерывной ленты статей, реализованной, например с помощью AJAX.
* `relatednfinity` _optional_ **bool** Непрерывная лента статей (Параметр был переименован из relatedfinity)
* `turboSource` _optional_ **string** URL страницы-источника, который можно передать в Яндекс.Метрику.
* `turboTopic` _optional_ **string** Заголовок страницы, который можно передать в Яндекс.Метрику.
* `goals` _optional_ **array** массив типа: { _id_ - внутренний идентификатор цели (turbo-goal-id), _name_ - имя цели, _counter_id_ - id счётчика яндекс-метрики }
* `turboEnabled`_optional_ **bool** Принудительная установка атрибута "turbo". По умолчанию true. Установка в false позволит скрыть отображение турбо-страницы
*Будет добавлено в новых версиях turbo:source, turbo:topic, yandex:related, menu, pubDate как алиас date* ###### menu array
menu должен содержать массив объектов со следующими опциями:
* `link` **url string** ссылка
* `text` **string** текст ссылки. не должен содержать html
###### breadcrumbs array
Один элемент хлебных крошек должен содержать массив объектов со следующими опциями:
* `link` **url string** ссылка
* `text` **string** текст ссылки (не должен содержать html)
###### related array
related должен содержать массив объектов со следующими опциями:
* `link` **url string** ссылка на статью
* `image_url` **url string** ссылка на изображение к статье
* `text` **string** текст ссылки. Не должен содержать html
##### Получение XML ##### Получение XML
@@ -59,31 +82,58 @@ var xml = feed.xml();
```js ```js
var TR = require('turbo-rss'); var TR = require('turbo-rss');
/* lets create feed */
var feed = new TR({ var feed = new TR({
title: 'title', title: 'title',
description: 'description', description: 'description',
link: 'http://example.com', link: 'http://example.com',
}); });
/* loop over data and add to feed */
feed.item({ feed.item({
title: 'item title', title: 'item title',
image_url: 'http://example.com/example.png', image_url: 'http://example.com/example.png',
url: 'http://example.com/article4?this&that', url: 'http://example.com/article4?this&that',
author: 'LightAir', author: 'LightAir',
date: 'May 27, 2012', date: 'May 27, 2012',
content: '<p>hello</p>' content: '<p>hello</p>',
goals: [{
type: "yandex",
id: "turbo-goal-id",
counter_id: "12345",
name: "order",
}],
menu: [{
link: 'http://example.com/',
text: 'Главная'
}, {
link: 'http://example.com/about',
text: 'О сайте'
}],
related: [{
link: 'http://example.com/related/post1',
image_url: 'http://example.com/i/img1.jpg',
text: 'related link text 1'
}, {
link: 'http://example.com/related/post2',
image_url: 'http://example.com/i/img2.jpg',
text: 'related link text 2'
}]
}); });
// cache the xml to send to clients
var xml = feed.xml(); var xml = feed.xml();
``` ```
## Тестирование ## Тестирование
Для запуска тестов выполните `npm test`. На текущий момен покрытие тестами не 100% Для запуска тестов выполните `npm test`.
```sh ```sh
$ npm test $ npm test
``` ```
## Спасибо
@jahglow
@vvmspace
@crackosok

View File

@@ -0,0 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link>https://example.com/soups/with-potatoes/</link><pubDate>Sat, 26 May 2018 21:00:00 GMT</pubDate><author>LightAir</author><turbo:content><![CDATA[<header><figure><img src="https://example.com/example.png" /></figure><h1>Суп с картофелем</h1><div data-block="breadcrumblist"><a href="https://example.com/">Главная</a><a href="https://example.com/soups/">Супы</a><a href="https://example.com/soups/with-potatoes/">Суп с картофелем</a></div></header><p>Для приготовления супа с картофелем, возьмите</p>]]></turbo:content></item></channel></rss>

View File

@@ -1 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[Untitled]]></title><link>http://github.com/LightAir/turbo-rss</link><description><![CDATA[Untitled]]></description><language>ru</language></channel></rss> <rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title/><link></link><description/><language>ru</language></channel></rss>

View File

@@ -1 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link></link><turbo:source></turbo:source><turbo:content><![CDATA[<header> <h1>No title</h1></header>undefined]]></turbo:content></item></channel></rss> <rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link></link><turbo:content><![CDATA[<header><h1></h1></header>undefined]]></turbo:content></item></channel></rss>

View File

@@ -0,0 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="false"><link></link><turbo:content><![CDATA[<header><h1></h1></header>undefined]]></turbo:content></item></channel></rss>

View File

@@ -1 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[Untitled]]></title><link>http://github.com/LightAir/turbo-rss</link><description><![CDATA[Untitled]]></description><language>ru</language><item turbo="true"><link></link><turbo:source></turbo:source><turbo:content><![CDATA[<header> <h1>No title</h1></header>undefined]]></turbo:content></item></channel></rss> <rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title/><link></link><description/><language>ru</language><item turbo="true"><link></link><turbo:content><![CDATA[<header><h1></h1></header>undefined]]></turbo:content></item></channel></rss>

View File

@@ -0,0 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title/><link></link><description/><language>ru</language><item turbo="true"><link></link><turbo:content><![CDATA[<header><h1></h1></header>undefined]]></turbo:content></item><item turbo="true"><link></link><turbo:content><![CDATA[<header><h1></h1></header>undefined]]></turbo:content></item></channel></rss>

View File

@@ -0,0 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link>http://example.com/article4?this&amp;that</link><pubDate>Sat, 26 May 2018 21:00:00 GMT</pubDate><author>vvm.space</author><turbo:goal type="yandex" turbo-goal-id="turbo-goal-id" name="order" id="12345"/><turbo:content><![CDATA[<header><figure><img src="http://example.com/example.png" /></figure><h1>item title</h1></header><p>hello</p>]]></turbo:content><yandex:related><link url="http://example.com/related/post1" img="http://example.com/i/img1.jpg">related link text 1</link><link url="http://example.com/related/post2" img="http://example.com/i/img2.jpg">related link text 2</link></yandex:related></item></channel></rss>

View File

@@ -0,0 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link>http://example.com/article4?this&amp;that</link><pubDate>Sat, 26 May 2018 21:00:00 GMT</pubDate><author>LightAir</author><turbo:content><![CDATA[<header><figure><img src="http://example.com/example.png" /><figcaption>this is image caption</figcaption></figure><h1>item title</h1></header><p>hello</p>]]></turbo:content><yandex:related><link url="http://example.com/related/post1" img="http://example.com/i/img1.jpg">related link text 1</link><link url="http://example.com/related/post2" img="http://example.com/i/img2.jpg">related link text 2</link></yandex:related></item></channel></rss>

View File

@@ -0,0 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link>http://example.com/article4?this&amp;that</link><pubDate>Sat, 26 May 2018 21:00:00 GMT</pubDate><author>LightAir</author><turbo:content><![CDATA[<header><figure><img src="http://example.com/example.png" /></figure><h1>item title</h1><menu><a href="http://example.com/">Главная</a><a href="http://example.com/about">О сайте</a></menu></header><p>hello</p>]]></turbo:content><yandex:related type="infinity"><link url="http://example.com/related/post1" img="http://example.com/i/img1.jpg">related link text 1</link><link url="http://example.com/related/post2" img="http://example.com/i/img2.jpg">related link text 2</link></yandex:related></item><item turbo="true"><link></link><turbo:content><![CDATA[<header><h1></h1></header>undefined]]></turbo:content></item></channel></rss>

View File

@@ -0,0 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link>http://example.com/article4?this&amp;that</link><pubDate>Sat, 26 May 2018 21:00:00 GMT</pubDate><author>LightAir</author><turbo:content><![CDATA[<header><figure><img src="http://example.com/example.png" /></figure><h1>item title</h1></header><p>hello</p>]]></turbo:content><yandex:related><link url="http://example.com/related/post1" img="http://example.com/i/img1.jpg">related link text 1</link><link url="http://example.com/related/post2" img="http://example.com/i/img2.jpg">related link text 2</link></yandex:related></item></channel></rss>

View File

@@ -0,0 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link>http://example.com/article4?this&amp;that</link><pubDate>Sat, 26 May 2018 21:00:00 GMT</pubDate><author>LightAir</author><turbo:content><![CDATA[<header><figure><img src="http://example.com/example.png" /></figure><h1>item title</h1></header><p>hello</p>]]></turbo:content><yandex:related type="infinity"><link url="http://example.com/related/post1" img="http://example.com/i/img1.jpg">related link text 1</link><link url="http://example.com/related/post2" img="http://example.com/i/img2.jpg">related link text 2</link></yandex:related></item></channel></rss>

View File

@@ -0,0 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link></link><turbo:content><![CDATA[<header><h1>item title</h1><h2>Subheading</h2></header>undefined]]></turbo:content></item></channel></rss>

View File

@@ -1,34 +1,202 @@
// prova is a wrapper for tape const test = require('tape');
// use npm run test:browser to run tests in a browser const TR = require('..');
var test = require('tape');
var YTurbo = require('..'); const includeFolder = require('include-folder');
const expectedOutput = includeFolder(__dirname + '/expectedOutput', /.*\.xml$/);
var includeFolder = require('include-folder'); const baseOptions = {
var expectedOutput = includeFolder(__dirname + '/expectedOutput', /.*\.xml$/);
require('mockdate').set('Wed, 10 Dec 2014 19:04:57 GMT');
test('empty feed', function(t) {
t.plan(2);
var feed = new YTurbo();
t.equal(feed.xml(), expectedOutput.default.trim());
feed.item();
t.equal(feed.xml(), expectedOutput.defaultOneItem.trim());
});
test('default item', function(t) {
t.plan(1);
var feed = new YTurbo({
title: 'title', title: 'title',
description: 'description', description: 'description',
link: 'http://example.com/rss.xml', link: 'http://example.com/rss.xml',
site_url: 'http://example.com' site_url: 'http://example.com'
};
const relatedOptions = [{
link: 'http://example.com/related/post1',
image_url: 'http://example.com/i/img1.jpg',
text: 'related link text 1'
}, {
link: 'http://example.com/related/post2',
image_url: 'http://example.com/i/img2.jpg',
text: 'related link text 2'
}];
require('mockdate').set('Wed, 10 Dec 2014 19:04:57 GMT');
test('empty feed', function (t) {
t.plan(3);
const feed = new TR();
t.equal(feed.xml(), expectedOutput.default.trim());
feed.item();
t.equal(feed.xml(), expectedOutput.defaultOneItem.trim());
feed.item();
t.equal(feed.xml(), expectedOutput.defaultTwoItem.trim());
}); });
test('empty feed constructor', function (t) {
t.plan(1);
const feed = new TR(
{},
[{}, {}]
);
t.equal(feed.xml(), expectedOutput.defaultTwoItem.trim());
});
test('default item', function (t) {
t.plan(1);
const feed = new TR(baseOptions);
feed.item({}); feed.item({});
t.equal(feed.xml(), expectedOutput.defaultItem.trim()); t.equal(feed.xml(), expectedOutput.defaultItem.trim());
}); });
test('related item', function (t) {
t.plan(1);
const feed = new TR(baseOptions);
feed.item({
title: 'item title',
image_url: 'http://example.com/example.png',
url: 'http://example.com/article4?this&that',
author: 'LightAir',
date: 'May 27, 2018 00:00 AM',
menu: '<a href="http://example.com/page1.html">Текст ссылки</a> <a href="http://example.com/page2.html">Текст ссылки</a>',
content: '<p>hello</p>',
related: relatedOptions
});
t.equal(feed.xml(), expectedOutput.relatedItem.trim());
});
test('related item', function (t) {
t.plan(1);
const feed = new TR(baseOptions);
feed.item({
title: 'item title',
image_url: 'http://example.com/example.png',
url: 'http://example.com/article4?this&that',
author: 'LightAir',
date: 'May 27, 2018 00:00 AM',
content: '<p>hello</p>',
relatedInfinity: true,
related: relatedOptions
});
t.equal(feed.xml(), expectedOutput.relatedItemInfinity.trim());
});
test('menu', function (t) {
t.plan(1);
const feed = new TR(baseOptions);
feed.item({
title: 'item title',
image_url: 'http://example.com/example.png',
url: 'http://example.com/article4?this&that',
author: 'LightAir',
date: 'May 27, 2018 00:00 AM',
content: '<p>hello</p>',
relatedInfinity: true,
menu: [{
link: 'http://example.com/',
text: 'Главная',
}, {
link: 'http://example.com/about',
text: 'О сайте',
}],
related: relatedOptions
});
feed.item({});
t.equal(feed.xml(), expectedOutput.menu.trim());
});
test('goals', function (t) {
t.plan(1);
const feed = new TR(baseOptions);
feed.item({
title: 'item title',
image_url: 'http://example.com/example.png',
url: 'http://example.com/article4?this&that',
author: 'vvm.space',
date: 'May 27, 2018 00:00 AM',
menu: '<a href="http://example.com/page1.html">Текст ссылки</a> <a href="http://example.com/page2.html">Текст ссылки</a>',
goals: [{
type: 'yandex',
id: 'turbo-goal-id',
counter_id: '12345',
name: 'order',
}],
content: '<p>hello</p>',
related: relatedOptions
});
t.equal(feed.xml(), expectedOutput.goal.trim());
});
test('image caption', function (t) {
t.plan(1);
const feed = new TR(baseOptions);
feed.item({
title: 'item title',
image_url: 'http://example.com/example.png',
image_caption: 'this is image caption',
url: 'http://example.com/article4?this&that',
author: 'LightAir',
date: 'May 27, 2018 00:00 AM',
menu: '<a href="http://example.com/page1.html">Текст ссылки</a> <a href="http://example.com/page2.html">Текст ссылки</a>',
content: '<p>hello</p>',
related: relatedOptions
});
t.equal(feed.xml(), expectedOutput.imageCaption.trim());
});
test('subheading', function (t) {
t.plan(1);
const feed = new TR(baseOptions);
feed.item({
title: 'item title',
subheading: 'Subheading',
});
t.equal(feed.xml(), expectedOutput.subheading.trim());
});
test('breadcrumbs', function (t) {
t.plan(1);
const feed = new TR(baseOptions);
feed.item({
title: 'Суп с картофелем',
image_url: 'https://example.com/example.png',
breadcrumbs: [{
link: 'https://example.com/',
text: 'Главная',
}, {
link: 'https://example.com/soups/',
text: 'Супы',
}, {
link: 'https://example.com/soups/with-potatoes/',
text: 'Суп с картофелем'
}],
url: 'https://example.com/soups/with-potatoes/',
author: 'LightAir',
date: 'May 27, 2018 00:00 AM',
content: '<p>Для приготовления супа с картофелем, возьмите</p>'
});
t.equal(feed.xml(), expectedOutput.breadcrumbs.trim());
});