Compare commits

...

35 Commits

Author SHA1 Message Date
f090cc076e Merge branch 'maunium:master' into feat/search-focus 2023-01-08 21:53:27 +01:00
f59406a47a Add missing parameter to getting sticker sets. Fixes #51 2022-11-15 12:58:38 +02:00
31cc608a2b use visibility from widget API to autofocus on frame opening when required 2022-02-06 19:08:03 +01:00
9b87f7436f handle focus for iframe 2022-02-06 18:41:40 +01:00
26ab8e2821 properly handle mobile devices for autofocus 2022-02-06 16:25:38 +01:00
e30535a975 ignore autofocus issues on mobiles (disabled by design) 2022-02-06 16:04:39 +01:00
a197bda145 remove autofocus property for android 2022-02-06 15:58:28 +01:00
909aaf8d44 improve for mobile support 2022-02-06 15:47:38 +01:00
ad26574762 use flex instead of absolute for search field css 2022-02-06 12:19:17 +01:00
fed4f08218 handle autofocus search + setting on/off 2022-02-06 12:18:11 +01:00
41f0432e8d handle resetting search field 2022-02-06 12:17:29 +01:00
99ced8878a Merge remote-tracking branch 'salixor/feat/search-box' 2021-10-03 12:52:55 +03:00
046779d102 Update some metadata 2021-10-03 12:45:37 +03:00
ef844a0ff8 Update dependencies 2021-10-03 12:42:11 +03:00
502d91fc75 Merge remote-tracking branch 'p1gp1g/dev' 2021-10-03 11:50:47 +03:00
591137ccb3 Merge remote-tracking branch 'celogeek/fixes-ios-and-more' 2021-10-03 11:50:27 +03:00
f29c165357 Merge remote-tracking branch 'aWeinzierl/fix-encoding' 2021-10-03 11:49:53 +03:00
S1m
7939793351 Remove parseQuery and use params 2021-09-30 08:52:41 +02:00
S1m
e0d895f22a Check packfile protocole scheme + rm semicolons 2021-09-20 08:58:20 +02:00
S1m
5d3c7d1e2f Allow using external index.json and stickerpack 2021-09-19 17:35:28 +02:00
ec8eeeeaf5 Fix scrolling topbar on Firefox
(and possibly break it on other browsers)
2021-04-22 19:12:54 +03:00
57fde6fcad Assume https if homeserver URL doesn't have protocol 2021-04-22 19:12:54 +03:00
9443e79e97 fix display of packs with sticker-import --list 2021-02-07 17:52:55 +01:00
85813b22e5 add missing msgtype = m.sticker
On iOS the message is sent twice, with a duplicate event_id.
It cause error on logs, in different places (synapse, mautrix, ...)

It required to fix the already existing json or reimport the stickers.

The "packs/scalar*" example already include this field, and it works.
2021-02-07 17:50:50 +01:00
569d9815c6 remove redundant utf-8 setting 2021-01-28 00:06:58 +01:00
0f7b678f57 Use utf8-encoding whenever JSON is processed 2021-01-27 23:31:33 +01:00
b884a9c387 Set encoding to utf-8 when saving json file for stickerpack
Fixes UnicodeEncodeError with Windows 10 when trying to import sticker packs caused by the default encoding scheme in Windows
2021-01-27 22:09:15 +01:00
ba0096275c Update README.md 2021-01-24 13:14:59 +02:00
3916ade97b Merge pull request #26 from auscompgeek/patch-1
Show sticker body in hover tooltip
2021-01-20 23:58:00 +02:00
dab2420cd4 Merge pull request #28 from SpiritCroc/fix-import
Rename import.py, since import is a keyword
2021-01-20 23:57:28 +02:00
601d2acc32 Rename import.py, since import is a keyword
from sticker.import import cmd
                 ^
SyntaxError: invalid syntax

Fixes https://github.com/maunium/stickerpicker/issues/27.
2021-01-19 17:12:06 +01:00
21d4f5cce6 Show sticker body in hover tooltip 2020-12-30 19:56:31 +11:00
9350d5f27b Update sass style file 2020-12-17 09:31:29 +01:00
add27513fe Implement stickers search 2020-12-17 01:01:32 +01:00
66d5b90ea1 Re-format CSS for readability in PR 2020-12-17 01:00:22 +01:00
20 changed files with 551 additions and 2218 deletions

View File

@ -11,8 +11,14 @@ For setup and usage instructions, please visit the [wiki](https://github.com/mau
* [Enabling the widget](https://github.com/maunium/stickerpicker/wiki/Enabling-the-widget) * [Enabling the widget](https://github.com/maunium/stickerpicker/wiki/Enabling-the-widget)
* [Hosting on GitHub pages](https://github.com/maunium/stickerpicker/wiki/Hosting-on-GitHub-pages) * [Hosting on GitHub pages](https://github.com/maunium/stickerpicker/wiki/Hosting-on-GitHub-pages)
If you prefer video tutorials, [Brodie Robertson](https://www.youtube.com/c/BrodieRobertson) has made a great video on setting up the picker and creating some packs: https://youtu.be/Yz3H6KJTEI0.
## Comparison with other sticker pickers ## Comparison with other sticker pickers
* Scalar is the default integration manager in Element, which can't be self-hosted and only supports predefined sticker packs.
* [Dimension](https://github.com/turt2live/matrix-dimension) is an alternate integration manager. It can be self-hosted, but it's more difficult than Maunium sticker picker.
* Maunium sticker picker is just a sticker picker rather than a full integration manager. It's much simpler than integration managers, but currently has to be set up manually per-user.
| Feature | Scalar | Dimension | Maunium sticker picker | | Feature | Scalar | Dimension | Maunium sticker picker |
|---------------------------------|--------|-----------|------------------------| |---------------------------------|--------|-----------|------------------------|
| Free software | ❌ | ✔️ | ✔️ | | Free software | ❌ | ✔️ | ✔️ |

View File

@ -45,9 +45,10 @@ setuptools.setup(
"Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
], ],
entry_points={"console_scripts": [ entry_points={"console_scripts": [
"sticker-import=sticker.import:cmd", "sticker-import=sticker.stickerimport:cmd",
"sticker-pack=sticker.pack:cmd", "sticker-pack=sticker.pack:cmd",
]}, ]},
) )

View File

@ -42,6 +42,7 @@ if TYPE_CHECKING:
url: str url: str
info: MediaInfo info: MediaInfo
id: str id: str
msgtype: str
else: else:
MediaInfo = None MediaInfo = None
StickerInfo = None StickerInfo = None
@ -59,6 +60,8 @@ async def load_config(path: str) -> None:
homeserver_url = input("Homeserver URL: ") homeserver_url = input("Homeserver URL: ")
access_token = input("Access token: ") access_token = input("Access token: ")
whoami_url = URL(homeserver_url) / "_matrix" / "client" / "r0" / "account" / "whoami" whoami_url = URL(homeserver_url) / "_matrix" / "client" / "r0" / "account" / "whoami"
if whoami_url.scheme not in ("https", "http"):
whoami_url = whoami_url.with_scheme("https")
user_id = await whoami(whoami_url, access_token) user_id = await whoami(whoami_url, access_token)
with open(path, "w") as config_file: with open(path, "w") as config_file:
json.dump({ json.dump({

View File

@ -13,6 +13,7 @@
# #
# You should have received a copy of the GNU Affero General Public License # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>. # along with this program. If not, see <https://www.gnu.org/licenses/>.
from functools import partial
from io import BytesIO from io import BytesIO
import os.path import os.path
import json import json
@ -21,6 +22,7 @@ from PIL import Image
from . import matrix from . import matrix
open_utf8 = partial(open, encoding='UTF-8')
def convert_image(data: bytes) -> (bytes, int, int): def convert_image(data: bytes) -> (bytes, int, int):
image: Image.Image = Image.open(BytesIO(data)).convert("RGBA") image: Image.Image = Image.open(BytesIO(data)).convert("RGBA")
@ -41,7 +43,7 @@ def convert_image(data: bytes) -> (bytes, int, int):
def add_to_index(name: str, output_dir: str) -> None: def add_to_index(name: str, output_dir: str) -> None:
index_path = os.path.join(output_dir, "index.json") index_path = os.path.join(output_dir, "index.json")
try: try:
with open(index_path) as index_file: with open_utf8(index_path) as index_file:
index_data = json.load(index_file) index_data = json.load(index_file)
except (FileNotFoundError, json.JSONDecodeError): except (FileNotFoundError, json.JSONDecodeError):
index_data = {"packs": []} index_data = {"packs": []}
@ -49,7 +51,7 @@ def add_to_index(name: str, output_dir: str) -> None:
index_data["homeserver_url"] = matrix.homeserver_url index_data["homeserver_url"] = matrix.homeserver_url
if name not in index_data["packs"]: if name not in index_data["packs"]:
index_data["packs"].append(name) index_data["packs"].append(name)
with open(index_path, "w") as index_file: with open_utf8(index_path, "w") as index_file:
json.dump(index_data, index_file, indent=" ") json.dump(index_data, index_file, indent=" ")
print(f"Added {name} to {index_path}") print(f"Added {name} to {index_path}")
@ -74,4 +76,5 @@ def make_sticker(mxc: str, width: int, height: int, size: int,
"mimetype": "image/png", "mimetype": "image/png",
}, },
}, },
"msgtype": "m.sticker",
} }

View File

@ -93,7 +93,7 @@ async def main(args: argparse.Namespace) -> None:
dirname = os.path.basename(os.path.abspath(args.path)) dirname = os.path.basename(os.path.abspath(args.path))
meta_path = os.path.join(args.path, "pack.json") meta_path = os.path.join(args.path, "pack.json")
try: try:
with open(meta_path) as pack_file: with util.open_utf8(meta_path) as pack_file:
pack = json.load(pack_file) pack = json.load(pack_file)
print(f"Loaded existing pack meta from {meta_path}") print(f"Loaded existing pack meta from {meta_path}")
except FileNotFoundError: except FileNotFoundError:
@ -112,14 +112,14 @@ async def main(args: argparse.Namespace) -> None:
if sticker: if sticker:
pack["stickers"].append(sticker) pack["stickers"].append(sticker)
with open(meta_path, "w") as pack_file: with util.open_utf8(meta_path, "w") as pack_file:
json.dump(pack, pack_file) json.dump(pack, pack_file)
print(f"Wrote pack to {meta_path}") print(f"Wrote pack to {meta_path}")
if args.add_to_index: if args.add_to_index:
picker_file_name = f"{pack['id']}.json" picker_file_name = f"{pack['id']}.json"
picker_pack_path = os.path.join(args.add_to_index, picker_file_name) picker_pack_path = os.path.join(args.add_to_index, picker_file_name)
with open(picker_pack_path, "w") as pack_file: with util.open_utf8(picker_pack_path, "w") as pack_file:
json.dump(pack, pack_file) json.dump(pack, pack_file)
print(f"Copied pack to {picker_pack_path}") print(f"Copied pack to {picker_pack_path}")
util.add_to_index(picker_file_name, args.add_to_index) util.add_to_index(picker_file_name, args.add_to_index)

View File

@ -19,12 +19,12 @@ import json
index_path = "../web/packs/index.json" index_path = "../web/packs/index.json"
try: try:
with open(index_path) as index_file: with util.open_utf8(index_path) as index_file:
index_data = json.load(index_file) index_data = json.load(index_file)
except (FileNotFoundError, json.JSONDecodeError): except (FileNotFoundError, json.JSONDecodeError):
index_data = {"packs": []} index_data = {"packs": []}
with open(sys.argv[-1]) as file: with util.open_utf8(sys.argv[-1]) as file:
data = json.load(file) data = json.load(file)
for pack in data["assets"]: for pack in data["assets"]:
@ -45,12 +45,12 @@ for pack in data["assets"]:
} }
filename = f"scalar-{pack['name'].replace(' ', '_')}.json" filename = f"scalar-{pack['name'].replace(' ', '_')}.json"
pack_path = f"web/packs/{filename}" pack_path = f"web/packs/{filename}"
with open(pack_path, "w") as pack_file: with util.open_utf8(pack_path, "w") as pack_file:
json.dump(pack_data, pack_file) json.dump(pack_data, pack_file)
print(f"Wrote {title} to {pack_path}") print(f"Wrote {title} to {pack_path}")
if filename not in index_data["packs"]: if filename not in index_data["packs"]:
index_data["packs"].append(filename) index_data["packs"].append(filename)
with open(index_path, "w") as index_file: with util.open_utf8(index_path, "w") as index_file:
json.dump(index_data, index_file, indent=" ") json.dump(index_data, index_file, indent=" ")
print(f"Updated {index_path}") print(f"Updated {index_path}")

View File

@ -71,7 +71,7 @@ async def reupload_pack(client: TelegramClient, pack: StickerSetFull, output_dir
already_uploaded = {} already_uploaded = {}
try: try:
with open(pack_path) as pack_file: with util.open_utf8(pack_path) as pack_file:
existing_pack = json.load(pack_file) existing_pack = json.load(pack_file)
already_uploaded = {int(sticker["net.maunium.telegram.sticker"]["id"]): sticker already_uploaded = {int(sticker["net.maunium.telegram.sticker"]["id"]): sticker
for sticker in existing_pack["stickers"]} for sticker in existing_pack["stickers"]}
@ -99,7 +99,7 @@ async def reupload_pack(client: TelegramClient, pack: StickerSetFull, output_dir
doc["body"] = sticker.emoticon doc["body"] = sticker.emoticon
doc["net.maunium.telegram.sticker"]["emoticons"].append(sticker.emoticon) doc["net.maunium.telegram.sticker"]["emoticons"].append(sticker.emoticon)
with open(pack_path, "w") as pack_file: with util.open_utf8(pack_path, "w") as pack_file:
json.dump({ json.dump({
"title": pack.set.title, "title": pack.set.title,
"id": f"tg-{pack.set.id}", "id": f"tg-{pack.set.id}",
@ -138,11 +138,12 @@ async def main(args: argparse.Namespace) -> None:
if args.list: if args.list:
stickers: AllStickers = await client(GetAllStickersRequest(hash=0)) stickers: AllStickers = await client(GetAllStickersRequest(hash=0))
index = 1 index = 1
width = len(str(stickers.sets)) width = len(str(len(stickers.sets)))
print("Your saved sticker packs:") print("Your saved sticker packs:")
for saved_pack in stickers.sets: for saved_pack in stickers.sets:
print(f"{index:>{width}}. {saved_pack.title} " print(f"{index:>{width}}. {saved_pack.title} "
f"(t.me/addstickers/{saved_pack.short_name})") f"(t.me/addstickers/{saved_pack.short_name})")
index += 1
elif args.pack[0]: elif args.pack[0]:
input_packs = [] input_packs = []
for pack_url in args.pack[0]: for pack_url in args.pack[0]:
@ -152,7 +153,7 @@ async def main(args: argparse.Namespace) -> None:
return return
input_packs.append(InputStickerSetShortName(short_name=match.group(1))) input_packs.append(InputStickerSetShortName(short_name=match.group(1)))
for input_pack in input_packs: for input_pack in input_packs:
pack: StickerSetFull = await client(GetStickerSetRequest(input_pack)) pack: StickerSetFull = await client(GetStickerSetRequest(input_pack, hash=0))
await reupload_pack(client, pack, args.output_dir) await reupload_pack(client, pack, args.output_dir)
else: else:
parser.print_help() parser.print_help()

23
web/esinstall.js Normal file
View File

@ -0,0 +1,23 @@
const { install, printStats } = require("esinstall")
install(
[{
specifier: "htm/preact",
all: false,
default: false,
namespace: false,
named: ["html", "render", "Component"],
}],
{
dest: "./lib",
sourceMap: false,
treeshake: true,
verbose: true,
}
).then(data => {
const oldPrefix = "web_modules/"
const newPrefix = "lib/"
const spaces = " ".repeat(oldPrefix.length - newPrefix.length)
console.log("Installation complete")
console.log(printStats(data.stats).replace(oldPrefix, newPrefix + spaces))
})

File diff suppressed because one or more lines are too long

View File

@ -4,28 +4,16 @@
"description": "A fast and simple Matrix sticker picker widget", "description": "A fast and simple Matrix sticker picker widget",
"repository": "https://github.com/maunium/stickerpicker", "repository": "https://github.com/maunium/stickerpicker",
"author": "Tulir Asokan <tulir@maunium.net>", "author": "Tulir Asokan <tulir@maunium.net>",
"license": "MPL-2.0", "license": "AGPL-3.0-or-later",
"private": true, "private": true,
"scripts": { "scripts": {
"snowpack": "snowpack", "esinstall": "node ./esinstall.js",
"sass": "node-sass -o style style/*.sass --output-style compressed" "sass": "sass --no-source-map --style=compressed style/"
},
"snowpack": {
"install": [
"htm/preact"
],
"installOptions": {
"sourceMap": false,
"dest": "lib",
"treeshake": true
}
}, },
"dependencies": { "dependencies": {
"htm": "^3.0.4", "htm": "^3.1.0",
"preact": "^10.4.8", "preact": "^10.5.14",
"snowpack": "^2.10.3" "esinstall": "^1.1.7",
}, "sass": "^1.42.1"
"devDependencies": {
"node-sass": "^4.14.1"
} }
} }

1
web/res/reset.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM5.354 4.646a.5.5 0 1 0-.708.708L7.293 8l-2.647 2.646a.5.5 0 0 0 .708.708L8 8.707l2.646 2.647a.5.5 0 0 0 .708-.708L8.707 8l2.647-2.646a.5.5 0 0 0-.708-.708L8 7.293 5.354 4.646z"/></svg>

After

Width:  |  Height:  |  Size: 313 B

1
web/res/search.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M9.145 18.29c-5.042 0-9.145-4.102-9.145-9.145s4.103-9.145 9.145-9.145 9.145 4.103 9.145 9.145-4.102 9.145-9.145 9.145zm0-15.167c-3.321 0-6.022 2.702-6.022 6.022s2.702 6.022 6.022 6.022 6.023-2.702 6.023-6.022-2.702-6.022-6.023-6.022zm9.263 12.443c-.817 1.176-1.852 2.188-3.046 2.981l5.452 5.453 3.014-3.013-5.42-5.421z"/></svg>

After

Width:  |  Height:  |  Size: 419 B

View File

@ -15,12 +15,20 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
import { html, render, Component } from "../lib/htm/preact.js" import { html, render, Component } from "../lib/htm/preact.js"
import { Spinner } from "./spinner.js" import { Spinner } from "./spinner.js"
import { shouldAutofocusSearchBar, shouldDisplayAutofocusSearchBar, SearchBox } from "./search-box.js"
import { checkMobileSafari } from "./user-agent-detect.js"
import * as widgetAPI from "./widget-api.js" import * as widgetAPI from "./widget-api.js"
import * as frequent from "./frequently-used.js" import * as frequent from "./frequently-used.js"
// The base URL for fetching packs. The app will first fetch ${PACK_BASE_URL}/index.json, // The base URL for fetching packs. The app will first fetch ${PACK_BASE_URL}/index.json,
// then ${PACK_BASE_URL}/${packFile} for each packFile in the packs object of the index.json file. // then ${PACK_BASE_URL}/${packFile} for each packFile in the packs object of the index.json file.
const PACKS_BASE_URL = "packs" const PACKS_BASE_URL = "packs"
let INDEX = `${PACKS_BASE_URL}/index.json`
const params = new URLSearchParams(document.location.search)
if (params.has('config')) {
INDEX = params.get("config")
}
// This is updated from packs/index.json // This is updated from packs/index.json
let HOMESERVER_URL = "https://matrix-client.matrix.org" let HOMESERVER_URL = "https://matrix-client.matrix.org"
@ -28,23 +36,33 @@ const makeThumbnailURL = mxc => `${HOMESERVER_URL}/_matrix/media/r0/thumbnail/${
// We need to detect iOS webkit because it has a bug related to scrolling non-fixed divs // We need to detect iOS webkit because it has a bug related to scrolling non-fixed divs
// This is also used to fix scrolling to sections on Element iOS // This is also used to fix scrolling to sections on Element iOS
const isMobileSafari = navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/) const isMobileSafari = checkMobileSafari()
export const parseQuery = str => Object.fromEntries( // We need to detect iOS webkit / Android because autofocusing a field does not open
str.split("&") // the device keyboard by design, making the option obsolete
.map(part => part.split("=")) const shouldAutofocusOption = shouldAutofocusSearchBar()
.map(([key, value = ""]) => [key, value])) const displayAutofocusOption = shouldDisplayAutofocusSearchBar()
const supportedThemes = ["light", "dark", "black"] const supportedThemes = ["light", "dark", "black"]
const defaultState = {
packs: [],
loading: true,
error: null,
}
const defaultSearchState = {
searchTerm: null,
filteredPacks: null
}
class App extends Component { class App extends Component {
constructor(props) { constructor(props) {
super(props) super(props)
this.defaultTheme = parseQuery(location.search.substr(1)).theme this.defaultTheme = params.get("theme")
this.state = { this.state = {
packs: [], ...defaultState,
loading: true, ...defaultSearchState,
error: null,
stickersPerRow: parseInt(localStorage.mauStickersPerRow || "4"), stickersPerRow: parseInt(localStorage.mauStickersPerRow || "4"),
theme: localStorage.mauStickerThemeOverride || this.defaultTheme, theme: localStorage.mauStickerThemeOverride || this.defaultTheme,
frequentlyUsed: { frequentlyUsed: {
@ -65,6 +83,8 @@ class App extends Component {
this.imageObserver = null this.imageObserver = null
this.packListRef = null this.packListRef = null
this.navRef = null this.navRef = null
this.searchStickers = this.searchStickers.bind(this)
this.resetSearch = this.resetSearch.bind(this)
this.sendSticker = this.sendSticker.bind(this) this.sendSticker = this.sendSticker.bind(this)
this.navScroll = this.navScroll.bind(this) this.navScroll = this.navScroll.bind(this)
this.reloadPacks = this.reloadPacks.bind(this) this.reloadPacks = this.reloadPacks.bind(this)
@ -89,6 +109,33 @@ class App extends Component {
localStorage.mauFrequentlyUsedStickerCache = JSON.stringify(stickers.map(sticker => [sticker.id, sticker])) localStorage.mauFrequentlyUsedStickerCache = JSON.stringify(stickers.map(sticker => [sticker.id, sticker]))
} }
// Search
resetSearch() {
this.setState({ ...defaultSearchState })
}
searchStickers(searchTerm) {
const sanitizeString = s => s.toLowerCase().trim()
const sanitizedSearch = sanitizeString(searchTerm)
const allPacks = [this.state.frequentlyUsed, ...this.state.packs]
const packsWithFilteredStickers = allPacks.map(pack => ({
...pack,
stickers: pack.stickers.filter(sticker =>
sanitizeString(sticker.body).includes(sanitizedSearch) ||
sanitizeString(sticker.id).includes(sanitizedSearch)
),
}))
const filteredPacks = packsWithFilteredStickers.filter(({ stickers }) => !!stickers.length)
this.setState({ searchTerm, filteredPacks })
}
// End search
// Settings
setStickersPerRow(val) { setStickersPerRow(val) {
localStorage.mauStickersPerRow = val localStorage.mauStickersPerRow = val
document.documentElement.style.setProperty("--stickers-per-row", localStorage.mauStickersPerRow) document.documentElement.style.setProperty("--stickers-per-row", localStorage.mauStickersPerRow)
@ -108,16 +155,23 @@ class App extends Component {
} }
} }
setAutofocusSearchBar(checked) {
localStorage.mauAutofocusSearchBar = checked
}
// End settings
reloadPacks() { reloadPacks() {
this.imageObserver.disconnect() this.imageObserver.disconnect()
this.sectionObserver.disconnect() this.sectionObserver.disconnect()
this.setState({ packs: [] }) this.setState({ packs: defaultState.packs })
this.resetSearch()
this._loadPacks(true) this._loadPacks(true)
} }
_loadPacks(disableCache = false) { _loadPacks(disableCache = false) {
const cache = disableCache ? "no-cache" : undefined const cache = disableCache ? "no-cache" : undefined
fetch(`${PACKS_BASE_URL}/index.json`, { cache }).then(async indexRes => { fetch(INDEX, { cache }).then(async indexRes => {
if (indexRes.status >= 400) { if (indexRes.status >= 400) {
this.setState({ this.setState({
loading: false, loading: false,
@ -129,7 +183,12 @@ class App extends Component {
HOMESERVER_URL = indexData.homeserver_url || HOMESERVER_URL HOMESERVER_URL = indexData.homeserver_url || HOMESERVER_URL
// TODO only load pack metadata when scrolled into view? // TODO only load pack metadata when scrolled into view?
for (const packFile of indexData.packs) { for (const packFile of indexData.packs) {
const packRes = await fetch(`${PACKS_BASE_URL}/${packFile}`, { cache }) let packRes
if (packFile.startsWith("https://") || packFile.startsWith("http://")) {
packRes = await fetch(packFile, { cache })
} else {
packRes = await fetch(`${PACKS_BASE_URL}/${packFile}`, { cache })
}
const packData = await packRes.json() const packData = await packRes.json()
for (const sticker of packData.stickers) { for (const sticker of packData.stickers) {
this.stickersByID.set(sticker.id, sticker) this.stickersByID.set(sticker.id, sticker)
@ -173,6 +232,9 @@ class App extends Component {
for (const entry of intersections) { for (const entry of intersections) {
const packID = entry.target.getAttribute("data-pack-id") const packID = entry.target.getAttribute("data-pack-id")
const navElement = document.getElementById(`nav-${packID}`) const navElement = document.getElementById(`nav-${packID}`)
if (!navElement) {
continue
}
if (entry.isIntersecting) { if (entry.isIntersecting) {
navElement.classList.add("visible") navElement.classList.add("visible")
const bb = navElement.getBoundingClientRect() const bb = navElement.getBoundingClientRect()
@ -216,15 +278,21 @@ class App extends Component {
const sticker = this.stickersByID.get(id) const sticker = this.stickersByID.get(id)
frequent.add(id) frequent.add(id)
this.updateFrequentlyUsed() this.updateFrequentlyUsed()
this.resetSearch()
widgetAPI.sendSticker(sticker) widgetAPI.sendSticker(sticker)
} }
navScroll(evt) { navScroll(evt) {
this.navRef.scrollLeft += evt.deltaY * 12 this.navRef.scrollLeft += evt.deltaY
} }
render() { render() {
const theme = `theme-${this.state.theme}` const theme = `theme-${this.state.theme}`
const filterActive = !!this.state.filteredPacks
const packs = filterActive ? this.state.filteredPacks : [this.state.frequentlyUsed, ...this.state.packs]
const noPacksForSearch = filterActive && packs.length === 0
if (this.state.loading) { if (this.state.loading) {
return html`<main class="spinner ${theme}"><${Spinner} size=${80} green /></main>` return html`<main class="spinner ${theme}"><${Spinner} size=${80} green /></main>`
} else if (this.state.error) { } else if (this.state.error) {
@ -235,15 +303,21 @@ class App extends Component {
} else if (this.state.packs.length === 0) { } else if (this.state.packs.length === 0) {
return html`<main class="empty ${theme}"><h1>No packs found 😿</h1></main>` return html`<main class="empty ${theme}"><h1>No packs found 😿</h1></main>`
} }
return html`<main class="has-content ${theme}"> return html`<main class="has-content ${theme}">
<nav onWheel=${this.navScroll} ref=${elem => this.navRef = elem}> <nav onWheel=${this.navScroll} ref=${elem => this.navRef = elem}>
<${NavBarItem} pack=${this.state.frequentlyUsed} iconOverride="recent" /> <${NavBarItem} pack=${this.state.frequentlyUsed} iconOverride="recent" />
${this.state.packs.map(pack => html`<${NavBarItem} id=${pack.id} pack=${pack}/>`)} ${this.state.packs.map(pack => html`<${NavBarItem} id=${pack.id} pack=${pack}/>`)}
<${NavBarItem} pack=${{ id: "settings", title: "Settings" }} iconOverride="settings" /> <${NavBarItem} pack=${{ id: "settings", title: "Settings" }} iconOverride="settings" />
</nav> </nav>
<${SearchBox}
value=${this.state.searchTerm}
onSearch=${this.searchStickers}
onReset=${this.resetSearch}
/>
<div class="pack-list ${isMobileSafari ? "ios-safari-hack" : ""}" ref=${elem => this.packListRef = elem}> <div class="pack-list ${isMobileSafari ? "ios-safari-hack" : ""}" ref=${elem => this.packListRef = elem}>
<${Pack} pack=${this.state.frequentlyUsed} send=${this.sendSticker} /> ${noPacksForSearch ? html`<div class="search-empty"><h1>No stickers match your search</h1></div>` : null}
${this.state.packs.map(pack => html`<${Pack} id=${pack.id} pack=${pack} send=${this.sendSticker} />`)} ${packs.map(pack => html`<${Pack} id=${pack.id} pack=${pack} send=${this.sendSticker} />`)}
<${Settings} app=${this}/> <${Settings} app=${this}/>
</div> </div>
</main>` </main>`
@ -270,6 +344,14 @@ const Settings = ({ app }) => html`
<option value="black">Black</option> <option value="black">Black</option>
</select> </select>
</div> </div>
${displayAutofocusOption ? html`<div>
Autofocus search bar:
<input
type="checkbox"
checked=${shouldAutofocusOption}
onChange=${evt => app.setAutofocusSearchBar(evt.target.checked)}
/>
</div>` : null}
</div> </div>
</section> </section>
` `
@ -309,7 +391,7 @@ const Pack = ({ pack, send }) => html`
const Sticker = ({ content, send }) => html` const Sticker = ({ content, send }) => html`
<div class="sticker" onClick=${send} data-sticker-id=${content.id}> <div class="sticker" onClick=${send} data-sticker-id=${content.id}>
<img data-src=${makeThumbnailURL(content.url)} alt=${content.body} /> <img data-src=${makeThumbnailURL(content.url)} alt=${content.body} title=${content.body} />
</div> </div>
` `

89
web/src/search-box.js Normal file
View File

@ -0,0 +1,89 @@
// maunium-stickerpicker - A fast and simple Matrix sticker picker widget.
// Copyright (C) 2020 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import { html, Component } from "../lib/htm/preact.js"
import { checkMobileSafari, checkAndroid } from "./user-agent-detect.js"
export function shouldDisplayAutofocusSearchBar() {
return !checkMobileSafari() && !checkAndroid()
}
export function shouldAutofocusSearchBar() {
return localStorage.mauAutofocusSearchBar === 'true' && shouldDisplayAutofocusSearchBar()
}
export function focusSearchBar() {
const inputInWebView = document.querySelector('.search-box input')
if (inputInWebView && shouldAutofocusSearchBar()) {
inputInWebView.focus()
}
}
export class SearchBox extends Component {
constructor(props) {
super(props)
this.autofocus = shouldAutofocusSearchBar()
this.value = props.value
this.onSearch = props.onSearch
this.onReset = props.onReset
this.search = this.search.bind(this)
this.clearSearch = this.clearSearch.bind(this)
}
componentDidMount() {
focusSearchBar()
}
componentWillReceiveProps(props) {
this.value = props.value
}
search(e) {
if (e.key === "Escape") {
this.clearSearch()
return
}
this.onSearch(e.target.value)
}
clearSearch() {
this.onReset()
}
render() {
const isEmpty = !this.value
const className = `icon-display ${isEmpty ? null : 'reset-click-zone'}`
const title = isEmpty ? null : 'Click to reset'
const onClick = isEmpty ? null : this.clearSearch
const iconToDisplay = `icon-${isEmpty ? 'search' : 'reset'}`
return html`
<div class="search-box">
<input
placeholder="Find stickers …"
value=${this.value}
onKeyUp=${this.search}
autoFocus=${this.autofocus}
/>
<div class=${className} title=${title} onClick=${onClick}>
<span class="icon ${iconToDisplay}" />
</div>
</div>
`
}
}

View File

@ -0,0 +1,18 @@
export const getUserAgent = () => navigator.userAgent || navigator.vendor || window.opera
export const checkiOSDevice = () => {
const agent = getUserAgent()
return agent.match(/(iPod|iPhone|iPad)/)
}
export const checkMobileSafari = () => {
const agent = getUserAgent()
return agent.match(/(iPod|iPhone|iPad)/) && agent.match(/AppleWebKit/)
}
export const checkAndroid = () => {
const agent = getUserAgent()
return agent.match(/android/i)
}
export const checkMobileDevice = () => checkiOSDevice() || checkAndroid()

View File

@ -13,6 +13,8 @@
// //
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
import { focusSearchBar } from "./search-box.js"
let widgetId = null let widgetId = null
window.onmessage = event => { window.onmessage = event => {
@ -33,10 +35,12 @@ window.onmessage = event => {
widgetId = request.widgetId widgetId = request.widgetId
} }
let response let response = {}
if (request.action === "visibility") { if (request.action === "visibility") { // visibility of the widget changed
response = {} if (request.visible) {
focusSearchBar() // we have to re-focus the search bar when appropriate
}
} else if (request.action === "capabilities") { } else if (request.action === "capabilities") {
response = { capabilities: ["m.sticker"] } response = { capabilities: ["m.sticker"] }
} else { } else {

View File

@ -1 +1 @@
*{font-family:sans-serif}body{margin:0}h1{font-size:1rem}:root{--stickers-per-row: 4;--sticker-size: calc(100vw / var(--stickers-per-row))}main{color:var(--text-color)}main.spinner{margin-top:5rem}main.error,main.empty{margin:2rem}main.empty{text-align:center}main.has-content{position:fixed;top:0;left:0;right:0;bottom:0;display:grid;grid-template-rows:calc(12vw + 2px) auto}main.theme-light{--highlight-color: #eee;--text-color: black;background-color:white}main.theme-dark{--highlight-color: #444;--text-color: white;background-color:#22262e}main.theme-black{--highlight-color: #222;--text-color: white;background-color:black}.icon{width:100%;height:100%;background-color:var(--text-color);mask-size:contain;-webkit-mask-size:contain;mask-image:var(--icon-image);-webkit-mask-image:var(--icon-image)}.icon.icon-settings{--icon-image: url(../res/settings.svg)}.icon.icon-recent{--icon-image: url(../res/recent.svg)}nav{display:flex;overflow-x:auto}nav>a{border-bottom:2px solid transparent}nav>a.visible{border-bottom-color:green}nav>a>div.sticker{width:12vw;height:12vw}div.pack-list,nav{scrollbar-width:none}div.pack-list::-webkit-scrollbar,nav::-webkit-scrollbar{display:none}div.pack-list{overflow-y:auto}div.pack-list.ios-safari-hack{position:fixed;top:calc(12vw + 2px);bottom:0;left:0;right:0;-webkit-overflow-scrolling:touch}section.stickerpack{margin-top:.75rem}section.stickerpack>div.sticker-list{display:flex;flex-wrap:wrap}section.stickerpack>h1{margin:0 0 0 .75rem}div.sticker{display:flex;padding:4px;cursor:pointer;position:relative;width:var(--sticker-size);height:var(--sticker-size);box-sizing:border-box}div.sticker:hover{background-color:var(--highlight-color)}div.sticker>img{display:none;width:100%;object-fit:contain}div.sticker>img.visible{display:initial}div.sticker>.icon{width:70%;height:70%;margin:15%}div.settings-list{display:flex;flex-direction:column}div.settings-list>*{margin:.5rem}div.settings-list button{padding:.5rem;border-radius:.25rem}div.settings-list input{width:100%} *{font-family:sans-serif}body{margin:0}h1{font-size:1rem}:root{--stickers-per-row: 4;--sticker-size: calc(100vw / var(--stickers-per-row))}main{color:var(--text-color)}main.spinner{margin-top:5rem}main.error,main.empty{margin:2rem}main.empty{text-align:center}main.has-content{position:fixed;top:0;left:0;right:0;bottom:0;display:grid;grid-template-rows:calc(12vw + 2px) min-content auto}main.theme-light{--highlight-color: #eee;--search-box-color: var(--highlight-color);--text-color: black;background-color:#fff}main.theme-dark{--highlight-color: #444;--search-box-color: #383e4b;--text-color: white;background-color:#22262e}main.theme-black{--highlight-color: #222;--search-box-color: var(--highlight-color);--text-color: white;background-color:#000}.icon{width:100%;height:100%;background-color:var(--text-color);mask-size:contain;-webkit-mask-size:contain;mask-image:var(--icon-image);-webkit-mask-image:var(--icon-image)}.icon.icon-settings{--icon-image: url(../res/settings.svg)}.icon.icon-recent{--icon-image: url(../res/recent.svg)}.icon.icon-search{--icon-image: url(../res/search.svg)}.icon.icon-reset{--icon-image: url(../res/reset.svg)}nav{display:flex;overflow-x:auto}nav>a{border-bottom:2px solid transparent}nav>a.visible{border-bottom-color:green}nav>a>div.sticker{width:12vw;height:12vw}div.pack-list,nav{scrollbar-width:none}div.pack-list::-webkit-scrollbar,nav::-webkit-scrollbar{display:none}div.pack-list{overflow-y:auto}div.pack-list.ios-safari-hack{position:fixed;top:calc(calc(12vw + 2px) + calc(2 * 0.7rem + 2 * 0.5rem + 1rem));bottom:0;left:0;right:0;-webkit-overflow-scrolling:touch}div.search-empty{margin:1.2rem;text-align:center}section.stickerpack{margin-top:.75rem}section.stickerpack>div.sticker-list{display:flex;flex-wrap:wrap}section.stickerpack>h1{margin:0 0 0 .75rem}div.sticker{display:flex;padding:4px;cursor:pointer;position:relative;width:var(--sticker-size);height:var(--sticker-size);box-sizing:border-box}div.sticker:hover{background-color:var(--highlight-color)}div.sticker>img{display:none;width:100%;object-fit:contain}div.sticker>img.visible{display:initial}div.sticker>.icon{width:70%;height:70%;margin:15%}div.search-box{display:flex;margin:.5rem;padding:0;border-radius:.4rem;background-color:var(--search-box-color);opacity:.5;transition:all .1s;border:1px solid transparent}div.search-box:focus-within{opacity:1;border:1px solid var(--text-color)}div.search-box:not(:focus-within):hover{opacity:.7}div.search-box input,div.search-box .icon-display{color:var(--text-color);outline:none;border:none;height:1rem;margin:0;padding:.7rem;background-color:transparent;-webkit-tap-highlight-color:transparent}div.search-box .icon-display{width:1rem}div.search-box .icon-display.reset-click-zone{cursor:pointer}div.search-box .icon-display .icon{display:block;width:1rem;height:1rem}div.search-box .icon-display .icon-search{opacity:.5}div.search-box input{flex-grow:1;font-size:1rem}div.settings-list{display:flex;flex-direction:column}div.settings-list>*{margin:.5rem}div.settings-list button{padding:.5rem;border-radius:.25rem}div.settings-list input:not([type=checkbox]){width:100%}

View File

@ -32,6 +32,12 @@ $nav-bottom-highlight: 2px
$nav-height: calc(#{$nav-sticker-size} + #{$nav-bottom-highlight}) $nav-height: calc(#{$nav-sticker-size} + #{$nav-bottom-highlight})
$nav-height-inverse: calc(-#{$nav-sticker-size} - #{$nav-bottom-highlight}) $nav-height-inverse: calc(-#{$nav-sticker-size} - #{$nav-bottom-highlight})
$search-box-icon-size: 1rem
$search-box-input-height: 1rem
$search-box-input-padding: .7rem
$search-box-input-margin: .5rem
$search-box-height: calc(2 * #{$search-box-input-padding} + 2 * #{$search-box-input-margin} + #{$search-box-input-height})
main main
color: var(--text-color) color: var(--text-color)
@ -50,22 +56,24 @@ main
left: 0 left: 0
right: 0 right: 0
bottom: 0 bottom: 0
display: grid display: grid
grid-template-rows: $nav-height auto grid-template-rows: $nav-height min-content auto
main.theme-light main.theme-light
--highlight-color: #eee --highlight-color: #eee
--search-box-color: var(--highlight-color)
--text-color: black --text-color: black
background-color: white background-color: white
main.theme-dark main.theme-dark
--highlight-color: #444 --highlight-color: #444
--search-box-color: #383e4b
--text-color: white --text-color: white
background-color: #22262e background-color: #22262e
main.theme-black main.theme-black
--highlight-color: #222 --highlight-color: #222
--search-box-color: var(--highlight-color)
--text-color: white --text-color: white
background-color: black background-color: black
@ -84,6 +92,12 @@ main.theme-black
&.icon-recent &.icon-recent
--icon-image: url(../res/recent.svg) --icon-image: url(../res/recent.svg)
&.icon-search
--icon-image: url(../res/search.svg)
&.icon-reset
--icon-image: url(../res/reset.svg)
nav nav
display: flex display: flex
overflow-x: auto overflow-x: auto
@ -109,12 +123,16 @@ div.pack-list
div.pack-list.ios-safari-hack div.pack-list.ios-safari-hack
position: fixed position: fixed
top: $nav-height top: calc(#{$nav-height} + #{$search-box-height})
bottom: 0 bottom: 0
left: 0 left: 0
right: 0 right: 0
-webkit-overflow-scrolling: touch -webkit-overflow-scrolling: touch
div.search-empty
margin: 1.2rem
text-align: center
section.stickerpack section.stickerpack
margin-top: .75rem margin-top: .75rem
@ -150,6 +168,51 @@ div.sticker
height: 70% height: 70%
margin: 15% margin: 15%
div.search-box
display: flex
margin: $search-box-input-margin
padding: 0
border-radius: .4rem
background-color: var(--search-box-color)
opacity: .5
transition: all .1s
border: 1px solid transparent
&:focus-within
opacity: 1
border: 1px solid var(--text-color)
&:not(:focus-within):hover
opacity: .7
input,.icon-display
color: var(--text-color)
outline: none
border: none
height: $search-box-input-height
margin: 0
padding: $search-box-input-padding
background-color: transparent
-webkit-tap-highlight-color: transparent
.icon-display
width: $search-box-input-height
&.reset-click-zone
cursor: pointer
.icon
display: block
width: $search-box-icon-size
height: $search-box-icon-size
.icon-search
opacity: .5
input
flex-grow: 1
font-size: 1rem
div.settings-list div.settings-list
display: flex display: flex
flex-direction: column flex-direction: column
@ -161,5 +224,5 @@ div.settings-list
padding: .5rem padding: .5rem
border-radius: .25rem border-radius: .25rem
input input:not([type="checkbox"])
width: 100% width: 100%

View File

@ -1 +1 @@
.sk-center-wrapper{width:100%;display:flex;justify-content:space-around}.sk-chase{position:relative;animation:sk-chase 2.5s infinite linear both}.sk-chase.green>.sk-chase-dot:before{background-color:#00C853}.sk-chase>.sk-chase-dot{width:100%;height:100%;position:absolute;left:0;top:0;animation:sk-chase-dot 2.0s infinite ease-in-out both}.sk-chase>.sk-chase-dot:before{content:'';display:block;width:25%;height:25%;border-radius:100%;animation:sk-chase-dot-before 2.0s infinite ease-in-out both;background-color:#FFF}.sk-chase>.sk-chase-dot:nth-child(1){animation-delay:-1.1s}.sk-chase>.sk-chase-dot:nth-child(2){animation-delay:-1.0s}.sk-chase>.sk-chase-dot:nth-child(3){animation-delay:-0.9s}.sk-chase>.sk-chase-dot:nth-child(4){animation-delay:-0.8s}.sk-chase>.sk-chase-dot:nth-child(5){animation-delay:-0.7s}.sk-chase>.sk-chase-dot:nth-child(6){animation-delay:-0.6s}.sk-chase>.sk-chase-dot:nth-child(1):before{animation-delay:-1.1s}.sk-chase>.sk-chase-dot:nth-child(2):before{animation-delay:-1.0s}.sk-chase>.sk-chase-dot:nth-child(3):before{animation-delay:-0.9s}.sk-chase>.sk-chase-dot:nth-child(4):before{animation-delay:-0.8s}.sk-chase>.sk-chase-dot:nth-child(5):before{animation-delay:-0.7s}.sk-chase>.sk-chase-dot:nth-child(6):before{animation-delay:-0.6s}@keyframes sk-chase{100%{transform:rotate(360deg)}}@keyframes sk-chase-dot{80%,100%{transform:rotate(360deg)}}@keyframes sk-chase-dot-before{50%{transform:scale(0.4)}100%,0%{transform:scale(1)}} .sk-center-wrapper{width:100%;display:flex;justify-content:space-around}.sk-chase{position:relative;animation:sk-chase 2.5s infinite linear both}.sk-chase.green>.sk-chase-dot:before{background-color:#00c853}.sk-chase>.sk-chase-dot{width:100%;height:100%;position:absolute;left:0;top:0;animation:sk-chase-dot 2s infinite ease-in-out both}.sk-chase>.sk-chase-dot:before{content:"";display:block;width:25%;height:25%;border-radius:100%;animation:sk-chase-dot-before 2s infinite ease-in-out both;background-color:#fff}.sk-chase>.sk-chase-dot:nth-child(1){animation-delay:-1.1s}.sk-chase>.sk-chase-dot:nth-child(2){animation-delay:-1s}.sk-chase>.sk-chase-dot:nth-child(3){animation-delay:-0.9s}.sk-chase>.sk-chase-dot:nth-child(4){animation-delay:-0.8s}.sk-chase>.sk-chase-dot:nth-child(5){animation-delay:-0.7s}.sk-chase>.sk-chase-dot:nth-child(6){animation-delay:-0.6s}.sk-chase>.sk-chase-dot:nth-child(1):before{animation-delay:-1.1s}.sk-chase>.sk-chase-dot:nth-child(2):before{animation-delay:-1s}.sk-chase>.sk-chase-dot:nth-child(3):before{animation-delay:-0.9s}.sk-chase>.sk-chase-dot:nth-child(4):before{animation-delay:-0.8s}.sk-chase>.sk-chase-dot:nth-child(5):before{animation-delay:-0.7s}.sk-chase>.sk-chase-dot:nth-child(6):before{animation-delay:-0.6s}@keyframes sk-chase{100%{transform:rotate(360deg)}}@keyframes sk-chase-dot{80%,100%{transform:rotate(360deg)}}@keyframes sk-chase-dot-before{50%{transform:scale(0.4)}100%,0%{transform:scale(1)}}

File diff suppressed because it is too large Load Diff