link fe: move @ta encoding into lib

This commit is contained in:
Fang 2020-02-06 23:51:24 +01:00
parent 1490e415c4
commit b0759ad8bc
No known key found for this signature in database
GPG Key ID: EB035760C1BBA972
2 changed files with 40 additions and 39 deletions

View File

@ -1,7 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import { uuid } from '/lib/util';
import { uuid, stringToTa } from '/lib/util';
import { store } from '/store';
import moment from 'moment';
@ -102,7 +102,7 @@ class UrbitApi {
}
getCommentsPage(path, url, page) {
const strictUrl = this.encodeUrl(url);
const strictUrl = stringToTa(url);
const endpoint = '/json/' + page + '/discussions/' + strictUrl + path;
this.bindLinkView(endpoint,
(res) => {
@ -129,7 +129,7 @@ class UrbitApi {
}
getSubmission(path, url, callback) {
const strictUrl = this.encodeUrl(url);
const strictUrl = stringToTa(url);
const endpoint = '/json/0/submission/' + strictUrl + path;
this.bindLinkView(endpoint,
(res) => {
@ -174,42 +174,6 @@ class UrbitApi {
});
}
//TODO into lib?
// encode the url into @ta-safe format, using logic from +wood
encodeUrl(url) {
let strictUrl = '';
for (let i = 0; i < url.length; i++) {
const char = url[i];
let add = '';
switch (char) {
case ' ':
add = '.';
break;
case '.':
add = '~.';
break;
case '~':
add = '~~';
break;
default:
const charCode = url.charCodeAt(i);
if (
(charCode >= 97 && charCode <= 122) || // a-z
(charCode >= 48 && charCode <= 57) || // 0-9
char === '-'
) {
add = char;
} else {
//TODO behavior for unicode doesn't match +wood's,
// but we can probably get away with that for now.
add = '~' + charCode.toString(16) + '.';
}
}
strictUrl = strictUrl + add;
}
return '~.' + strictUrl;
}
}
export let api = new UrbitApi();

View File

@ -19,6 +19,43 @@ export function isPatTa(str) {
return !!r;
}
// encode the string into @ta-safe format, using logic from +wood.
// for example, 'some Chars!' becomes '~.some.~43.hars~21.'
//
export function stringToTa(string) {
let out = '';
for (let i = 0; i < string.length; i++) {
const char = string[i];
let add = '';
switch (char) {
case ' ':
add = '.';
break;
case '.':
add = '~.';
break;
case '~':
add = '~~';
break;
default:
const charCode = string.charCodeAt(i);
if (
(charCode >= 97 && charCode <= 122) || // a-z
(charCode >= 48 && charCode <= 57) || // 0-9
char === '-'
) {
add = char;
} else {
//TODO behavior for unicode doesn't match +wood's,
// but we can probably get away with that for now.
add = '~' + charCode.toString(16) + '.';
}
}
out = out + add;
}
return '~.' + out;
}
/*
Goes from:
~2018.7.17..23.15.09..5be5 // urbit @da